File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1347: download - view: text, annotated - select for diffs
Mon Aug 7 20:22:54 2017 UTC (6 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Trust Settings
  Check if action is permissible based on trust settings for:
  catalog, domroles, enroll, reqcrs, msg, othcoau, or coaurem for current context.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1347 2017/08/07 20:22:54 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: 
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 20;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_servercerts_info {
  233:     my ($lonhost,$context) = @_;
  234:     my ($rep,$uselocal);
  235:     if (grep { $_ eq $lonhost } &current_machine_ids()) {
  236:         $uselocal = 1;
  237:     }
  238:     if (($context ne 'cgi') && ($uselocal)) {
  239:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  240:         if ($distro eq '') {
  241:             $uselocal = 0;
  242:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  243:             if ($1 < 6) {
  244:                 $uselocal = 0;
  245:             }
  246:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  247:             if ($1 < 12) {
  248:                 $uselocal = 0;
  249:             }
  250:         }
  251:     }
  252:     if ($uselocal) {
  253:         $rep = LONCAPA::Lond::server_certs(\%perlvar);
  254:     } else {
  255:         $rep=&reply('servercerts',$lonhost);
  256:     }
  257:     my ($result,%returnhash);
  258:     if (defined($lonhost)) {
  259:         if (!defined(&hostname($lonhost))) {
  260:             return;
  261:         }
  262:     }
  263:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  264:         ($rep eq 'unknown_cmd')) {
  265:         $result = $rep;
  266:     } else {
  267:         $result = 'ok';
  268:         my @pairs=split(/\&/,$rep);
  269:         foreach my $item (@pairs) {
  270:             my ($key,$value)=split(/=/,$item,2);
  271:             my $what = &unescape($key);
  272:             $returnhash{$what}=&thaw_unescape($value);
  273:         }
  274:     }
  275:     return ($result,\%returnhash);
  276: }
  277: 
  278: sub get_server_loncaparev {
  279:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  280:     if (defined($lonhost)) {
  281:         if (!defined(&hostname($lonhost))) {
  282:             undef($lonhost);
  283:         }
  284:     }
  285:     if (!defined($lonhost)) {
  286:         if (defined(&domain($dom,'primary'))) {
  287:             $lonhost=&domain($dom,'primary');
  288:             if ($lonhost eq 'no_host') {
  289:                 undef($lonhost);
  290:             }
  291:         }
  292:     }
  293:     if (defined($lonhost)) {
  294:         my $cachetime = 12*3600;
  295:         if (!$ignore_cache) {
  296:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  297:             if (defined($cached)) {
  298:                 return $loncaparev;
  299:             }
  300:         }
  301:         my ($answer,$loncaparev);
  302:         my @ids=&current_machine_ids();
  303:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  304:             $answer = $perlvar{'lonVersion'};
  305:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  306:                 $loncaparev = $1;
  307:             }
  308:         } else {
  309:             $answer = &reply('serverloncaparev',$lonhost);
  310:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  311:                 if ($caller eq 'loncron') {
  312:                     my $protocol = $protocol{$lonhost};
  313:                     $protocol = 'http' if ($protocol ne 'https');
  314:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  315:                     my $request=new HTTP::Request('GET',$url);
  316:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  317:                     unless ($response->is_error()) {
  318:                         my $content = $response->content;
  319:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  320:                             $loncaparev = $1;
  321:                         }
  322:                     }
  323:                 } else {
  324:                     $loncaparev = $loncaparevs{$lonhost};
  325:                 }
  326:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  327:                 $loncaparev = $1;
  328:             }
  329:         }
  330:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  331:     }
  332: }
  333: 
  334: sub get_server_homeID {
  335:     my ($hostname,$ignore_cache,$caller) = @_;
  336:     unless ($ignore_cache) {
  337:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  338:         if (defined($cached)) {
  339:             return $serverhomeID;
  340:         }
  341:     }
  342:     my $cachetime = 12*3600;
  343:     my $serverhomeID;
  344:     if ($caller eq 'loncron') { 
  345:         my @machine_ids = &machine_ids($hostname);
  346:         foreach my $id (@machine_ids) {
  347:             my $response = &reply('serverhomeID',$id);
  348:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  349:                 $serverhomeID = $response;
  350:                 last;
  351:             }
  352:         }
  353:         if ($serverhomeID eq '') {
  354:             $serverhomeID = $machine_ids[-1];
  355:         }
  356:     } else {
  357:         $serverhomeID = $serverhomeIDs{$hostname};
  358:     }
  359:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  360: }
  361: 
  362: sub get_remote_globals {
  363:     my ($lonhost,$whathash,$ignore_cache) = @_;
  364:     my ($result,%returnhash,%whatneeded);
  365:     if (ref($whathash) eq 'HASH') {
  366:         foreach my $what (sort(keys(%{$whathash}))) {
  367:             my $hashid = $lonhost.'-'.$what;
  368:             my ($response,$cached);
  369:             unless ($ignore_cache) {
  370:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  371:             }
  372:             if (defined($cached)) {
  373:                 $returnhash{$what} = $response;
  374:             } else {
  375:                 $whatneeded{$what} = 1;
  376:             }
  377:         }
  378:         if (keys(%whatneeded) == 0) {
  379:             $result = 'ok';
  380:         } else {
  381:             my $requested = &freeze_escape(\%whatneeded);
  382:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  383:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  384:                 ($rep eq 'unknown_cmd')) {
  385:                 $result = $rep;
  386:             } else {
  387:                 $result = 'ok';
  388:                 my @pairs=split(/\&/,$rep);
  389:                 foreach my $item (@pairs) {
  390:                     my ($key,$value)=split(/=/,$item,2);
  391:                     my $what = &unescape($key);
  392:                     my $hashid = $lonhost.'-'.$what;
  393:                     $returnhash{$what}=&thaw_unescape($value);
  394:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  395:                 }
  396:             }
  397:         }
  398:     }
  399:     return ($result,\%returnhash);
  400: }
  401: 
  402: sub remote_devalidate_cache {
  403:     my ($lonhost,$cachekeys) = @_;
  404:     my $items;
  405:     return unless (ref($cachekeys) eq 'ARRAY');
  406:     my $cachestr = join('&',@{$cachekeys});
  407:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  408:     return $response;
  409: }
  410: 
  411: # -------------------------------------------------- Non-critical communication
  412: sub subreply {
  413:     my ($cmd,$server)=@_;
  414:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  415:     #
  416:     #  With loncnew process trimming, there's a timing hole between lonc server
  417:     #  process exit and the master server picking up the listen on the AF_UNIX
  418:     #  socket.  In that time interval, a lock file will exist:
  419: 
  420:     my $lockfile=$peerfile.".lock";
  421:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  422: 	sleep(0.1);
  423:     }
  424:     # At this point, either a loncnew parent is listening or an old lonc
  425:     # or loncnew child is listening so we can connect or everything's dead.
  426:     #
  427:     #   We'll give the connection a few tries before abandoning it.  If
  428:     #   connection is not possible, we'll con_lost back to the client.
  429:     #   
  430:     my $client;
  431:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  432: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  433: 				      Type    => SOCK_STREAM,
  434: 				      Timeout => 10);
  435: 	if ($client) {
  436: 	    last;		# Connected!
  437: 	} else {
  438: 	    &create_connection(&hostname($server),$server);
  439: 	}
  440:         sleep(0.1);	# Try again later if failed connection.
  441:     }
  442:     my $answer;
  443:     if ($client) {
  444: 	print $client "sethost:$server:$cmd\n";
  445: 	$answer=<$client>;
  446: 	if (!$answer) { $answer="con_lost"; }
  447: 	chomp($answer);
  448:     } else {
  449: 	$answer = 'con_lost';	# Failed connection.
  450:     }
  451:     return $answer;
  452: }
  453: 
  454: sub reply {
  455:     my ($cmd,$server)=@_;
  456:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  457:     my $answer=subreply($cmd,$server);
  458:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  459:        &logthis("<font color=\"blue\">WARNING:".
  460:                 " $cmd to $server returned $answer</font>");
  461:     }
  462:     return $answer;
  463: }
  464: 
  465: # ----------------------------------------------------------- Send USR1 to lonc
  466: 
  467: sub reconlonc {
  468:     my ($lonid) = @_;
  469:     if ($lonid) {
  470:         my $hostname = &hostname($lonid);
  471: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  472: 	if ($hostname && -e $peerfile) {
  473: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  474: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  475: 					     Type    => SOCK_STREAM,
  476: 					     Timeout => 10);
  477: 	    if ($client) {
  478: 		print $client ("reset_retries\n");
  479: 		my $answer=<$client>;
  480: 		#reset just this one.
  481: 	    }
  482: 	}
  483: 	return;
  484:     }
  485: 
  486:     &logthis("Trying to reconnect lonc");
  487:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  488:     if (open(my $fh,"<$loncfile")) {
  489: 	my $loncpid=<$fh>;
  490:         chomp($loncpid);
  491:         if (kill 0 => $loncpid) {
  492: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  493:             kill USR1 => $loncpid;
  494:             sleep 1;
  495:         } else {
  496: 	    &logthis(
  497:                "<font color=\"blue\">WARNING:".
  498:                " lonc at pid $loncpid not responding, giving up</font>");
  499:         }
  500:     } else {
  501: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  502:     }
  503: }
  504: 
  505: # ------------------------------------------------------ Critical communication
  506: 
  507: sub critical {
  508:     my ($cmd,$server)=@_;
  509:     unless (&hostname($server)) {
  510:         &logthis("<font color=\"blue\">WARNING:".
  511:                " Critical message to unknown server ($server)</font>");
  512:         return 'no_such_host';
  513:     }
  514:     my $answer=reply($cmd,$server);
  515:     if ($answer eq 'con_lost') {
  516: 	&reconlonc($server);
  517: 	my $answer=reply($cmd,$server);
  518:         if ($answer eq 'con_lost') {
  519:             my $now=time;
  520:             my $middlename=$cmd;
  521:             $middlename=substr($middlename,0,16);
  522:             $middlename=~s/\W//g;
  523:             my $dfilename=
  524:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  525:             $dumpcount++;
  526:             {
  527: 		my $dfh;
  528: 		if (open($dfh,">$dfilename")) {
  529: 		    print $dfh "$cmd\n"; 
  530: 		    close($dfh);
  531: 		}
  532:             }
  533:             sleep 1;
  534:             my $wcmd='';
  535:             {
  536: 		my $dfh;
  537: 		if (open($dfh,"<$dfilename")) {
  538: 		    $wcmd=<$dfh>; 
  539: 		    close($dfh);
  540: 		}
  541:             }
  542:             chomp($wcmd);
  543:             if ($wcmd eq $cmd) {
  544: 		&logthis("<font color=\"blue\">WARNING: ".
  545:                          "Connection buffer $dfilename: $cmd</font>");
  546:                 &logperm("D:$server:$cmd");
  547: 	        return 'con_delayed';
  548:             } else {
  549:                 &logthis("<font color=\"red\">CRITICAL:"
  550:                         ." Critical connection failed: $server $cmd</font>");
  551:                 &logperm("F:$server:$cmd");
  552:                 return 'con_failed';
  553:             }
  554:         }
  555:     }
  556:     return $answer;
  557: }
  558: 
  559: # ------------------------------------------- check if return value is an error
  560: 
  561: sub error {
  562:     my ($result) = @_;
  563:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  564: 	if ($2 == 2) { return undef; }
  565: 	return $1;
  566:     }
  567:     return undef;
  568: }
  569: 
  570: sub convert_and_load_session_env {
  571:     my ($lonidsdir,$handle)=@_;
  572:     my @profile;
  573:     {
  574: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  575: 	if (!$opened) {
  576: 	    return 0;
  577: 	}
  578: 	flock($idf,LOCK_SH);
  579: 	@profile=<$idf>;
  580: 	close($idf);
  581:     }
  582:     my %temp_env;
  583:     foreach my $line (@profile) {
  584: 	if ($line !~ m/=/) {
  585: 	    return 0;
  586: 	}
  587: 	chomp($line);
  588: 	my ($envname,$envvalue)=split(/=/,$line,2);
  589: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  590:     }
  591:     unlink("$lonidsdir/$handle.id");
  592:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  593: 	    0640)) {
  594: 	%disk_env = %temp_env;
  595: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  596: 	untie(%disk_env);
  597:     }
  598:     return 1;
  599: }
  600: 
  601: # ------------------------------------------- Transfer profile into environment
  602: my $env_loaded;
  603: sub transfer_profile_to_env {
  604:     my ($lonidsdir,$handle,$force_transfer) = @_;
  605:     if (!$force_transfer && $env_loaded) { return; } 
  606: 
  607:     if (!defined($lonidsdir)) {
  608: 	$lonidsdir = $perlvar{'lonIDsDir'};
  609:     }
  610:     if (!defined($handle)) {
  611:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  612:     }
  613: 
  614:     my $convert;
  615:     {
  616:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  617: 	if (!$opened) {
  618: 	    return;
  619: 	}
  620: 	flock($idf,LOCK_SH);
  621: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  622: 		&GDBM_READER(),0640)) {
  623: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  624: 	    untie(%disk_env);
  625: 	} else {
  626: 	    $convert = 1;
  627: 	}
  628:     }
  629:     if ($convert) {
  630: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  631: 	    &logthis("Failed to load session, or convert session.");
  632: 	}
  633:     }
  634: 
  635:     my %remove;
  636:     while ( my $envname = each(%env) ) {
  637:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  638:             if ($time < time-300) {
  639:                 $remove{$key}++;
  640:             }
  641:         }
  642:     }
  643: 
  644:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  645:     $env_loaded=1;
  646:     foreach my $expired_key (keys(%remove)) {
  647:         &delenv($expired_key);
  648:     }
  649: }
  650: 
  651: # ---------------------------------------------------- Check for valid session 
  652: sub check_for_valid_session {
  653:     my ($r,$name,$userhashref) = @_;
  654:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  655:     my ($linkname,$pubname);
  656:     if ($name eq '') {
  657:         $name = 'lonID';
  658:         $linkname = 'lonLinkID';
  659:         $pubname = 'lonPubID';
  660:     }
  661:     my $lonid=$cookies{$name};
  662:     if (!$lonid) {
  663:         if (($name eq 'lonID') && ($ENV{'SERVER_PORT'} != 443) && ($linkname)) {
  664:             $lonid=$cookies{$linkname};
  665:         }
  666:         if (!$lonid) {
  667:             if (($name eq 'lonID') && ($pubname)) {
  668:                 $lonid=$cookies{$pubname};
  669:             }
  670:         }
  671:     }
  672:     return undef if (!$lonid);
  673: 
  674:     my $handle=&LONCAPA::clean_handle($lonid->value);
  675:     my $lonidsdir;
  676:     if ($name eq 'lonDAV') {
  677:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  678:     } else {
  679:         $lonidsdir=$r->dir_config('lonIDsDir');
  680:     }
  681:     return undef if (!-e "$lonidsdir/$handle.id");
  682: 
  683:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  684:     return undef if (!$opened);
  685: 
  686:     flock($idf,LOCK_SH);
  687:     my %disk_env;
  688:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  689: 	    &GDBM_READER(),0640)) {
  690: 	return undef;	
  691:     }
  692: 
  693:     if (!defined($disk_env{'user.name'})
  694: 	|| !defined($disk_env{'user.domain'})) {
  695: 	return undef;
  696:     }
  697: 
  698:     if (ref($userhashref) eq 'HASH') {
  699:         $userhashref->{'name'} = $disk_env{'user.name'};
  700:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  701:     }
  702: 
  703:     return $handle;
  704: }
  705: 
  706: sub timed_flock {
  707:     my ($file,$lock_type) = @_;
  708:     my $failed=0;
  709:     eval {
  710: 	local $SIG{__DIE__}='DEFAULT';
  711: 	local $SIG{ALRM}=sub {
  712: 	    $failed=1;
  713: 	    die("failed lock");
  714: 	};
  715: 	alarm(13);
  716: 	flock($file,$lock_type);
  717: 	alarm(0);
  718:     };
  719:     if ($failed) {
  720: 	return undef;
  721:     } else {
  722: 	return 1;
  723:     }
  724: }
  725: 
  726: # ---------------------------------------------------------- Append Environment
  727: 
  728: sub appenv {
  729:     my ($newenv,$roles) = @_;
  730:     if (ref($newenv) eq 'HASH') {
  731:         foreach my $key (keys(%{$newenv})) {
  732:             my $refused = 0;
  733: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  734:                 $refused = 1;
  735:                 if (ref($roles) eq 'ARRAY') {
  736:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  737:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  738:                         $refused = 0;
  739:                     }
  740:                 }
  741:             }
  742:             if ($refused) {
  743:                 &logthis("<font color=\"blue\">WARNING: ".
  744:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  745:                          .'</font>');
  746: 	        delete($newenv->{$key});
  747:             } else {
  748:                 $env{$key}=$newenv->{$key};
  749:             }
  750:         }
  751:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  752:         if ($opened
  753: 	    && &timed_flock($env_file,LOCK_EX)
  754: 	    &&
  755: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  756: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  757: 	    while (my ($key,$value) = each(%{$newenv})) {
  758: 	        $disk_env{$key} = $value;
  759: 	    }
  760: 	    untie(%disk_env);
  761:         }
  762:     }
  763:     return 'ok';
  764: }
  765: # ----------------------------------------------------- Delete from Environment
  766: 
  767: sub delenv {
  768:     my ($delthis,$regexp,$roles) = @_;
  769:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  770:         my $refused = 1;
  771:         if (ref($roles) eq 'ARRAY') {
  772:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  773:             if (grep(/^\Q$role\E$/,@{$roles})) {
  774:                 $refused = 0;
  775:             }
  776:         }
  777:         if ($refused) {
  778:             &logthis("<font color=\"blue\">WARNING: ".
  779:                      "Attempt to delete from environment ".$delthis);
  780:             return 'error';
  781:         }
  782:     }
  783:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  784:     if ($opened
  785: 	&& &timed_flock($env_file,LOCK_EX)
  786: 	&&
  787: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  788: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  789: 	foreach my $key (keys(%disk_env)) {
  790: 	    if ($regexp) {
  791:                 if ($key=~/^$delthis/) {
  792:                     delete($env{$key});
  793:                     delete($disk_env{$key});
  794:                 } 
  795:             } else {
  796:                 if ($key=~/^\Q$delthis\E/) {
  797: 		    delete($env{$key});
  798: 		    delete($disk_env{$key});
  799: 	        }
  800:             }
  801: 	}
  802: 	untie(%disk_env);
  803:     }
  804:     return 'ok';
  805: }
  806: 
  807: sub get_env_multiple {
  808:     my ($name) = @_;
  809:     my @values;
  810:     if (defined($env{$name})) {
  811:         # exists is it an array
  812:         if (ref($env{$name})) {
  813:             @values=@{ $env{$name} };
  814:         } else {
  815:             $values[0]=$env{$name};
  816:         }
  817:     }
  818:     return(@values);
  819: }
  820: 
  821: # ------------------------------------------------------------------- Locking
  822: 
  823: sub set_lock {
  824:     my ($text)=@_;
  825:     $locknum++;
  826:     my $id=$$.'-'.$locknum;
  827:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  828:              'session.lock.'.$id => $text});
  829:     return $id;
  830: }
  831: 
  832: sub get_locks {
  833:     my $num=0;
  834:     my %texts=();
  835:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  836:        if ($lock=~/\w/) {
  837:           $num++;
  838:           $texts{$lock}=$env{'session.lock.'.$lock};
  839:        }
  840:    }
  841:    return ($num,%texts);
  842: }
  843: 
  844: sub remove_lock {
  845:     my ($id)=@_;
  846:     my $newlocks='';
  847:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  848:        if (($lock=~/\w/) && ($lock ne $id)) {
  849:           $newlocks.=','.$lock;
  850:        }
  851:     }
  852:     &appenv({'session.locks' => $newlocks});
  853:     &delenv('session.lock.'.$id);
  854: }
  855: 
  856: sub remove_all_locks {
  857:     my $activelocks=$env{'session.locks'};
  858:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  859:        if ($lock=~/\w/) {
  860:           &remove_lock($lock);
  861:        }
  862:     }
  863: }
  864: 
  865: 
  866: # ------------------------------------------ Find out current server userload
  867: sub userload {
  868:     my $numusers=0;
  869:     {
  870: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  871: 	my $filename;
  872: 	my $curtime=time;
  873: 	while ($filename=readdir(LONIDS)) {
  874: 	    next if ($filename eq '.' || $filename eq '..');
  875: 	    next if ($filename =~ /publicuser_\d+\.id/);
  876: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  877: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  878: 	}
  879: 	closedir(LONIDS);
  880:     }
  881:     my $userloadpercent=0;
  882:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  883:     if ($maxuserload) {
  884: 	$userloadpercent=100*$numusers/$maxuserload;
  885:     }
  886:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  887:     return $userloadpercent;
  888: }
  889: 
  890: # ------------------------------ Find server with least workload from spare.tab
  891: 
  892: sub spareserver {
  893:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  894:     my $spare_server;
  895:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  896:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  897:                                                      :  $userloadpercent;
  898:     my ($uint_dom,$remotesessions);
  899:     if (($udom ne '') && (&domain($udom) ne '')) {
  900:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  901:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  902:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  903:         $remotesessions = $udomdefaults{'remotesessions'};
  904:     }
  905:     my $spareshash = &this_host_spares($udom);
  906:     if (ref($spareshash) eq 'HASH') {
  907:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  908:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  909:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  910:                                              $try_server));
  911: 	        ($spare_server, $lowest_load) =
  912: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  913:             }
  914:         }
  915: 
  916:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  917: 
  918:         if (!$found_server) {
  919:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  920: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  921:                     next unless (&spare_can_host($udom,$uint_dom,
  922:                                                  $remotesessions,$try_server));
  923: 	            ($spare_server, $lowest_load) =
  924: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  925:                 }
  926: 	    }
  927:         }
  928:     }
  929: 
  930:     if (!$want_server_name) {
  931:         my $protocol = 'http';
  932:         if ($protocol{$spare_server} eq 'https') {
  933:             $protocol = $protocol{$spare_server};
  934:         }
  935:         if (defined($spare_server)) {
  936:             my $hostname = &hostname($spare_server);
  937:             if (defined($hostname)) {
  938: 	        $spare_server = $protocol.'://'.$hostname;
  939:             }
  940:         }
  941:     }
  942:     return $spare_server;
  943: }
  944: 
  945: sub compare_server_load {
  946:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  947: 
  948:     if ($required) {
  949:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  950:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  951:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  952:         if (($major eq '' && $minor eq '') ||
  953:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  954:             return ($spare_server,$lowest_load);
  955:         }
  956:     }
  957: 
  958:     my $loadans     = &reply('load',    $try_server);
  959:     my $userloadans = &reply('userload',$try_server);
  960: 
  961:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  962: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  963:     }
  964: 
  965:     my $load;
  966:     if ($loadans =~ /\d/) {
  967: 	if ($userloadans =~ /\d/) {
  968: 	    #both are numbers, pick the bigger one
  969: 	    $load = ($loadans > $userloadans) ? $loadans 
  970: 		                              : $userloadans;
  971: 	} else {
  972: 	    $load = $loadans;
  973: 	}
  974:     } else {
  975: 	$load = $userloadans;
  976:     }
  977: 
  978:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  979: 	$spare_server = $try_server;
  980: 	$lowest_load  = $load;
  981:     }
  982:     return ($spare_server,$lowest_load);
  983: }
  984: 
  985: # --------------------------- ask offload servers if user already has a session
  986: sub find_existing_session {
  987:     my ($udom,$uname) = @_;
  988:     my $spareshash = &this_host_spares($udom);
  989:     if (ref($spareshash) eq 'HASH') {
  990:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  991:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  992:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  993:             }
  994:         }
  995:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  996:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  997:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  998:             }
  999:         }
 1000:     }
 1001:     return;
 1002: }
 1003: 
 1004: # -------------------------------- ask if server already has a session for user
 1005: sub has_user_session {
 1006:     my ($lonid,$udom,$uname) = @_;
 1007:     my $result = &reply(join(':','userhassession',
 1008: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1009:     return 1 if ($result eq 'ok');
 1010: 
 1011:     return 0;
 1012: }
 1013: 
 1014: # --------- determine least loaded server in a user's domain which allows login
 1015: 
 1016: sub choose_server {
 1017:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1018:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1019:     my %servers = &get_servers($udom);
 1020:     my $lowest_load = 30000;
 1021:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1022:     if ($skiploadbal) {
 1023:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1024:         unless (defined($cached)) {
 1025:             my $cachetime = 60*60*24;
 1026:             my %domconfig =
 1027:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1028:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1029:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1030:                                            $cachetime);
 1031:             }
 1032:         }
 1033:     }
 1034:     foreach my $lonhost (keys(%servers)) {
 1035:         if ($skiploadbal) {
 1036:             if (ref($balancers) eq 'HASH') {
 1037:                 next if (exists($balancers->{$lonhost}));
 1038:             }
 1039:         }   
 1040:         my $loginvia;
 1041:         if ($checkloginvia) {
 1042:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1043:             if ($loginvia) {
 1044:                 my ($server,$path) = split(/:/,$loginvia);
 1045:                 ($login_host, $lowest_load) =
 1046:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1047:                 if ($login_host eq $server) {
 1048:                     $portal_path = $path;
 1049:                     $isredirect = 1;
 1050:                 }
 1051:             } else {
 1052:                 ($login_host, $lowest_load) =
 1053:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1054:                 if ($login_host eq $lonhost) {
 1055:                     $portal_path = '';
 1056:                     $isredirect = ''; 
 1057:                 }
 1058:             }
 1059:         } else {
 1060:             ($login_host, $lowest_load) =
 1061:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1062:         }
 1063:     }
 1064:     if ($login_host ne '') {
 1065:         $hostname = &hostname($login_host);
 1066:     }
 1067:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1068: }
 1069: 
 1070: # --------------------------------------------- Try to change a user's password
 1071: 
 1072: sub changepass {
 1073:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1074:     $currentpass = &escape($currentpass);
 1075:     $newpass     = &escape($newpass);
 1076:     my $lonhost = $perlvar{'lonHostID'};
 1077:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1078: 		       $server);
 1079:     if (! $answer) {
 1080: 	&logthis("No reply on password change request to $server ".
 1081: 		 "by $uname in domain $udom.");
 1082:     } elsif ($answer =~ "^ok") {
 1083:         &logthis("$uname in $udom successfully changed their password ".
 1084: 		 "on $server.");
 1085:     } elsif ($answer =~ "^pwchange_failure") {
 1086: 	&logthis("$uname in $udom was unable to change their password ".
 1087: 		 "on $server.  The action was blocked by either lcpasswd ".
 1088: 		 "or pwchange");
 1089:     } elsif ($answer =~ "^non_authorized") {
 1090:         &logthis("$uname in $udom did not get their password correct when ".
 1091: 		 "attempting to change it on $server.");
 1092:     } elsif ($answer =~ "^auth_mode_error") {
 1093:         &logthis("$uname in $udom attempted to change their password despite ".
 1094: 		 "not being locally or internally authenticated on $server.");
 1095:     } elsif ($answer =~ "^unknown_user") {
 1096:         &logthis("$uname in $udom attempted to change their password ".
 1097: 		 "on $server but were unable to because $server is not ".
 1098: 		 "their home server.");
 1099:     } elsif ($answer =~ "^refused") {
 1100: 	&logthis("$server refused to change $uname in $udom password because ".
 1101: 		 "it was sent an unencrypted request to change the password.");
 1102:     } elsif ($answer =~ "invalid_client") {
 1103:         &logthis("$server refused to change $uname in $udom password because ".
 1104:                  "it was a reset by e-mail originating from an invalid server.");
 1105:     }
 1106:     return $answer;
 1107: }
 1108: 
 1109: # ----------------------- Try to determine user's current authentication scheme
 1110: 
 1111: sub queryauthenticate {
 1112:     my ($uname,$udom)=@_;
 1113:     my $uhome=&homeserver($uname,$udom);
 1114:     if (!$uhome) {
 1115: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1116: 	return 'no_host';
 1117:     }
 1118:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1119:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1120: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1121:     }
 1122:     return $answer;
 1123: }
 1124: 
 1125: # --------- Try to authenticate user from domain's lib servers (first this one)
 1126: 
 1127: sub authenticate {
 1128:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1129:     $upass=&escape($upass);
 1130:     $uname= &LONCAPA::clean_username($uname);
 1131:     my $uhome=&homeserver($uname,$udom,1);
 1132:     my $newhome;
 1133:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1134: # Maybe the machine was offline and only re-appeared again recently?
 1135:         &reconlonc();
 1136: # One more
 1137: 	$uhome=&homeserver($uname,$udom,1);
 1138:         if (($uhome eq 'no_host') && $checkdefauth) {
 1139:             if (defined(&domain($udom,'primary'))) {
 1140:                 $newhome=&domain($udom,'primary');
 1141:             }
 1142:             if ($newhome ne '') {
 1143:                 $uhome = $newhome;
 1144:             }
 1145:         }
 1146: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1147: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1148: 	    return 'no_host';
 1149:         }
 1150:     }
 1151:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1152:     if ($answer eq 'authorized') {
 1153:         if ($newhome) {
 1154:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1155:             return 'no_account_on_host'; 
 1156:         } else {
 1157:             &logthis("User $uname at $udom authorized by $uhome");
 1158:             return $uhome;
 1159:         }
 1160:     }
 1161:     if ($answer eq 'non_authorized') {
 1162: 	&logthis("User $uname at $udom rejected by $uhome");
 1163: 	return 'no_host'; 
 1164:     }
 1165:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1166:     return 'no_host';
 1167: }
 1168: 
 1169: sub can_host_session {
 1170:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1171:     my $canhost = 1;
 1172:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1173:     if (ref($remotesessions) eq 'HASH') {
 1174:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1175:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1176:                 $canhost = 0;
 1177:             } else {
 1178:                 $canhost = 1;
 1179:             }
 1180:         }
 1181:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1182:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1183:                 $canhost = 1;
 1184:             } else {
 1185:                 $canhost = 0;
 1186:             }
 1187:         }
 1188:         if ($canhost) {
 1189:             if ($remotesessions->{'version'} ne '') {
 1190:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1191:                 if ($reqmajor ne '' && $reqminor ne '') {
 1192:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1193:                         my $major = $1;
 1194:                         my $minor = $2;
 1195:                         if (($major < $reqmajor ) ||
 1196:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1197:                             $canhost = 0;
 1198:                         }
 1199:                     } else {
 1200:                         $canhost = 0;
 1201:                     }
 1202:                 }
 1203:             }
 1204:         }
 1205:     }
 1206:     if ($canhost) {
 1207:         if (ref($hostedsessions) eq 'HASH') {
 1208:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1209:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1210:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1211:                 if (($uint_dom ne '') && 
 1212:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1213:                     $canhost = 0;
 1214:                 } else {
 1215:                     $canhost = 1;
 1216:                 }
 1217:             }
 1218:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1219:                 if (($uint_dom ne '') && 
 1220:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1221:                     $canhost = 1;
 1222:                 } else {
 1223:                     $canhost = 0;
 1224:                 }
 1225:             }
 1226:         }
 1227:     }
 1228:     return $canhost;
 1229: }
 1230: 
 1231: sub spare_can_host {
 1232:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1233:     my $canhost=1;
 1234:     my $try_server_hostname = &hostname($try_server);
 1235:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1236:     my $serverhomedom = &host_domain($serverhomeID);
 1237:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1238:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1239:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1240:             $canhost = 0;
 1241:         }
 1242:     }
 1243:     if (($canhost) && ($uint_dom)) {
 1244:         my @intdoms;
 1245:         my $internet_names = &get_internet_names($try_server);
 1246:         if (ref($internet_names) eq 'ARRAY') {
 1247:             @intdoms = @{$internet_names};
 1248:         }
 1249:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1250:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1251:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1252:                                          $remotesessions,
 1253:                                          $defdomdefaults{'hostedsessions'});
 1254:         }
 1255:     }
 1256:     return $canhost;
 1257: }
 1258: 
 1259: sub this_host_spares {
 1260:     my ($dom) = @_;
 1261:     my ($dom_in_use,$lonhost_in_use,$result);
 1262:     my @hosts = &current_machine_ids();
 1263:     foreach my $lonhost (@hosts) {
 1264:         if (&host_domain($lonhost) eq $dom) {
 1265:             $dom_in_use = $dom;
 1266:             $lonhost_in_use = $lonhost;
 1267:             last;
 1268:         }
 1269:     }
 1270:     if ($dom_in_use ne '') {
 1271:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1272:     }
 1273:     if (ref($result) ne 'HASH') {
 1274:         $lonhost_in_use = $perlvar{'lonHostID'};
 1275:         $dom_in_use = &host_domain($lonhost_in_use);
 1276:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1277:         if (ref($result) ne 'HASH') {
 1278:             $result = \%spareid;
 1279:         }
 1280:     }
 1281:     return $result;
 1282: }
 1283: 
 1284: sub spares_for_offload  {
 1285:     my ($dom_in_use,$lonhost_in_use) = @_;
 1286:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1287:     if (defined($cached)) {
 1288:         return $result;
 1289:     } else {
 1290:         my $cachetime = 60*60*24;
 1291:         my %domconfig =
 1292:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1293:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1294:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1295:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1296:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1297:                 }
 1298:             }
 1299:         }
 1300:     }
 1301:     return;
 1302: }
 1303: 
 1304: sub get_lonbalancer_config {
 1305:     my ($servers) = @_;
 1306:     my ($currbalancer,$currtargets);
 1307:     if (ref($servers) eq 'HASH') {
 1308:         foreach my $server (keys(%{$servers})) {
 1309:             my %what = (
 1310:                          spareid => 1,
 1311:                          perlvar => 1,
 1312:                        );
 1313:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1314:             if ($result eq 'ok') {
 1315:                 if (ref($returnhash) eq 'HASH') {
 1316:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1317:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1318:                             $currbalancer = $server;
 1319:                             $currtargets = {};
 1320:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1321:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1322:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1323:                                 }
 1324:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1325:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1326:                                 }
 1327:                             }
 1328:                             last;
 1329:                         }
 1330:                     }
 1331:                 }
 1332:             }
 1333:         }
 1334:     }
 1335:     return ($currbalancer,$currtargets);
 1336: }
 1337: 
 1338: sub check_loadbalancing {
 1339:     my ($uname,$udom,$caller) = @_;
 1340:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1341:         $rule_in_effect,$offloadto,$otherserver);
 1342:     my $lonhost = $perlvar{'lonHostID'};
 1343:     my @hosts = &current_machine_ids();
 1344:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1345:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1346:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1347:     my $serverhomedom = &host_domain($lonhost);
 1348:     my $domneedscache;
 1349:     my $cachetime = 60*60*24;
 1350: 
 1351:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1352:         $dom_in_use = $udom;
 1353:         $homeintdom = 1;
 1354:     } else {
 1355:         $dom_in_use = $serverhomedom;
 1356:     }
 1357:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1358:     unless (defined($cached)) {
 1359:         my %domconfig =
 1360:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1361:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1362:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1363:         } else {
 1364:             $domneedscache = $dom_in_use;
 1365:         }
 1366:     }
 1367:     if (ref($result) eq 'HASH') {
 1368:         ($is_balancer,$currtargets,$currrules) = 
 1369:             &check_balancer_result($result,@hosts);
 1370:         if ($is_balancer) {
 1371:             if (ref($currrules) eq 'HASH') {
 1372:                 if ($homeintdom) {
 1373:                     if ($uname ne '') {
 1374:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1375:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1376:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1377:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1378:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1379:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1380:                             }
 1381:                         }
 1382:                         if ($rule_in_effect eq '') {
 1383:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1384:                             if ($userenv{'inststatus'} ne '') {
 1385:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1386:                                 my ($othertitle,$usertypes,$types) =
 1387:                                     &Apache::loncommon::sorted_inst_types($udom);
 1388:                                 if (ref($types) eq 'ARRAY') {
 1389:                                     foreach my $type (@{$types}) {
 1390:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1391:                                             if (exists($currrules->{$type})) {
 1392:                                                 $rule_in_effect = $currrules->{$type};
 1393:                                             }
 1394:                                         }
 1395:                                     }
 1396:                                 }
 1397:                             } else {
 1398:                                 if (exists($currrules->{'default'})) {
 1399:                                     $rule_in_effect = $currrules->{'default'};
 1400:                                 }
 1401:                             }
 1402:                         }
 1403:                     } else {
 1404:                         if (exists($currrules->{'default'})) {
 1405:                             $rule_in_effect = $currrules->{'default'};
 1406:                         }
 1407:                     }
 1408:                 } else {
 1409:                     if ($currrules->{'_LC_external'} ne '') {
 1410:                         $rule_in_effect = $currrules->{'_LC_external'};
 1411:                     }
 1412:                 }
 1413:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1414:                                                        $uname,$udom);
 1415:             }
 1416:         }
 1417:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1418:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1419:         unless (defined($cached)) {
 1420:             my %domconfig =
 1421:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1422:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1423:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1424:             } else {
 1425:                 $domneedscache = $serverhomedom;
 1426:             }
 1427:         }
 1428:         if (ref($result) eq 'HASH') {
 1429:             ($is_balancer,$currtargets,$currrules) = 
 1430:                 &check_balancer_result($result,@hosts);
 1431:             if ($is_balancer) {
 1432:                 if (ref($currrules) eq 'HASH') {
 1433:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1434:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1435:                     }
 1436:                 }
 1437:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1438:                                                        $uname,$udom);
 1439:             }
 1440:         } else {
 1441:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1442:                 $is_balancer = 1;
 1443:                 $offloadto = &this_host_spares($dom_in_use);
 1444:             }
 1445:             unless (defined($cached)) {
 1446:                 $domneedscache = $serverhomedom;
 1447:             }
 1448:         }
 1449:     } else {
 1450:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1451:             $is_balancer = 1;
 1452:             $offloadto = &this_host_spares($dom_in_use);
 1453:         }
 1454:         unless (defined($cached)) {
 1455:             $domneedscache = $serverhomedom;
 1456:         }
 1457:     }
 1458:     if ($domneedscache) {
 1459:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1460:     }
 1461:     if ($is_balancer) {
 1462:         my $lowest_load = 30000;
 1463:         if (ref($offloadto) eq 'HASH') {
 1464:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1465:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1466:                     ($otherserver,$lowest_load) =
 1467:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1468:                 }
 1469:             }
 1470:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1471: 
 1472:             if (!$found_server) {
 1473:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1474:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1475:                         ($otherserver,$lowest_load) =
 1476:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1477:                     }
 1478:                 }
 1479:             }
 1480:         } elsif (ref($offloadto) eq 'ARRAY') {
 1481:             if (@{$offloadto} == 1) {
 1482:                 $otherserver = $offloadto->[0];
 1483:             } elsif (@{$offloadto} > 1) {
 1484:                 foreach my $try_server (@{$offloadto}) {
 1485:                     ($otherserver,$lowest_load) =
 1486:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1487:                 }
 1488:             }
 1489:         }
 1490:         unless ($caller eq 'login') {
 1491:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1492:                 $is_balancer = 0;
 1493:                 if ($uname ne '' && $udom ne '') {
 1494:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1495:                     
 1496:                         &appenv({'user.loadbalexempt'     => $lonhost,  
 1497:                                  'user.loadbalcheck.time' => time});
 1498:                     }
 1499:                 }
 1500:             }
 1501:         }
 1502:     }
 1503:     return ($is_balancer,$otherserver);
 1504: }
 1505: 
 1506: sub check_balancer_result {
 1507:     my ($result,@hosts) = @_;
 1508:     my ($is_balancer,$currtargets,$currrules);
 1509:     if (ref($result) eq 'HASH') {
 1510:         if ($result->{'lonhost'} ne '') {
 1511:             my $currbalancer = $result->{'lonhost'};
 1512:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1513:                 $is_balancer = 1;
 1514:                 $currtargets = $result->{'targets'};
 1515:                 $currrules = $result->{'rules'};
 1516:             }
 1517:         } else {
 1518:             foreach my $key (keys(%{$result})) {
 1519:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1520:                     (ref($result->{$key}) eq 'HASH')) {
 1521:                     $is_balancer = 1;
 1522:                     $currrules = $result->{$key}{'rules'};
 1523:                     $currtargets = $result->{$key}{'targets'};
 1524:                     last;
 1525:                 }
 1526:             }
 1527:         }
 1528:     }
 1529:     return ($is_balancer,$currtargets,$currrules);
 1530: }
 1531: 
 1532: sub get_loadbalancer_targets {
 1533:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1534:     my $offloadto;
 1535:     if ($rule_in_effect eq 'none') {
 1536:         return [$perlvar{'lonHostID'}];
 1537:     } elsif ($rule_in_effect eq '') {
 1538:         $offloadto = $currtargets;
 1539:     } else {
 1540:         if ($rule_in_effect eq 'homeserver') {
 1541:             my $homeserver = &homeserver($uname,$udom);
 1542:             if ($homeserver ne 'no_host') {
 1543:                 $offloadto = [$homeserver];
 1544:             }
 1545:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1546:             my %domconfig =
 1547:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1548:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1549:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1550:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1551:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1552:                     }
 1553:                 }
 1554:             } else {
 1555:                 my %servers = &internet_dom_servers($udom);
 1556:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1557:                 if (&hostname($remotebalancer) ne '') {
 1558:                     $offloadto = [$remotebalancer];
 1559:                 }
 1560:             }
 1561:         } elsif (&hostname($rule_in_effect) ne '') {
 1562:             $offloadto = [$rule_in_effect];
 1563:         }
 1564:     }
 1565:     return $offloadto;
 1566: }
 1567: 
 1568: sub internet_dom_servers {
 1569:     my ($dom) = @_;
 1570:     my (%uniqservers,%servers);
 1571:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1572:     my @machinedoms = &machine_domains($primaryserver);
 1573:     foreach my $mdom (@machinedoms) {
 1574:         my %currservers = %servers;
 1575:         my %server = &get_servers($mdom);
 1576:         %servers = (%currservers,%server);
 1577:     }
 1578:     my %by_hostname;
 1579:     foreach my $id (keys(%servers)) {
 1580:         push(@{$by_hostname{$servers{$id}}},$id);
 1581:     }
 1582:     foreach my $hostname (sort(keys(%by_hostname))) {
 1583:         if (@{$by_hostname{$hostname}} > 1) {
 1584:             my $match = 0;
 1585:             foreach my $id (@{$by_hostname{$hostname}}) {
 1586:                 if (&host_domain($id) eq $dom) {
 1587:                     $uniqservers{$id} = $hostname;
 1588:                     $match = 1;
 1589:                 }
 1590:             }
 1591:             unless ($match) {
 1592:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1593:             }
 1594:         } else {
 1595:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1596:         }
 1597:     }
 1598:     return %uniqservers;
 1599: }
 1600: 
 1601: sub notcallable {
 1602:     my ($cmdtype,$calldom) = @_;
 1603:     if (&domain($calldom) eq '') {
 1604:         return 1;
 1605:     }
 1606:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1607:         return 1;
 1608:     }
 1609:     my @machinedoms = &current_machine_domains();
 1610:     if (grep(/^\Q$calldom\E$/,@machinedoms)) {
 1611:         return;
 1612:     }
 1613:     my $reject;
 1614:     my $intdom = &internet_dom($perlvar{'lonHostID'});
 1615:     if ($intdom eq '') {
 1616:         return 1;
 1617:     }
 1618:     my $callprimary = &domain($calldom,'primary');
 1619:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1620:     unless ($intdom eq $intcalldom) {
 1621:         my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1622:         unless (defined($cached)) {
 1623:             my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1624:             &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1625:             $trustconfig = $domconfig{'trust'};
 1626:         }
 1627:         if (ref($trustconfig)) {
 1628:             if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1629:                 if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1630:                     if (grep(/^\Q$intdom\E$/,@{$trustconfig->{$cmdtype}->{'exc'}})) {
 1631:                         $reject = 1;
 1632:                     }
 1633:                 }
 1634:                 if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1635:                     if (grep(/^\Q$intdom\E$/,@{$trustconfig->{$cmdtype}->{'inc'}})) {
 1636:                         $reject = 0;
 1637:                     } else {
 1638:                         $reject = 1;
 1639:                     }
 1640:                 }
 1641:             }
 1642:         }
 1643:     }
 1644:     return $reject;
 1645: }
 1646: 
 1647: sub trusted_domains {
 1648:     my ($cmdtype,$calldom) = @_;
 1649:     my (%trusted,%untrusted);
 1650:     if (&domain($calldom) eq '') {
 1651:         return (\%trusted,\%untrusted);
 1652:     }
 1653:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1654:         return (\%trusted,\%untrusted);
 1655:     }
 1656:     my $callprimary = &domain($calldom,'primary');
 1657:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1658:     if ($intcalldom eq '') {
 1659:         return (\%trusted,\%untrusted);
 1660:     }
 1661: 
 1662:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1663:     unless (defined($cached)) {
 1664:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1665:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1666:         $trustconfig = $domconfig{'trust'};
 1667:     }
 1668:     if (ref($trustconfig)) {
 1669:         my (%possexc,%possinc,@allexc,@allinc); 
 1670:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1671:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1672:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1673:             }
 1674:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1675:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1676:             }
 1677:         }
 1678:         if (keys(%possexc)) {
 1679:             if (keys(%possinc)) {
 1680:                 foreach my $key (sort(keys(%possexc))) {
 1681:                     next if ($key eq $intcalldom);
 1682:                     unless ($possinc{$key}) {
 1683:                         push(@allexc,$key);
 1684:                     }
 1685:                 }
 1686:             } else {
 1687:                 @allexc = sort(keys(%possexc));
 1688:             }
 1689:         }
 1690:         if (keys(%possinc)) {
 1691:             $possinc{$intcalldom} = 1;
 1692:             @allinc = sort(keys(%possinc));
 1693:         }
 1694:         if ((@allexc > 0) || (@allinc > 0)) {
 1695:             my %doms_by_intdom;
 1696:             my %allintdoms = &all_host_intdom();
 1697:             my %alldoms = &all_host_domain();
 1698:             foreach my $key (%allintdoms) {
 1699:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1700:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1701:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1702:                     }
 1703:                 } else {
 1704:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1705:                 }
 1706:             }
 1707:             foreach my $exc (@allexc) {
 1708:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1709:                     map { $untrusted{$_}; } @{$doms_by_intdom{$exc}};
 1710:                 }
 1711:             }
 1712:             foreach my $inc (@allinc) {
 1713:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1714:                     map { $trusted{$_}; } @{$doms_by_intdom{$inc}};
 1715:                 }
 1716:             }
 1717:         }
 1718:     }
 1719:     return(\%trusted,\%untrusted);
 1720: }
 1721: 
 1722: sub will_trust {
 1723:     my ($cmdtype,$domain,$possdom) = @_;
 1724:     return 1 if ($domain eq $possdom);
 1725:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1726:     my $willtrust; 
 1727:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1728:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1729:             $willtrust = 1;
 1730:         }
 1731:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1732:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1733:             $willtrust = 1;
 1734:         }
 1735:     } else {
 1736:         $willtrust = 1;
 1737:     }
 1738:     return $willtrust;
 1739: }
 1740: 
 1741: # ---------------------- Find the homebase for a user from domain's lib servers
 1742: 
 1743: my %homecache;
 1744: sub homeserver {
 1745:     my ($uname,$udom,$ignoreBadCache)=@_;
 1746:     my $index="$uname:$udom";
 1747: 
 1748:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1749: 
 1750:     my %servers = &get_servers($udom,'library');
 1751:     foreach my $tryserver (keys(%servers)) {
 1752:         next if ($ignoreBadCache ne 'true' && 
 1753: 		 exists($badServerCache{$tryserver}));
 1754: 
 1755: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1756: 	if ($answer eq 'found') {
 1757: 	    delete($badServerCache{$tryserver}); 
 1758: 	    return $homecache{$index}=$tryserver;
 1759: 	} elsif ($answer eq 'no_host') {
 1760: 	    $badServerCache{$tryserver}=1;
 1761: 	}
 1762:     }    
 1763:     return 'no_host';
 1764: }
 1765: 
 1766: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1767: 
 1768: sub idget {
 1769:     my ($udom,$idsref,$namespace)=@_;
 1770:     my %returnhash=();
 1771:     my @ids=(); 
 1772:     if (ref($idsref) eq 'ARRAY') {
 1773:         @ids = @{$idsref};
 1774:     } else {
 1775:         return %returnhash; 
 1776:     }
 1777:     if ($namespace eq '') {
 1778:         $namespace = 'ids';
 1779:     }
 1780:     
 1781:     my %servers = &get_servers($udom,'library');
 1782:     foreach my $tryserver (keys(%servers)) {
 1783: 	my $idlist=join('&', map { &escape($_); } @ids);
 1784: 	if ($namespace eq 'ids') {
 1785: 	    $idlist=~tr/A-Z/a-z/;
 1786: 	}
 1787: 	my $reply;
 1788: 	if ($namespace eq 'ids') {
 1789: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1790: 	} else {
 1791: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1792: 	}
 1793: 	my @answer=();
 1794: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1795: 	    @answer=split(/\&/,$reply);
 1796: 	}                    ;
 1797: 	my $i;
 1798: 	for ($i=0;$i<=$#ids;$i++) {
 1799: 	    if ($answer[$i]) {
 1800: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1801: 	    }
 1802: 	}
 1803:     }
 1804:     return %returnhash;
 1805: }
 1806: 
 1807: # ------------------------------------- Find the IDs behind a list of usernames
 1808: 
 1809: sub idrget {
 1810:     my ($udom,@unames)=@_;
 1811:     my %returnhash=();
 1812:     foreach my $uname (@unames) {
 1813:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1814:     }
 1815:     return %returnhash;
 1816: }
 1817: 
 1818: # Store away a list of names and associated student/employee IDs or clicker IDs
 1819: 
 1820: sub idput {
 1821:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1822:     my %servers=();
 1823:     my %ids=();
 1824:     my %byid = ();
 1825:     if (ref($idsref) eq 'HASH') {
 1826:         %ids=%{$idsref};
 1827:     }
 1828:     if ($namespace eq '') {
 1829:         $namespace = 'ids'; 
 1830:     }
 1831:     foreach my $uname (keys(%ids)) {
 1832: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1833:         if ($uhom eq '') {
 1834:             $uhom=&homeserver($uname,$udom);
 1835:         }
 1836:         if ($uhom ne 'no_host') {
 1837:             my $esc_unam=&escape($uname);
 1838:             if ($namespace eq 'ids') {
 1839:                 my $id=&escape($ids{$uname});
 1840:                 $id=~tr/A-Z/a-z/;
 1841:                 my $esc_unam=&escape($uname);
 1842:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1843:             } else {
 1844:                 my @currids = split(/,/,$ids{$uname});
 1845:                 foreach my $id (@currids) {
 1846:                     $byid{$uhom}{$id} .= $uname.',';
 1847:                 }
 1848:             }
 1849:         }
 1850:     }
 1851:     if ($namespace eq 'clickers') {
 1852:         foreach my $server (keys(%byid)) {
 1853:             if (ref($byid{$server}) eq 'HASH') {
 1854:                 foreach my $id (keys(%{$byid{$server}})) {
 1855:                     $byid{$server} =~ s/,$//;
 1856:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1857:                 }
 1858:             }
 1859:         }
 1860:     }
 1861:     foreach my $server (keys(%servers)) {
 1862:         $servers{$server} =~ s/\&$//;
 1863:         if ($namespace eq 'ids') {     
 1864:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1865:         } else {
 1866:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1867:         }
 1868:     }
 1869: }
 1870: 
 1871: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1872: 
 1873: sub iddel {
 1874:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1875:     my %result=();
 1876:     my %ids=();
 1877:     my %byid = ();
 1878:     if (ref($idshashref) eq 'HASH') {
 1879:         %ids=%{$idshashref};
 1880:     } else {
 1881:         return %result;
 1882:     }
 1883:     if ($namespace eq '') {
 1884:         $namespace = 'ids';
 1885:     }
 1886:     my %servers=();
 1887:     while (my ($id,$unamestr) = each(%ids)) {
 1888:         if ($namespace eq 'ids') {
 1889:             my $uhom = $uhome;
 1890:             if ($uhom eq '') { 
 1891:                 $uhom=&homeserver($unamestr,$udom);
 1892:             }
 1893:             if ($uhom ne 'no_host') {
 1894:                 $servers{$uhom}.='&'.&escape($id);
 1895:             }
 1896:          } else {
 1897:             my @curritems = split(/,/,$ids{$id});
 1898:             foreach my $uname (@curritems) {
 1899:                 my $uhom = $uhome;
 1900:                 if ($uhom eq '') {
 1901:                     $uhom=&homeserver($uname,$udom);
 1902:                 }
 1903:                 if ($uhom ne 'no_host') { 
 1904:                     $byid{$uhom}{$id} .= $uname.',';
 1905:                 }
 1906:             }
 1907:         }
 1908:     }
 1909:     if ($namespace eq 'clickers') {
 1910:         foreach my $server (keys(%byid)) {
 1911:             if (ref($byid{$server}) eq 'HASH') {
 1912:                 foreach my $id (keys(%{$byid{$server}})) {
 1913:                     $byid{$server}{$id} =~ s/,$//;
 1914:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 1915:                 }
 1916:             }
 1917:         }
 1918:     }
 1919:     foreach my $server (keys(%servers)) {
 1920:         $servers{$server} =~ s/\&$//;
 1921:         if ($namespace eq 'ids') {
 1922:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1923:         } elsif ($namespace eq 'clickers') {
 1924:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 1925:         }
 1926:     }
 1927:     return %result;
 1928: }
 1929: 
 1930: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 1931: 
 1932: sub updateclickers {
 1933:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 1934:     my %clickers;
 1935:     if (ref($idshashref) eq 'HASH') {
 1936:         %clickers=%{$idshashref};
 1937:     } else {
 1938:         return;
 1939:     }
 1940:     my $items='';
 1941:     foreach my $item (keys(%clickers)) {
 1942:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 1943:     }
 1944:     $items=~s/\&$//;
 1945:     my $request = "updateclickers:$udom:$action:$items";
 1946:     if ($critical) {
 1947:         return &critical($request,$uhome);
 1948:     } else {
 1949:         return &reply($request,$uhome);
 1950:     }
 1951: }
 1952: 
 1953: # ------------------------------dump from db file owned by domainconfig user
 1954: sub dump_dom {
 1955:     my ($namespace, $udom, $regexp) = @_;
 1956: 
 1957:     $udom ||= $env{'user.domain'};
 1958: 
 1959:     return () unless $udom;
 1960: 
 1961:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1962: }
 1963: 
 1964: # ------------------------------------------ get items from domain db files   
 1965: 
 1966: sub get_dom {
 1967:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1968:     return if ($udom eq 'public');
 1969:     my $items='';
 1970:     foreach my $item (@$storearr) {
 1971:         $items.=&escape($item).'&';
 1972:     }
 1973:     $items=~s/\&$//;
 1974:     if (!$udom) {
 1975:         $udom=$env{'user.domain'};
 1976:         return if ($udom eq 'public');
 1977:         if (defined(&domain($udom,'primary'))) {
 1978:             $uhome=&domain($udom,'primary');
 1979:         } else {
 1980:             undef($uhome);
 1981:         }
 1982:     } else {
 1983:         if (!$uhome) {
 1984:             if (defined(&domain($udom,'primary'))) {
 1985:                 $uhome=&domain($udom,'primary');
 1986:             }
 1987:         }
 1988:     }
 1989:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1990:         my $rep;
 1991:         if ($namespace =~ /^enc/) {
 1992:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 1993:         } else {
 1994:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1995:         }
 1996:         my %returnhash;
 1997:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1998:             return %returnhash;
 1999:         }
 2000:         my @pairs=split(/\&/,$rep);
 2001:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2002:             return @pairs;
 2003:         }
 2004:         my $i=0;
 2005:         foreach my $item (@$storearr) {
 2006:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2007:             $i++;
 2008:         }
 2009:         return %returnhash;
 2010:     } else {
 2011:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2012:     }
 2013: }
 2014: 
 2015: # -------------------------------------------- put items in domain db files 
 2016: 
 2017: sub put_dom {
 2018:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2019:     if (!$udom) {
 2020:         $udom=$env{'user.domain'};
 2021:         if (defined(&domain($udom,'primary'))) {
 2022:             $uhome=&domain($udom,'primary');
 2023:         } else {
 2024:             undef($uhome);
 2025:         }
 2026:     } else {
 2027:         if (!$uhome) {
 2028:             if (defined(&domain($udom,'primary'))) {
 2029:                 $uhome=&domain($udom,'primary');
 2030:             }
 2031:         }
 2032:     } 
 2033:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2034:         my $items='';
 2035:         foreach my $item (keys(%$storehash)) {
 2036:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2037:         }
 2038:         $items=~s/\&$//;
 2039:         if ($namespace =~ /^enc/) {
 2040:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2041:         } else {
 2042:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2043:         }
 2044:     } else {
 2045:         &logthis("put_dom failed - no homeserver and/or domain");
 2046:     }
 2047: }
 2048: 
 2049: # --------------------- newput for items in db file owned by domainconfig user
 2050: sub newput_dom {
 2051:     my ($namespace,$storehash,$udom) = @_;
 2052:     my $result;
 2053:     if (!$udom) {
 2054:         $udom=$env{'user.domain'};
 2055:     }
 2056:     if ($udom) {
 2057:         my $uname = &get_domainconfiguser($udom);
 2058:         $result = &newput($namespace,$storehash,$udom,$uname);
 2059:     }
 2060:     return $result;
 2061: }
 2062: 
 2063: # --------------------- delete for items in db file owned by domainconfig user
 2064: sub del_dom {
 2065:     my ($namespace,$storearr,$udom)=@_;
 2066:     if (ref($storearr) eq 'ARRAY') {
 2067:         if (!$udom) {
 2068:             $udom=$env{'user.domain'};
 2069:         }
 2070:         if ($udom) {
 2071:             my $uname = &get_domainconfiguser($udom); 
 2072:             return &del($namespace,$storearr,$udom,$uname);
 2073:         }
 2074:     }
 2075: }
 2076: 
 2077: # ----------------------------------construct domainconfig user for a domain 
 2078: sub get_domainconfiguser {
 2079:     my ($udom) = @_;
 2080:     return $udom.'-domainconfig';
 2081: }
 2082: 
 2083: sub retrieve_inst_usertypes {
 2084:     my ($udom) = @_;
 2085:     my (%returnhash,@order);
 2086:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2087:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2088:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2089:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2090:     } else {
 2091:         if (defined(&domain($udom,'primary'))) {
 2092:             my $uhome=&domain($udom,'primary');
 2093:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2094:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2095:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2096:                 return (\%returnhash,\@order);
 2097:             }
 2098:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2099:             my @pairs=split(/\&/,$hashitems);
 2100:             foreach my $item (@pairs) {
 2101:                 my ($key,$value)=split(/=/,$item,2);
 2102:                 $key = &unescape($key);
 2103:                 next if ($key =~ /^error: 2 /);
 2104:                 $returnhash{$key}=&thaw_unescape($value);
 2105:             }
 2106:             my @esc_order = split(/\&/,$orderitems);
 2107:             foreach my $item (@esc_order) {
 2108:                 push(@order,&unescape($item));
 2109:             }
 2110:         } else {
 2111:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2112:         }
 2113:         return (\%returnhash,\@order);
 2114:     }
 2115: }
 2116: 
 2117: sub is_domainimage {
 2118:     my ($url) = @_;
 2119:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2120:         if (&domain($1) ne '') {
 2121:             return '1';
 2122:         }
 2123:     }
 2124:     return;
 2125: }
 2126: 
 2127: sub inst_directory_query {
 2128:     my ($srch) = @_;
 2129:     my $udom = $srch->{'srchdomain'};
 2130:     my %results;
 2131:     my $homeserver = &domain($udom,'primary');
 2132:     my $outcome;
 2133:     if ($homeserver ne '') {
 2134: 	my $queryid=&reply("querysend:instdirsearch:".
 2135: 			   &escape($srch->{'srchby'}).':'.
 2136: 			   &escape($srch->{'srchterm'}).':'.
 2137: 			   &escape($srch->{'srchtype'}),$homeserver);
 2138: 	my $host=&hostname($homeserver);
 2139: 	if ($queryid !~/^\Q$host\E\_/) {
 2140: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2141: 	    return;
 2142: 	}
 2143: 	my $response = &get_query_reply($queryid);
 2144: 	my $maxtries = 5;
 2145: 	my $tries = 1;
 2146: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2147: 	    $response = &get_query_reply($queryid);
 2148: 	    $tries ++;
 2149: 	}
 2150: 
 2151:         if (!&error($response) && $response ne 'refused') {
 2152:             if ($response eq 'unavailable') {
 2153:                 $outcome = $response;
 2154:             } else {
 2155:                 $outcome = 'ok';
 2156:                 my @matches = split(/\n/,$response);
 2157:                 foreach my $match (@matches) {
 2158:                     my ($key,$value) = split(/=/,$match);
 2159:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2160:                 }
 2161:             }
 2162:         }
 2163:     }
 2164:     return ($outcome,%results);
 2165: }
 2166: 
 2167: sub usersearch {
 2168:     my ($srch) = @_;
 2169:     my $dom = $srch->{'srchdomain'};
 2170:     my %results;
 2171:     my %libserv = &all_library();
 2172:     my $query = 'usersearch';
 2173:     foreach my $tryserver (keys(%libserv)) {
 2174:         if (&host_domain($tryserver) eq $dom) {
 2175:             my $host=&hostname($tryserver);
 2176:             my $queryid=
 2177:                 &reply("querysend:".&escape($query).':'.
 2178:                        &escape($srch->{'srchby'}).':'.
 2179:                        &escape($srch->{'srchtype'}).':'.
 2180:                        &escape($srch->{'srchterm'}),$tryserver);
 2181:             if ($queryid !~/^\Q$host\E\_/) {
 2182:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2183:                 next;
 2184:             }
 2185:             my $reply = &get_query_reply($queryid);
 2186:             my $maxtries = 1;
 2187:             my $tries = 1;
 2188:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2189:                 $reply = &get_query_reply($queryid);
 2190:                 $tries ++;
 2191:             }
 2192:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2193:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2194:             } else {
 2195:                 my @matches;
 2196:                 if ($reply =~ /\n/) {
 2197:                     @matches = split(/\n/,$reply);
 2198:                 } else {
 2199:                     @matches = split(/\&/,$reply);
 2200:                 }
 2201:                 foreach my $match (@matches) {
 2202:                     my ($uname,$udom,%userhash);
 2203:                     foreach my $entry (split(/:/,$match)) {
 2204:                         my ($key,$value) =
 2205:                             map {&unescape($_);} split(/=/,$entry);
 2206:                         $userhash{$key} = $value;
 2207:                         if ($key eq 'username') {
 2208:                             $uname = $value;
 2209:                         } elsif ($key eq 'domain') {
 2210:                             $udom = $value;
 2211:                         }
 2212:                     }
 2213:                     $results{$uname.':'.$udom} = \%userhash;
 2214:                 }
 2215:             }
 2216:         }
 2217:     }
 2218:     return %results;
 2219: }
 2220: 
 2221: sub get_instuser {
 2222:     my ($udom,$uname,$id) = @_;
 2223:     my $homeserver = &domain($udom,'primary');
 2224:     my ($outcome,%results);
 2225:     if ($homeserver ne '') {
 2226:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2227:                            &escape($id).':'.&escape($udom),$homeserver);
 2228:         my $host=&hostname($homeserver);
 2229:         if ($queryid !~/^\Q$host\E\_/) {
 2230:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2231:             return;
 2232:         }
 2233:         my $response = &get_query_reply($queryid);
 2234:         my $maxtries = 5;
 2235:         my $tries = 1;
 2236:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2237:             $response = &get_query_reply($queryid);
 2238:             $tries ++;
 2239:         }
 2240:         if (!&error($response) && $response ne 'refused') {
 2241:             if ($response eq 'unavailable') {
 2242:                 $outcome = $response;
 2243:             } else {
 2244:                 $outcome = 'ok';
 2245:                 my @matches = split(/\n/,$response);
 2246:                 foreach my $match (@matches) {
 2247:                     my ($key,$value) = split(/=/,$match);
 2248:                     $results{&unescape($key)} = &thaw_unescape($value);
 2249:                 }
 2250:             }
 2251:         }
 2252:     }
 2253:     my %userinfo;
 2254:     if (ref($results{$uname}) eq 'HASH') {
 2255:         %userinfo = %{$results{$uname}};
 2256:     } 
 2257:     return ($outcome,%userinfo);
 2258: }
 2259: 
 2260: sub get_multiple_instusers {
 2261:     my ($udom,$users,$caller) = @_;
 2262:     my ($outcome,$results);
 2263:     if (ref($users) eq 'HASH') {
 2264:         my $count = keys(%{$users}); 
 2265:         my $requested = &freeze_escape($users);
 2266:         my $homeserver = &domain($udom,'primary');
 2267:         if ($homeserver ne '') {
 2268:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2269:             my $host=&hostname($homeserver);
 2270:             if ($queryid !~/^\Q$host\E\_/) {
 2271:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2272:                          ' for host: '.$homeserver.'in domain '.$udom);
 2273:                 return ($outcome,$results);
 2274:             }
 2275:             my $response = &get_query_reply($queryid);
 2276:             my $maxtries = 5;
 2277:             if ($count > 100) {
 2278:                 $maxtries = 1+int($count/20);
 2279:             }
 2280:             my $tries = 1;
 2281:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2282:                 $response = &get_query_reply($queryid);
 2283:                 $tries ++;
 2284:             }
 2285:             if ($response eq '') {
 2286:                 $results = {};
 2287:                 foreach my $key (keys(%{$users})) {
 2288:                     my ($uname,$id);
 2289:                     if ($caller eq 'id') {
 2290:                         $id = $key;
 2291:                     } else {
 2292:                         $uname = $key;
 2293:                     }
 2294:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2295:                     $outcome = $resp;
 2296:                     if ($resp eq 'ok') {
 2297:                         %{$results} = (%{$results}, %info);
 2298:                     } else {
 2299:                         last;
 2300:                     }
 2301:                 }
 2302:             } elsif(!&error($response) && ($response ne 'refused')) {
 2303:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2304:                     $outcome = $response;
 2305:                 } else {
 2306:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2307:                     if ($outcome eq 'ok') {
 2308:                         $results = &thaw_unescape($userdata); 
 2309:                     }
 2310:                 }
 2311:             }
 2312:         }
 2313:     }
 2314:     return ($outcome,$results);
 2315: }
 2316: 
 2317: sub inst_rulecheck {
 2318:     my ($udom,$uname,$id,$item,$rules) = @_;
 2319:     my %returnhash;
 2320:     if ($udom ne '') {
 2321:         if (ref($rules) eq 'ARRAY') {
 2322:             @{$rules} = map {&escape($_);} (@{$rules});
 2323:             my $rulestr = join(':',@{$rules});
 2324:             my $homeserver=&domain($udom,'primary');
 2325:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2326:                 my $response;
 2327:                 if ($item eq 'username') {                
 2328:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2329:                                               ':'.&escape($uname).':'.$rulestr,
 2330:                                               $homeserver));
 2331:                 } elsif ($item eq 'id') {
 2332:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2333:                                               ':'.&escape($id).':'.$rulestr,
 2334:                                               $homeserver));
 2335:                 } elsif ($item eq 'selfcreate') {
 2336:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2337:                                                &escape($udom).':'.&escape($uname).
 2338:                                               ':'.$rulestr,$homeserver));
 2339:                 }
 2340:                 if ($response ne 'refused') {
 2341:                     my @pairs=split(/\&/,$response);
 2342:                     foreach my $item (@pairs) {
 2343:                         my ($key,$value)=split(/=/,$item,2);
 2344:                         $key = &unescape($key);
 2345:                         next if ($key =~ /^error: 2 /);
 2346:                         $returnhash{$key}=&thaw_unescape($value);
 2347:                     }
 2348:                 }
 2349:             }
 2350:         }
 2351:     }
 2352:     return %returnhash;
 2353: }
 2354: 
 2355: sub inst_userrules {
 2356:     my ($udom,$check) = @_;
 2357:     my (%ruleshash,@ruleorder);
 2358:     if ($udom ne '') {
 2359:         my $homeserver=&domain($udom,'primary');
 2360:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2361:             my $response;
 2362:             if ($check eq 'id') {
 2363:                 $response=&reply('instidrules:'.&escape($udom),
 2364:                                  $homeserver);
 2365:             } elsif ($check eq 'email') {
 2366:                 $response=&reply('instemailrules:'.&escape($udom),
 2367:                                  $homeserver);
 2368:             } else {
 2369:                 $response=&reply('instuserrules:'.&escape($udom),
 2370:                                  $homeserver);
 2371:             }
 2372:             if (($response ne 'refused') && ($response ne 'error') && 
 2373:                 ($response ne 'unknown_cmd') && 
 2374:                 ($response ne 'no_such_host')) {
 2375:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2376:                 my @pairs=split(/\&/,$hashitems);
 2377:                 foreach my $item (@pairs) {
 2378:                     my ($key,$value)=split(/=/,$item,2);
 2379:                     $key = &unescape($key);
 2380:                     next if ($key =~ /^error: 2 /);
 2381:                     $ruleshash{$key}=&thaw_unescape($value);
 2382:                 }
 2383:                 my @esc_order = split(/\&/,$orderitems);
 2384:                 foreach my $item (@esc_order) {
 2385:                     push(@ruleorder,&unescape($item));
 2386:                 }
 2387:             }
 2388:         }
 2389:     }
 2390:     return (\%ruleshash,\@ruleorder);
 2391: }
 2392: 
 2393: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2394: 
 2395: sub get_domain_defaults {
 2396:     my ($domain,$ignore_cache) = @_;
 2397:     return if (($domain eq '') || ($domain eq 'public'));
 2398:     my $cachetime = 60*60*24;
 2399:     unless ($ignore_cache) {
 2400:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2401:         if (defined($cached)) {
 2402:             if (ref($result) eq 'HASH') {
 2403:                 return %{$result};
 2404:             }
 2405:         }
 2406:     }
 2407:     my %domdefaults;
 2408:     my %domconfig =
 2409:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2410:                                   'requestcourses','inststatus',
 2411:                                   'coursedefaults','usersessions',
 2412:                                   'requestauthor','selfenrollment',
 2413:                                   'coursecategories','ssl','autoenroll',
 2414:                                   'trust','helpsettings'],$domain);
 2415:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2416:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2417:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2418:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2419:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2420:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2421:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2422:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2423:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2424:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2425:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2426:     } else {
 2427:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2428:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2429:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2430:     }
 2431:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2432:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2433:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2434:         } else {
 2435:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2436:         }
 2437:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2438:         foreach my $item (@usertools) {
 2439:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2440:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2441:             }
 2442:         }
 2443:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2444:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2445:         }
 2446:     }
 2447:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2448:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2449:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2450:         }
 2451:     }
 2452:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2453:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2454:     }
 2455:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2456:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2457:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2458:         }
 2459:     }
 2460:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2461:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2462:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2463:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2464:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2465:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2466:         }
 2467:         foreach my $type (@coursetypes) {
 2468:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2469:                 unless ($type eq 'community') {
 2470:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2471:                 }
 2472:             }
 2473:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2474:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2475:             }
 2476:             if ($domdefaults{'postsubmit'} eq 'on') {
 2477:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2478:                     $domdefaults{$type.'postsubtimeout'} = 
 2479:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2480:                 }
 2481:             }
 2482:         }
 2483:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2484:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2485:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2486:                 if (@clonecodes) {
 2487:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2488:                 }
 2489:             }
 2490:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2491:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2492:         }
 2493:     }
 2494:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2495:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2496:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2497:         }
 2498:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2499:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2500:         }
 2501:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2502:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2503:         }
 2504:     }
 2505:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2506:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2507:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2508:                             'approval','limit');
 2509:             foreach my $type (@coursetypes) {
 2510:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2511:                     my @mgrdc = ();
 2512:                     foreach my $item (@settings) {
 2513:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2514:                             push(@mgrdc,$item);
 2515:                         }
 2516:                     }
 2517:                     if (@mgrdc) {
 2518:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2519:                     }
 2520:                 }
 2521:             }
 2522:         }
 2523:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2524:             foreach my $type (@coursetypes) {
 2525:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2526:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2527:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2528:                     }
 2529:                 }
 2530:             }
 2531:         }
 2532:     }
 2533:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2534:         $domdefaults{'catauth'} = 'std';
 2535:         $domdefaults{'catunauth'} = 'std';
 2536:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2537:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2538:         }
 2539:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2540:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2541:         }
 2542:     }
 2543:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2544:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2545:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2546:         }
 2547:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2548:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2549:         }
 2550:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2551:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2552:         }
 2553:     }
 2554:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2555:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2556:         foreach my $prefix (@prefixes) {
 2557:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2558:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2559:             }
 2560:         }
 2561:     }
 2562:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2563:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2564:     }
 2565:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2566:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2567:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2568:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2569:         }
 2570:     }
 2571:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2572:     return %domdefaults;
 2573: }
 2574: 
 2575: sub course_portal_url {
 2576:     my ($cnum,$cdom) = @_;
 2577:     my $chome = &homeserver($cnum,$cdom);
 2578:     my $hostname = &hostname($chome);
 2579:     my $protocol = $protocol{$chome};
 2580:     $protocol = 'http' if ($protocol ne 'https');
 2581:     my %domdefaults = &get_domain_defaults($cdom);
 2582:     my $firsturl;
 2583:     if ($domdefaults{'portal_def'}) {
 2584:         $firsturl = $domdefaults{'portal_def'};
 2585:     } else {
 2586:         $firsturl = $protocol.'://'.$hostname;
 2587:     }
 2588:     return $firsturl;
 2589: }
 2590: 
 2591: # --------------------------------------------------- Assign a key to a student
 2592: 
 2593: sub assign_access_key {
 2594: #
 2595: # a valid key looks like uname:udom#comments
 2596: # comments are being appended
 2597: #
 2598:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2599:     $kdom=
 2600:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2601:     $knum=
 2602:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2603:     $cdom=
 2604:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2605:     $cnum=
 2606:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2607:     $udom=$env{'user.name'} unless (defined($udom));
 2608:     $uname=$env{'user.domain'} unless (defined($uname));
 2609:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2610:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2611:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2612:                                                   # assigned to this person
 2613:                                                   # - this should not happen,
 2614:                                                   # unless something went wrong
 2615:                                                   # the first time around
 2616: # ready to assign
 2617:         $logentry=$1.'; '.$logentry;
 2618:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2619:                                                  $kdom,$knum) eq 'ok') {
 2620: # key now belongs to user
 2621: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2622:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2623:                 &appenv({'environment.'.$envkey => $ckey});
 2624:                 return 'ok';
 2625:             } else {
 2626:                 return 
 2627:   'error: Count not permanently assign key, will need to be re-entered later.';
 2628: 	    }
 2629:         } else {
 2630:             return 'error: Could not assign key, try again later.';
 2631:         }
 2632:     } elsif (!$existing{$ckey}) {
 2633: # the key does not exist
 2634: 	return 'error: The key does not exist';
 2635:     } else {
 2636: # the key is somebody else's
 2637: 	return 'error: The key is already in use';
 2638:     }
 2639: }
 2640: 
 2641: # ------------------------------------------ put an additional comment on a key
 2642: 
 2643: sub comment_access_key {
 2644: #
 2645: # a valid key looks like uname:udom#comments
 2646: # comments are being appended
 2647: #
 2648:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2649:     $cdom=
 2650:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2651:     $cnum=
 2652:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2653:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2654:     if ($existing{$ckey}) {
 2655:         $existing{$ckey}.='; '.$logentry;
 2656: # ready to assign
 2657:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2658:                                                  $cdom,$cnum) eq 'ok') {
 2659: 	    return 'ok';
 2660:         } else {
 2661: 	    return 'error: Count not store comment.';
 2662:         }
 2663:     } else {
 2664: # the key does not exist
 2665: 	return 'error: The key does not exist';
 2666:     }
 2667: }
 2668: 
 2669: # ------------------------------------------------------ Generate a set of keys
 2670: 
 2671: sub generate_access_keys {
 2672:     my ($number,$cdom,$cnum,$logentry)=@_;
 2673:     $cdom=
 2674:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2675:     $cnum=
 2676:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2677:     unless (&allowed('mky',$cdom)) { return 0; }
 2678:     unless (($cdom) && ($cnum)) { return 0; }
 2679:     if ($number>10000) { return 0; }
 2680:     sleep(2); # make sure don't get same seed twice
 2681:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2682:     my $total=0;
 2683:     for (my $i=1;$i<=$number;$i++) {
 2684:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2685:                   sprintf("%lx",int(100000*rand)).'-'.
 2686:                   sprintf("%lx",int(100000*rand));
 2687:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2688:        $newkey=~s/0/h/g; # and also 0 and O
 2689:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2690:        if ($existing{$newkey}) {
 2691:            $i--;
 2692:        } else {
 2693: 	  if (&put('accesskeys',
 2694:               { $newkey => '# generated '.localtime().
 2695:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2696:                            '; '.$logentry },
 2697: 		   $cdom,$cnum) eq 'ok') {
 2698:               $total++;
 2699: 	  }
 2700:        }
 2701:     }
 2702:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2703:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2704:     return $total;
 2705: }
 2706: 
 2707: # ------------------------------------------------------- Validate an accesskey
 2708: 
 2709: sub validate_access_key {
 2710:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2711:     $cdom=
 2712:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2713:     $cnum=
 2714:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2715:     $udom=$env{'user.domain'} unless (defined($udom));
 2716:     $uname=$env{'user.name'} unless (defined($uname));
 2717:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2718:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2719: }
 2720: 
 2721: # ------------------------------------- Find the section of student in a course
 2722: sub devalidate_getsection_cache {
 2723:     my ($udom,$unam,$courseid)=@_;
 2724:     my $hashid="$udom:$unam:$courseid";
 2725:     &devalidate_cache_new('getsection',$hashid);
 2726: }
 2727: 
 2728: sub courseid_to_courseurl {
 2729:     my ($courseid) = @_;
 2730:     #already url style courseid
 2731:     return $courseid if ($courseid =~ m{^/});
 2732: 
 2733:     if (exists($env{'course.'.$courseid.'.num'})) {
 2734: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2735: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2736: 	return "/$cdom/$cnum";
 2737:     }
 2738: 
 2739:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2740:     if (exists($courseinfo{'num'})) {
 2741: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2742:     }
 2743: 
 2744:     return undef;
 2745: }
 2746: 
 2747: sub getsection {
 2748:     my ($udom,$unam,$courseid)=@_;
 2749:     my $cachetime=1800;
 2750: 
 2751:     my $hashid="$udom:$unam:$courseid";
 2752:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2753:     if (defined($cached)) { return $result; }
 2754: 
 2755:     my %Pending; 
 2756:     my %Expired;
 2757:     #
 2758:     # Each role can either have not started yet (pending), be active, 
 2759:     #    or have expired.
 2760:     #
 2761:     # If there is an active role, we are done.
 2762:     #
 2763:     # If there is more than one role which has not started yet, 
 2764:     #     choose the one which will start sooner
 2765:     # If there is one role which has not started yet, return it.
 2766:     #
 2767:     # If there is more than one expired role, choose the one which ended last.
 2768:     # If there is a role which has expired, return it.
 2769:     #
 2770:     $courseid = &courseid_to_courseurl($courseid);
 2771:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2772:     foreach my $key (keys(%roleshash)) {
 2773:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2774:         my $section=$1;
 2775:         if ($key eq $courseid.'_st') { $section=''; }
 2776:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2777:         my $now=time;
 2778:         if (defined($end) && $end && ($now > $end)) {
 2779:             $Expired{$end}=$section;
 2780:             next;
 2781:         }
 2782:         if (defined($start) && $start && ($now < $start)) {
 2783:             $Pending{$start}=$section;
 2784:             next;
 2785:         }
 2786:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2787:     }
 2788:     #
 2789:     # Presumedly there will be few matching roles from the above
 2790:     # loop and the sorting time will be negligible.
 2791:     if (scalar(keys(%Pending))) {
 2792:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2793:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2794:     } 
 2795:     if (scalar(keys(%Expired))) {
 2796:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2797:         my $time = pop(@sorted);
 2798:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2799:     }
 2800:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2801: }
 2802: 
 2803: sub save_cache {
 2804:     &purge_remembered();
 2805:     #&Apache::loncommon::validate_page();
 2806:     undef(%env);
 2807:     undef($env_loaded);
 2808: }
 2809: 
 2810: my $to_remember=-1;
 2811: my %remembered;
 2812: my %accessed;
 2813: my $kicks=0;
 2814: my $hits=0;
 2815: sub make_key {
 2816:     my ($name,$id) = @_;
 2817:     if (length($id) > 65 
 2818: 	&& length(&escape($id)) > 200) {
 2819: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2820:     }
 2821:     return &escape($name.':'.$id);
 2822: }
 2823: 
 2824: sub devalidate_cache_new {
 2825:     my ($name,$id,$debug) = @_;
 2826:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2827:     my $remembered_id=$name.':'.$id;
 2828:     $id=&make_key($name,$id);
 2829:     $memcache->delete($id);
 2830:     delete($remembered{$remembered_id});
 2831:     delete($accessed{$remembered_id});
 2832: }
 2833: 
 2834: sub is_cached_new {
 2835:     my ($name,$id,$debug) = @_;
 2836:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2837:     if (exists($remembered{$remembered_id})) {
 2838: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2839: 	$accessed{$remembered_id}=[&gettimeofday()];
 2840: 	$hits++;
 2841: 	return ($remembered{$remembered_id},1);
 2842:     }
 2843:     $id=&make_key($name,$id);
 2844:     my $value = $memcache->get($id);
 2845:     if (!(defined($value))) {
 2846: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2847: 	return (undef,undef);
 2848:     }
 2849:     if ($value eq '__undef__') {
 2850: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2851: 	$value=undef;
 2852:     }
 2853:     &make_room($remembered_id,$value,$debug);
 2854:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2855:     return ($value,1);
 2856: }
 2857: 
 2858: sub do_cache_new {
 2859:     my ($name,$id,$value,$time,$debug) = @_;
 2860:     my $remembered_id=$name.':'.$id;
 2861:     $id=&make_key($name,$id);
 2862:     my $setvalue=$value;
 2863:     if (!defined($setvalue)) {
 2864: 	$setvalue='__undef__';
 2865:     }
 2866:     if (!defined($time) ) {
 2867: 	$time=600;
 2868:     }
 2869:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2870:     my $result = $memcache->set($id,$setvalue,$time);
 2871:     if (! $result) {
 2872: 	&logthis("caching of id -> $id  failed");
 2873: 	$memcache->disconnect_all();
 2874:     }
 2875:     # need to make a copy of $value
 2876:     &make_room($remembered_id,$value,$debug);
 2877:     return $value;
 2878: }
 2879: 
 2880: sub make_room {
 2881:     my ($remembered_id,$value,$debug)=@_;
 2882: 
 2883:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2884:                                     : $value;
 2885:     if ($to_remember<0) { return; }
 2886:     $accessed{$remembered_id}=[&gettimeofday()];
 2887:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2888:     my $to_kick;
 2889:     my $max_time=0;
 2890:     foreach my $other (keys(%accessed)) {
 2891: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2892: 	    $to_kick=$other;
 2893: 	    $max_time=&tv_interval($accessed{$other});
 2894: 	}
 2895:     }
 2896:     delete($remembered{$to_kick});
 2897:     delete($accessed{$to_kick});
 2898:     $kicks++;
 2899:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2900:     return;
 2901: }
 2902: 
 2903: sub purge_remembered {
 2904:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2905:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2906:     undef(%remembered);
 2907:     undef(%accessed);
 2908: }
 2909: # ------------------------------------- Read an entry from a user's environment
 2910: 
 2911: sub userenvironment {
 2912:     my ($udom,$unam,@what)=@_;
 2913:     my $items;
 2914:     foreach my $item (@what) {
 2915:         $items.=&escape($item).'&';
 2916:     }
 2917:     $items=~s/\&$//;
 2918:     my %returnhash=();
 2919:     my $uhome = &homeserver($unam,$udom);
 2920:     unless ($uhome eq 'no_host') {
 2921:         my @answer=split(/\&/, 
 2922:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2923:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2924:             return %returnhash;
 2925:         }
 2926:         my $i;
 2927:         for ($i=0;$i<=$#what;$i++) {
 2928: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2929:         }
 2930:     }
 2931:     return %returnhash;
 2932: }
 2933: 
 2934: # ---------------------------------------------------------- Get a studentphoto
 2935: sub studentphoto {
 2936:     my ($udom,$unam,$ext) = @_;
 2937:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2938:     if (defined($env{'request.course.id'})) {
 2939:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2940:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2941:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2942:             } else {
 2943:                 my ($result,$perm_reqd)=
 2944: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2945:                 if ($result eq 'ok') {
 2946:                     if (!($perm_reqd eq 'yes')) {
 2947:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2948:                     }
 2949:                 }
 2950:             }
 2951:         }
 2952:     } else {
 2953:         my ($result,$perm_reqd) = 
 2954: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2955:         if ($result eq 'ok') {
 2956:             if (!($perm_reqd eq 'yes')) {
 2957:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2958:             }
 2959:         }
 2960:     }
 2961:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2962: }
 2963: 
 2964: sub retrievestudentphoto {
 2965:     my ($udom,$unam,$ext,$type) = @_;
 2966:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2967:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2968:     if ($ret eq 'ok') {
 2969:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2970:         if ($type eq 'thumbnail') {
 2971:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2972:         }
 2973:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2974:         return $tokenurl;
 2975:     } else {
 2976:         if ($type eq 'thumbnail') {
 2977:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2978:         } else { 
 2979:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2980:         }
 2981:     }
 2982: }
 2983: 
 2984: # -------------------------------------------------------------------- New chat
 2985: 
 2986: sub chatsend {
 2987:     my ($newentry,$anon,$group)=@_;
 2988:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2989:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2990:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2991:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2992: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2993: 		   &escape($newentry)).':'.$group,$chome);
 2994: }
 2995: 
 2996: # ------------------------------------------ Find current version of a resource
 2997: 
 2998: sub getversion {
 2999:     my $fname=&clutter(shift);
 3000:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3001:     return &currentversion(&filelocation('',$fname));
 3002: }
 3003: 
 3004: sub currentversion {
 3005:     my $fname=shift;
 3006:     my $author=$fname;
 3007:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3008:     my ($udom,$uname)=split(/\//,$author);
 3009:     my $home=&homeserver($uname,$udom);
 3010:     if ($home eq 'no_host') { 
 3011:         return -1; 
 3012:     }
 3013:     my $answer=&reply("currentversion:$fname",$home);
 3014:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3015: 	return -1;
 3016:     }
 3017:     return $answer;
 3018: }
 3019: 
 3020: #
 3021: # Return special version number of resource if set by override, empty otherwise
 3022: #
 3023: sub usedversion {
 3024:     my $fname=shift;
 3025:     unless ($fname) { $fname=$env{'request.uri'}; }
 3026:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3027:     if ($urlversion) { return $urlversion; }
 3028:     return '';
 3029: }
 3030: 
 3031: # ----------------------------- Subscribe to a resource, return URL if possible
 3032: 
 3033: sub subscribe {
 3034:     my $fname=shift;
 3035:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3036:     $fname=~s/[\n\r]//g;
 3037:     my $author=$fname;
 3038:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3039:     my ($udom,$uname)=split(/\//,$author);
 3040:     my $home=homeserver($uname,$udom);
 3041:     if ($home eq 'no_host') {
 3042:         return 'not_found';
 3043:     }
 3044:     my $answer=reply("sub:$fname",$home);
 3045:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3046: 	$answer.=' by '.$home;
 3047:     }
 3048:     return $answer;
 3049: }
 3050:     
 3051: # -------------------------------------------------------------- Replicate file
 3052: 
 3053: sub repcopy {
 3054:     my $filename=shift;
 3055:     $filename=~s/\/+/\//g;
 3056:     my $londocroot = $perlvar{'lonDocRoot'};
 3057:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3058:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3059:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3060: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3061: 	return &repcopy_userfile($filename);
 3062:     }
 3063:     $filename=~s/[\n\r]//g;
 3064:     my $transname="$filename.in.transfer";
 3065: # FIXME: this should flock
 3066:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3067:     my $remoteurl=subscribe($filename);
 3068:     if ($remoteurl =~ /^con_lost by/) {
 3069: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3070:            return 'unavailable';
 3071:     } elsif ($remoteurl eq 'not_found') {
 3072: 	   #&logthis("Subscribe returned not_found: $filename");
 3073: 	   return 'not_found';
 3074:     } elsif ($remoteurl =~ /^rejected by/) {
 3075: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3076:            return 'forbidden';
 3077:     } elsif ($remoteurl eq 'directory') {
 3078:            return 'ok';
 3079:     } else {
 3080:         my $author=$filename;
 3081:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3082:         my ($udom,$uname)=split(/\//,$author);
 3083:         my $home=homeserver($uname,$udom);
 3084:         unless ($home eq $perlvar{'lonHostID'}) {
 3085:            my @parts=split(/\//,$filename);
 3086:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3087:            if ($path ne "$londocroot/res") {
 3088:                &logthis("Malconfiguration for replication: $filename");
 3089: 	       return 'bad_request';
 3090:            }
 3091:            my $count;
 3092:            for ($count=5;$count<$#parts;$count++) {
 3093:                $path.="/$parts[$count]";
 3094:                if ((-e $path)!=1) {
 3095: 		   mkdir($path,0777);
 3096:                }
 3097:            }
 3098:            my $request=new HTTP::Request('GET',"$remoteurl");
 3099:            my $response;
 3100:            if ($remoteurl =~ m{/raw/}) {
 3101:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3102:            } else {
 3103:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3104:            }
 3105:            if ($response->is_error()) {
 3106: 	       unlink($transname);
 3107:                my $message=$response->status_line;
 3108:                &logthis("<font color=\"blue\">WARNING:"
 3109:                        ." LWP get: $message: $filename</font>");
 3110:                return 'unavailable';
 3111:            } else {
 3112: 	       if ($remoteurl!~/\.meta$/) {
 3113:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3114:                   my $mresponse;
 3115:                   if ($remoteurl =~ m{/raw/}) {
 3116:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3117:                   } else {
 3118:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3119:                   }
 3120:                   if ($mresponse->is_error()) {
 3121: 		      unlink($filename.'.meta');
 3122:                       &logthis(
 3123:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3124:                   }
 3125: 	       }
 3126:                rename($transname,$filename);
 3127:                return 'ok';
 3128:            }
 3129:        }
 3130:     }
 3131: }
 3132: 
 3133: # ------------------------------------------------ Get server side include body
 3134: sub ssi_body {
 3135:     my ($filelink,%form)=@_;
 3136:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3137:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3138:     }
 3139:     my $output='';
 3140:     my $response;
 3141:     if ($filelink=~/^https?\:/) {
 3142:        ($output,$response)=&externalssi($filelink);
 3143:     } else {
 3144:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3145:        $filelink .= 'inhibitmenu=yes';
 3146:        ($output,$response)=&ssi($filelink,%form);
 3147:     }
 3148:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3149:     $output=~s/^.*?\<body[^\>]*\>//si;
 3150:     $output=~s/\<\/body\s*\>.*?$//si;
 3151:     if (wantarray) {
 3152:         return ($output, $response);
 3153:     } else {
 3154:         return $output;
 3155:     }
 3156: }
 3157: 
 3158: # --------------------------------------------------------- Server Side Include
 3159: 
 3160: sub absolute_url {
 3161:     my ($host_name) = @_;
 3162:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3163:     if ($host_name eq '') {
 3164: 	$host_name = $ENV{'SERVER_NAME'};
 3165:     }
 3166:     return $protocol.$host_name;
 3167: }
 3168: 
 3169: #
 3170: #   Server side include.
 3171: # Parameters:
 3172: #  fn     Possibly encrypted resource name/id.
 3173: #  form   Hash that describes how the rendering should be done
 3174: #         and other things.
 3175: # Returns:
 3176: #   Scalar context: The content of the response.
 3177: #   Array context:  2 element list of the content and the full response object.
 3178: #     
 3179: sub ssi {
 3180: 
 3181:     my ($fn,%form)=@_;
 3182:     my $request;
 3183: 
 3184:     $form{'no_update_last_known'}=1;
 3185:     &Apache::lonenc::check_encrypt(\$fn);
 3186:     if (%form) {
 3187:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3188:       $request->content(join('&',map { 
 3189:             my $name = escape($_);
 3190:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3191:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3192:             : &escape($form{$_}) );    
 3193:         } keys(%form)));
 3194:     } else {
 3195:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3196:     }
 3197: 
 3198:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3199:     my $lonhost = $perlvar{'lonHostID'};
 3200:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
 3201: 
 3202:     if (wantarray) {
 3203: 	return ($response->content, $response);
 3204:     } else {
 3205: 	return $response->content;
 3206:     }
 3207: }
 3208: 
 3209: sub externalssi {
 3210:     my ($url)=@_;
 3211:     my $request=new HTTP::Request('GET',$url);
 3212:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3213:     if (wantarray) {
 3214:         return ($response->content, $response);
 3215:     } else {
 3216:         return $response->content;
 3217:     }
 3218: }
 3219: 
 3220: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3221: 
 3222: sub allowuploaded {
 3223:     my ($srcurl,$url)=@_;
 3224:     $url=&clutter(&declutter($url));
 3225:     my $dir=$url;
 3226:     $dir=~s/\/[^\/]+$//;
 3227:     my %httpref=();
 3228:     my $httpurl=&hreflocation('',$url);
 3229:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3230:     &Apache::lonnet::appenv(\%httpref);
 3231: }
 3232: 
 3233: #
 3234: # Determine if the current user should be able to edit a particular resource,
 3235: # when viewing in course context.
 3236: # (a) When viewing resource used to determine if "Edit" item is included in 
 3237: #     Functions.
 3238: # (b) When displaying folder contents in course editor, used to determine if
 3239: #     "Edit" link will be displayed alongside resource.
 3240: #
 3241: #  input: six args -- filename (decluttered), course number, course domain,
 3242: #                   url, symb (if registered) and group (if this is a group
 3243: #                   item -- e.g., bulletin board, group page etc.).
 3244: #  output: array of five scalars -- 
 3245: #          $cfile -- url for file editing if editable on current server
 3246: #          $home -- homeserver of resource (i.e., for author if published,
 3247: #                                           or course if uploaded.).
 3248: #          $switchserver --  1 if server switch will be needed.
 3249: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3250: #          $forceview -- 1 if icon/link should be to go to view mode
 3251: #
 3252: 
 3253: sub can_edit_resource {
 3254:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3255:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3256: #
 3257: # For aboutme pages user can only edit his/her own.
 3258: #
 3259:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3260:         my ($sdom,$sname) = ($1,$2);
 3261:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3262:             $home = $env{'user.home'};
 3263:             $cfile = $resurl;
 3264:             if ($env{'form.forceedit'}) {
 3265:                 $forceview = 1;
 3266:             } else {
 3267:                 $forceedit = 1;
 3268:             }
 3269:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3270:         } else {
 3271:             return;
 3272:         }
 3273:     }
 3274: 
 3275:     if ($env{'request.course.id'}) {
 3276:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3277:         if ($group ne '') {
 3278: # if this is a group homepage or group bulletin board, check group privs
 3279:             my $allowed = 0;
 3280:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3281:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3282:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3283:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3284:                     $allowed = 1;
 3285:                 }
 3286:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3287:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3288:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3289:                     $allowed = 1;
 3290:                 }
 3291:             }
 3292:             if ($allowed) {
 3293:                 $home=&homeserver($cnum,$cdom);
 3294:                 if ($env{'form.forceedit'}) {
 3295:                     $forceview = 1;
 3296:                 } else {
 3297:                     $forceedit = 1;
 3298:                 }
 3299:                 $cfile = $resurl;
 3300:             } else {
 3301:                 return;
 3302:             }
 3303:         } else {
 3304:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3305:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3306:                     return;
 3307:                 }
 3308:             } elsif (!$crsedit) {
 3309: #
 3310: # No edit allowed where CC has switched to student role.
 3311: #
 3312:                 return;
 3313:             }
 3314:         }
 3315:     }
 3316: 
 3317:     if ($file ne '') {
 3318:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3319:             if (&is_course_upload($file,$cnum,$cdom)) {
 3320:                 $uploaded = 1;
 3321:                 $incourse = 1;
 3322:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3323:                     $cfile = &hreflocation('',$file);
 3324:                     if ($env{'form.forceedit'}) {
 3325:                         $forceview = 1;
 3326:                     } else {
 3327:                         $forceedit = 1;
 3328:                     }
 3329:                 }
 3330:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3331:                 $incourse = 1;
 3332:                 if ($env{'form.forceedit'}) {
 3333:                     $forceview = 1;
 3334:                 } else {
 3335:                     $forceedit = 1;
 3336:                 }
 3337:                 $cfile = $resurl;
 3338:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3339:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3340:                     $incourse = 1;
 3341:                     if ($env{'form.forceedit'}) {
 3342:                         $forceview = 1;
 3343:                     } else {
 3344:                         $forceedit = 1;
 3345:                     }
 3346:                     $cfile = $resurl;
 3347:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3348:                     $incourse = 1;
 3349:                     $cfile = $resurl.'/smpedit';
 3350:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3351:                     $incourse = 1;
 3352:                     if ($env{'form.forceedit'}) {
 3353:                         $forceview = 1;
 3354:                     } else {
 3355:                         $forceedit = 1;
 3356:                     }
 3357:                     $cfile = $resurl;
 3358:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3359:                     $incourse = 1;
 3360:                     if ($env{'form.forceedit'}) {
 3361:                         $forceview = 1;
 3362:                     } else {
 3363:                         $forceedit = 1;
 3364:                     }
 3365:                     $cfile = $resurl;
 3366:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3367:                     $incourse = 1;
 3368:                     if ($env{'form.forceedit'}) {
 3369:                         $forceview = 1;
 3370:                     } else {
 3371:                         $forceedit = 1;
 3372:                     }
 3373:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3374:                 }
 3375:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3376:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3377:                 if (&is_on_map($template)) { 
 3378:                     $incourse = 1;
 3379:                     $forceview = 1;
 3380:                     $cfile = $template;
 3381:                 }
 3382:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3383:                     $incourse = 1;
 3384:                     if ($env{'form.forceedit'}) {
 3385:                         $forceview = 1;
 3386:                     } else {
 3387:                         $forceedit = 1;
 3388:                     }
 3389:                     $cfile = $resurl;
 3390:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3391:                 $incourse = 1;
 3392:                 if ($env{'form.forceedit'}) {
 3393:                     $forceview = 1;
 3394:                 } else {
 3395:                     $forceedit = 1;
 3396:                 }
 3397:                 $cfile = $resurl;
 3398:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3399:                 $incourse = 1;
 3400:                 $forceview = 1;
 3401:                 if ($symb) {
 3402:                     my ($map,$id,$res)=&decode_symb($symb);
 3403:                     $env{'request.symb'} = $symb;
 3404:                     $cfile = &clutter($res);
 3405:                 } else {
 3406:                     $cfile = $env{'form.suppurl'};
 3407:                     my $escfile = &unescape($cfile);
 3408:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3409:                         $cfile = '/adm/wrapper'.$escfile;
 3410:                     } else {
 3411:                         $escfile =~ s{^http://}{};
 3412:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3413:                     }
 3414:                 }
 3415:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3416:                 if ($env{'form.forceedit'}) {
 3417:                     $forceview = 1;
 3418:                 } else {
 3419:                     $forceedit = 1;
 3420:                 }
 3421:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3422:             }
 3423:         }
 3424:         if ($uploaded || $incourse) {
 3425:             $home=&homeserver($cnum,$cdom);
 3426:         } elsif ($file !~ m{/$}) {
 3427:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3428:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3429:             # Check that the user has permission to edit this resource
 3430:             my $setpriv = 1;
 3431:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3432:             if (defined($cfudom)) {
 3433:                 $home=&homeserver($cfuname,$cfudom);
 3434:                 $cfile=$file;
 3435:             }
 3436:         }
 3437:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3438:             (($home ne '') && ($home ne 'no_host'))) {
 3439:             my @ids=&current_machine_ids();
 3440:             unless (grep(/^\Q$home\E$/,@ids)) {
 3441:                 $switchserver=1;
 3442:             }
 3443:         }
 3444:     }
 3445:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3446: }
 3447: 
 3448: sub is_course_upload {
 3449:     my ($file,$cnum,$cdom) = @_;
 3450:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3451:     $uploadpath =~ s{^\/}{};
 3452:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3453:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3454:         return 1;
 3455:     }
 3456:     return;
 3457: }
 3458: 
 3459: sub in_course {
 3460:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3461:     if ($hideprivileged) {
 3462:         my $skipuser;
 3463:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3464:         my @possdoms = ($cdom);  
 3465:         if ($coursehash{'checkforpriv'}) { 
 3466:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3467:         }
 3468:         if (&privileged($uname,$udom,\@possdoms)) {
 3469:             $skipuser = 1;
 3470:             if ($coursehash{'nothideprivileged'}) {
 3471:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3472:                     my $user;
 3473:                     if ($item =~ /:/) {
 3474:                         $user = $item;
 3475:                     } else {
 3476:                         $user = join(':',split(/[\@]/,$item));
 3477:                     }
 3478:                     if ($user eq $uname.':'.$udom) {
 3479:                         undef($skipuser);
 3480:                         last;
 3481:                     }
 3482:                 }
 3483:             }
 3484:             if ($skipuser) {
 3485:                 return 0;
 3486:             }
 3487:         }
 3488:     }
 3489:     $type ||= 'any';
 3490:     if (!defined($cdom) || !defined($cnum)) {
 3491:         my $cid  = $env{'request.course.id'};
 3492:         $cdom = $env{'course.'.$cid.'.domain'};
 3493:         $cnum = $env{'course.'.$cid.'.num'};
 3494:     }
 3495:     my $typesref;
 3496:     if (($type eq 'any') || ($type eq 'all')) {
 3497:         $typesref = ['active','previous','future'];
 3498:     } elsif ($type eq 'previous' || $type eq 'future') {
 3499:         $typesref = [$type];
 3500:     }
 3501:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3502:                               $typesref,undef,[$cdom]);
 3503:     my ($tmp) = keys(%roles);
 3504:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3505:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3506:     if (@course_roles > 0) {
 3507:         return 1;
 3508:     }
 3509:     return 0;
 3510: }
 3511: 
 3512: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3513: # input: action, courseID, current domain, intended
 3514: #        path to file, source of file, instruction to parse file for objects,
 3515: #        ref to hash for embedded objects,
 3516: #        ref to hash for codebase of java objects.
 3517: #        reference to scalar to accommodate mime type determined
 3518: #          from File::MMagic if $parser = parse.
 3519: #
 3520: # output: url to file (if action was uploaddoc), 
 3521: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3522: #
 3523: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3524: # course.
 3525: #
 3526: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3527: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3528: #          course's home server.
 3529: #
 3530: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3531: #          be copied from $source (current location) to 
 3532: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3533: #         and will then be copied to
 3534: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3535: #         course's home server.
 3536: #
 3537: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3538: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3539: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3540: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3541: #         in course's home server.
 3542: #
 3543: 
 3544: sub process_coursefile {
 3545:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3546:         $mimetype)=@_;
 3547:     my $fetchresult;
 3548:     my $home=&homeserver($docuname,$docudom);
 3549:     if ($action eq 'propagate') {
 3550:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3551: 			     $home);
 3552:     } else {
 3553:         my $fpath = '';
 3554:         my $fname = $file;
 3555:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3556:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3557:         my $filepath = &build_filepath($fpath);
 3558:         if ($action eq 'copy') {
 3559:             if ($source eq '') {
 3560:                 $fetchresult = 'no source file';
 3561:                 return $fetchresult;
 3562:             } else {
 3563:                 my $destination = $filepath.'/'.$fname;
 3564:                 rename($source,$destination);
 3565:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3566:                                  $home);
 3567:             }
 3568:         } elsif ($action eq 'uploaddoc') {
 3569:             open(my $fh,'>'.$filepath.'/'.$fname);
 3570:             print $fh $env{'form.'.$source};
 3571:             close($fh);
 3572:             if ($parser eq 'parse') {
 3573:                 my $mm = new File::MMagic;
 3574:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3575:                 if ($type eq 'text/html') {
 3576:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3577:                     unless ($parse_result eq 'ok') {
 3578:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3579:                     }
 3580:                 }
 3581:                 if (ref($mimetype)) {
 3582:                     $$mimetype = $type;
 3583:                 } 
 3584:             }
 3585:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3586:                                  $home);
 3587:             if ($fetchresult eq 'ok') {
 3588:                 return '/uploaded/'.$fpath.'/'.$fname;
 3589:             } else {
 3590:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3591:                         ' to host '.$home.': '.$fetchresult);
 3592:                 return '/adm/notfound.html';
 3593:             }
 3594:         }
 3595:     }
 3596:     unless ( $fetchresult eq 'ok') {
 3597:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3598:              ' to host '.$home.': '.$fetchresult);
 3599:     }
 3600:     return $fetchresult;
 3601: }
 3602: 
 3603: sub build_filepath {
 3604:     my ($fpath) = @_;
 3605:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3606:     unless ($fpath eq '') {
 3607:         my @parts=split('/',$fpath);
 3608:         foreach my $part (@parts) {
 3609:             $filepath.= '/'.$part;
 3610:             if ((-e $filepath)!=1) {
 3611:                 mkdir($filepath,0777);
 3612:             }
 3613:         }
 3614:     }
 3615:     return $filepath;
 3616: }
 3617: 
 3618: sub store_edited_file {
 3619:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3620:     my $file = $primary_url;
 3621:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3622:     my $fpath = '';
 3623:     my $fname = $file;
 3624:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3625:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3626:     my $filepath = &build_filepath($fpath);
 3627:     open(my $fh,'>'.$filepath.'/'.$fname);
 3628:     print $fh $content;
 3629:     close($fh);
 3630:     my $home=&homeserver($docuname,$docudom);
 3631:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3632: 			  $home);
 3633:     if ($$fetchresult eq 'ok') {
 3634:         return '/uploaded/'.$fpath.'/'.$fname;
 3635:     } else {
 3636:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3637: 		 ' to host '.$home.': '.$$fetchresult);
 3638:         return '/adm/notfound.html';
 3639:     }
 3640: }
 3641: 
 3642: sub clean_filename {
 3643:     my ($fname,$args)=@_;
 3644: # Replace Windows backslashes by forward slashes
 3645:     $fname=~s/\\/\//g;
 3646:     if (!$args->{'keep_path'}) {
 3647:         # Get rid of everything but the actual filename
 3648: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3649:     }
 3650: # Replace spaces by underscores
 3651:     $fname=~s/\s+/\_/g;
 3652: # Replace all other weird characters by nothing
 3653:     $fname=~s{[^/\w\.\-]}{}g;
 3654: # Replace all .\d. sequences with _\d. so they no longer look like version
 3655: # numbers
 3656:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3657:     return $fname;
 3658: }
 3659: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3660: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3661: # image with the same aspect ratio as the original, but with dimensions which do 
 3662: # not exceed $resizewidth and $resizeheight.
 3663:  
 3664: sub resizeImage {
 3665:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3666:     my $ima = Image::Magick->new;
 3667:     my $resized;
 3668:     if (-e $img_path) {
 3669:         $ima->Read($img_path);
 3670:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3671:             my $width = $ima->Get('width');
 3672:             my $height = $ima->Get('height');
 3673:             if ($width > $resizewidth) {
 3674: 	        my $factor = $width/$resizewidth;
 3675:                 my $newheight = $height/$factor;
 3676:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3677:                 $resized = 1;
 3678:             }
 3679:         }
 3680:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3681:             my $width = $ima->Get('width');
 3682:             my $height = $ima->Get('height');
 3683:             if ($height > $resizeheight) {
 3684:                 my $factor = $height/$resizeheight;
 3685:                 my $newwidth = $width/$factor;
 3686:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3687:                 $resized = 1;
 3688:             }
 3689:         }
 3690:         if ($resized) {
 3691:             $ima->Write($img_path);
 3692:         }
 3693:     }
 3694:     return;
 3695: }
 3696: 
 3697: # --------------- Take an uploaded file and put it into the userfiles directory
 3698: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3699: #                    the desired filename is in $env{"form.$formname.filename"}
 3700: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3701: #                                    canceloverwrite, or ''. 
 3702: #                   if 'coursedoc': upload to the current course
 3703: #                   if 'existingfile': write file to tmp/overwrites directory 
 3704: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3705: #                   $context is passed as argument to &finishuserfileupload
 3706: #        $subdir - directory in userfile to store the file into
 3707: #        $parser - instruction to parse file for objects ($parser = parse)    
 3708: #        $allfiles - reference to hash for embedded objects
 3709: #        $codebase - reference to hash for codebase of java objects
 3710: #        $desuname - username for permanent storage of uploaded file
 3711: #        $dsetudom - domain for permanaent storage of uploaded file
 3712: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3713: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3714: #        $resizewidth - width (pixels) to which to resize uploaded image
 3715: #        $resizeheight - height (pixels) to which to resize uploaded image
 3716: #        $mimetype - reference to scalar to accommodate mime type determined
 3717: #                    from File::MMagic.
 3718: # 
 3719: # output: url of file in userspace, or error: <message> 
 3720: #             or /adm/notfound.html if failure to upload occurse
 3721: 
 3722: sub userfileupload {
 3723:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3724:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3725:     if (!defined($subdir)) { $subdir='unknown'; }
 3726:     my $fname=$env{'form.'.$formname.'.filename'};
 3727:     $fname=&clean_filename($fname);
 3728:     # See if there is anything left
 3729:     unless ($fname) { return 'error: no uploaded file'; }
 3730:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3731:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3732:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3733:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3734:         my $now = time;
 3735:         my $filepath;
 3736:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3737:              $filepath = 'tmp/helprequests/'.$now;
 3738:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3739:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3740:                          '_'.$env{'user.domain'}.'/pending';
 3741:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3742:             my ($docuname,$docudom);
 3743:             if ($destudom) {
 3744:                 $docudom = $destudom;
 3745:             } else {
 3746:                 $docudom = $env{'user.domain'};
 3747:             }
 3748:             if ($destuname) {
 3749:                 $docuname = $destuname;
 3750:             } else {
 3751:                 $docuname = $env{'user.name'};
 3752:             }
 3753:             if (exists($env{'form.group'})) {
 3754:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3755:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3756:             }
 3757:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3758:             if ($context eq 'canceloverwrite') {
 3759:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3760:                 if (-e  $tempfile) {
 3761:                     my @info = stat($tempfile);
 3762:                     if ($info[9] eq $env{'form.timestamp'}) {
 3763:                         unlink($tempfile);
 3764:                     }
 3765:                 }
 3766:                 return;
 3767:             }
 3768:         }
 3769:         # Create the directory if not present
 3770:         my @parts=split(/\//,$filepath);
 3771:         my $fullpath = $perlvar{'lonDaemons'};
 3772:         for (my $i=0;$i<@parts;$i++) {
 3773:             $fullpath .= '/'.$parts[$i];
 3774:             if ((-e $fullpath)!=1) {
 3775:                 mkdir($fullpath,0777);
 3776:             }
 3777:         }
 3778:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3779:         print $fh $env{'form.'.$formname};
 3780:         close($fh);
 3781:         if ($context eq 'existingfile') {
 3782:             my @info = stat($fullpath.'/'.$fname);
 3783:             return ($fullpath.'/'.$fname,$info[9]);
 3784:         } else {
 3785:             return $fullpath.'/'.$fname;
 3786:         }
 3787:     }
 3788:     if ($subdir eq 'scantron') {
 3789:         $fname = 'scantron_orig_'.$fname;
 3790:     } else {
 3791:         $fname="$subdir/$fname";
 3792:     }
 3793:     if ($context eq 'coursedoc') {
 3794: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3795: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3796:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3797:             return &finishuserfileupload($docuname,$docudom,
 3798: 					 $formname,$fname,$parser,$allfiles,
 3799: 					 $codebase,$thumbwidth,$thumbheight,
 3800:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3801:         } else {
 3802:             if ($env{'form.folder'}) {
 3803:                 $fname=$env{'form.folder'}.'/'.$fname;
 3804:             }
 3805:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3806: 				       $fname,$formname,$parser,
 3807: 				       $allfiles,$codebase,$mimetype);
 3808:         }
 3809:     } elsif (defined($destuname)) {
 3810:         my $docuname=$destuname;
 3811:         my $docudom=$destudom;
 3812: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3813: 				     $parser,$allfiles,$codebase,
 3814:                                      $thumbwidth,$thumbheight,
 3815:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3816:     } else {
 3817:         my $docuname=$env{'user.name'};
 3818:         my $docudom=$env{'user.domain'};
 3819:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3820:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3821:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3822:         }
 3823: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3824: 				     $parser,$allfiles,$codebase,
 3825:                                      $thumbwidth,$thumbheight,
 3826:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3827:     }
 3828: }
 3829: 
 3830: sub finishuserfileupload {
 3831:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3832:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3833:     my $path=$docudom.'/'.$docuname.'/';
 3834:     my $filepath=$perlvar{'lonDocRoot'};
 3835:   
 3836:     my ($fnamepath,$file,$fetchthumb);
 3837:     $file=$fname;
 3838:     if ($fname=~m|/|) {
 3839:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3840: 	$path.=$fnamepath.'/';
 3841:     }
 3842:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3843:     my $count;
 3844:     for ($count=4;$count<=$#parts;$count++) {
 3845:         $filepath.="/$parts[$count]";
 3846:         if ((-e $filepath)!=1) {
 3847: 	    mkdir($filepath,0777);
 3848:         }
 3849:     }
 3850: 
 3851: # Save the file
 3852:     {
 3853: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3854: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3855: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3856: 	    return '/adm/notfound.html';
 3857: 	}
 3858:         if ($context eq 'overwrite') {
 3859:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3860:             my $target = $filepath.'/'.$file;
 3861:             if (-e $source) {
 3862:                 my @info = stat($source);
 3863:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3864:                     unless (&File::Copy::move($source,$target)) {
 3865:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3866:                         return "Moving from $source failed";
 3867:                     }
 3868:                 } else {
 3869:                     return "Temporary file: $source had unexpected date/time for last modification";
 3870:                 }
 3871:             } else {
 3872:                 return "Temporary file: $source missing";
 3873:             }
 3874:         } elsif (!print FH ($env{'form.'.$formname})) {
 3875: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3876: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3877: 	    return '/adm/notfound.html';
 3878: 	}
 3879: 	close(FH);
 3880:         if ($resizewidth && $resizeheight) {
 3881:             my $mm = new File::MMagic;
 3882:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3883:             if ($mime_type =~ m{^image/}) {
 3884: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3885:             }  
 3886: 	}
 3887:     }
 3888:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3889:         if (ref($mimetype)) {
 3890:             if ($$mimetype eq '') {
 3891:                 my $mm = new File::MMagic;
 3892:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3893:                 $$mimetype = $type;
 3894:             }
 3895:         }
 3896:     }
 3897:     if ($parser eq 'parse') {
 3898:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3899:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3900:                                                        $allfiles,$codebase);
 3901:             unless ($parse_result eq 'ok') {
 3902:                 &logthis('Failed to parse '.$filepath.$file.
 3903: 	   	         ' for embedded media: '.$parse_result); 
 3904:             }
 3905:         }
 3906:     }
 3907:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3908:         my $input = $filepath.'/'.$file;
 3909:         my $output = $filepath.'/'.'tn-'.$file;
 3910:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3911:         system("convert -sample $thumbsize $input $output");
 3912:         if (-e $filepath.'/'.'tn-'.$file) {
 3913:             $fetchthumb  = 1; 
 3914:         }
 3915:     }
 3916:  
 3917: # Notify homeserver to grep it
 3918: #
 3919:     my $docuhome=&homeserver($docuname,$docudom);	
 3920:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3921:     if ($fetchresult eq 'ok') {
 3922:         if ($fetchthumb) {
 3923:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3924:             if ($thumbresult ne 'ok') {
 3925:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3926:                          $docuhome.': '.$thumbresult);
 3927:             }
 3928:         }
 3929: #
 3930: # Return the URL to it
 3931:         return '/uploaded/'.$path.$file;
 3932:     } else {
 3933:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3934: 		 ': '.$fetchresult);
 3935:         return '/adm/notfound.html';
 3936:     }
 3937: }
 3938: 
 3939: sub extract_embedded_items {
 3940:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3941:     my @state = ();
 3942:     my (%lastids,%related,%shockwave,%flashvars);
 3943:     my %javafiles = (
 3944:                       codebase => '',
 3945:                       code => '',
 3946:                       archive => ''
 3947:                     );
 3948:     my %mediafiles = (
 3949:                       src => '',
 3950:                       movie => '',
 3951:                      );
 3952:     my $p;
 3953:     if ($content) {
 3954:         $p = HTML::LCParser->new($content);
 3955:     } else {
 3956:         $p = HTML::LCParser->new($fullpath);
 3957:     }
 3958:     while (my $t=$p->get_token()) {
 3959: 	if ($t->[0] eq 'S') {
 3960: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3961: 	    push(@state, $tagname);
 3962:             if (lc($tagname) eq 'allow') {
 3963:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3964:             }
 3965: 	    if (lc($tagname) eq 'img') {
 3966: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3967: 	    }
 3968: 	    if (lc($tagname) eq 'a') {
 3969:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3970:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3971:                 }
 3972: 	    }
 3973:             if (lc($tagname) eq 'script') {
 3974:                 my $src;
 3975:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3976:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3977:                 } else {
 3978:                     if ($attr->{'src'} ne '') {
 3979:                         $src = $attr->{'src'};
 3980:                         &add_filetype($allfiles,$src,'src');
 3981:                     }
 3982:                 }
 3983:                 my $text = $p->get_trimmed_text();
 3984:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3985:                     my @swfargs = split(/,/,$1);
 3986:                     foreach my $item (@swfargs) {
 3987:                         $item =~ s/["']//g;
 3988:                         $item =~ s/^\s+//;
 3989:                         $item =~ s/\s+$//;
 3990:                     }
 3991:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3992:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3993:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3994:                         } else {
 3995:                             $related{$swfargs[0]} = [$swfargs[2]];
 3996:                         }
 3997:                     }
 3998:                 }
 3999:             }
 4000:             if (lc($tagname) eq 'link') {
 4001:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4002:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4003:                 }
 4004:             }
 4005: 	    if (lc($tagname) eq 'object' ||
 4006: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4007: 		foreach my $item (keys(%javafiles)) {
 4008: 		    $javafiles{$item} = '';
 4009: 		}
 4010:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4011:                     $lastids{lc($tagname)} = $attr->{'id'};
 4012:                 }
 4013: 	    }
 4014: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4015: 		my $name = lc($attr->{'name'});
 4016: 		foreach my $item (keys(%javafiles)) {
 4017: 		    if ($name eq $item) {
 4018: 			$javafiles{$item} = $attr->{'value'};
 4019: 			last;
 4020: 		    }
 4021: 		}
 4022:                 my $pathfrom;
 4023: 		foreach my $item (keys(%mediafiles)) {
 4024: 		    if ($name eq $item) {
 4025:                         $pathfrom = $attr->{'value'};
 4026:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4027: 			&add_filetype($allfiles,$pathfrom,$name);
 4028: 			last;
 4029: 		    }
 4030: 		}
 4031:                 if ($name eq 'flashvars') {
 4032:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4033:                 }
 4034:                 if ($pathfrom ne '') {
 4035:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4036:                                          $pathfrom);
 4037:                 }
 4038: 	    }
 4039: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4040: 		foreach my $item (keys(%javafiles)) {
 4041: 		    if ($attr->{$item}) {
 4042: 			$javafiles{$item} = $attr->{$item};
 4043: 			last;
 4044: 		    }
 4045: 		}
 4046: 		foreach my $item (keys(%mediafiles)) {
 4047: 		    if ($attr->{$item}) {
 4048: 			&add_filetype($allfiles,$attr->{$item},$item);
 4049: 			last;
 4050: 		    }
 4051: 		}
 4052:                 if (lc($tagname) eq 'embed') {
 4053:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4054:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4055:                                              $attr->{'src'});
 4056:                     }
 4057:                 }
 4058: 	    }
 4059:             if (lc($tagname) eq 'iframe') {
 4060:                 my $src = $attr->{'src'} ;
 4061:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4062:                     &add_filetype($allfiles,$src,'src');
 4063:                 } elsif ($src =~ m{^/}) {
 4064:                     if ($env{'request.course.id'}) {
 4065:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4066:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4067:                         my $url = &hreflocation('',$fullpath);
 4068:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4069:                             my $relpath = $1;
 4070:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4071:                                 &add_filetype($allfiles,$1,'src');
 4072:                             }
 4073:                         }
 4074:                     }
 4075:                 }
 4076:             }
 4077:             if ($t->[4] =~ m{/>$}) {
 4078:                 pop(@state);
 4079:             }
 4080: 	} elsif ($t->[0] eq 'E') {
 4081: 	    my ($tagname) = ($t->[1]);
 4082: 	    if ($javafiles{'codebase'} ne '') {
 4083: 		$javafiles{'codebase'} .= '/';
 4084: 	    }  
 4085: 	    if (lc($tagname) eq 'applet' ||
 4086: 		lc($tagname) eq 'object' ||
 4087: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4088: 		) {
 4089: 		foreach my $item (keys(%javafiles)) {
 4090: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4091: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4092: 			&add_filetype($allfiles,$file,$item);
 4093: 		    }
 4094: 		}
 4095: 	    } 
 4096: 	    pop @state;
 4097: 	}
 4098:     }
 4099:     foreach my $id (sort(keys(%flashvars))) {
 4100:         if ($shockwave{$id} ne '') {
 4101:             my @pairs = split(/\&/,$flashvars{$id});
 4102:             foreach my $pair (@pairs) {
 4103:                 my ($key,$value) = split(/\=/,$pair);
 4104:                 if ($key eq 'thumb') {
 4105:                     &add_filetype($allfiles,$value,$key);
 4106:                 } elsif ($key eq 'content') {
 4107:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4108:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4109:                     if ($ext ne '') {
 4110:                         &add_filetype($allfiles,$path.$value,$ext);
 4111:                     }
 4112:                 }
 4113:             }
 4114:         }
 4115:     }
 4116:     return 'ok';
 4117: }
 4118: 
 4119: sub add_filetype {
 4120:     my ($allfiles,$file,$type)=@_;
 4121:     if (exists($allfiles->{$file})) {
 4122: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4123: 	    push(@{$allfiles->{$file}}, &escape($type));
 4124: 	}
 4125:     } else {
 4126: 	@{$allfiles->{$file}} = (&escape($type));
 4127:     }
 4128: }
 4129: 
 4130: sub embedded_dependency {
 4131:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4132:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4133:         if (($identifier ne '') &&
 4134:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4135:             ($pathfrom ne '')) {
 4136:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4137:             foreach my $dep (@{$related->{$identifier}}) {
 4138:                 &add_filetype($allfiles,$path.$dep,'object');
 4139:             }
 4140:         }
 4141:     }
 4142:     return;
 4143: }
 4144: 
 4145: sub removeuploadedurl {
 4146:     my ($url)=@_;	
 4147:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4148:     return &removeuserfile($uname,$udom,$fname);
 4149: }
 4150: 
 4151: sub removeuserfile {
 4152:     my ($docuname,$docudom,$fname)=@_;
 4153:     my $home=&homeserver($docuname,$docudom);    
 4154:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4155:     if ($result eq 'ok') {	
 4156:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4157:             my $metafile = $fname.'.meta';
 4158:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4159: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4160:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4161:             my $sqlresult = 
 4162:                 &update_portfolio_table($docuname,$docudom,$file,
 4163:                                         'portfolio_metadata',$group,
 4164:                                         'delete');
 4165:         }
 4166:     }
 4167:     return $result;
 4168: }
 4169: 
 4170: sub mkdiruserfile {
 4171:     my ($docuname,$docudom,$dir)=@_;
 4172:     my $home=&homeserver($docuname,$docudom);
 4173:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4174: }
 4175: 
 4176: sub renameuserfile {
 4177:     my ($docuname,$docudom,$old,$new)=@_;
 4178:     my $home=&homeserver($docuname,$docudom);
 4179:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4180:                         &escape("$old").':'.&escape("$new"),$home);
 4181:     if ($result eq 'ok') {
 4182:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4183:             my $oldmeta = $old.'.meta';
 4184:             my $newmeta = $new.'.meta';
 4185:             my $metaresult = 
 4186:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4187: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4188:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4189:             my $sqlresult = 
 4190:                 &update_portfolio_table($docuname,$docudom,$file,
 4191:                                         'portfolio_metadata',$group,
 4192:                                         'delete');
 4193:         }
 4194:     }
 4195:     return $result;
 4196: }
 4197: 
 4198: # ------------------------------------------------------------------------- Log
 4199: 
 4200: sub log {
 4201:     my ($dom,$nam,$hom,$what)=@_;
 4202:     return critical("log:$dom:$nam:$what",$hom);
 4203: }
 4204: 
 4205: # ------------------------------------------------------------------ Course Log
 4206: #
 4207: # This routine flushes several buffers of non-mission-critical nature
 4208: #
 4209: 
 4210: sub flushcourselogs {
 4211:     &logthis('Flushing log buffers');
 4212: #
 4213: # course logs
 4214: # This is a log of all transactions in a course, which can be used
 4215: # for data mining purposes
 4216: #
 4217: # It also collects the courseid database, which lists last transaction
 4218: # times and course titles for all courseids
 4219: #
 4220:     my %courseidbuffer=();
 4221:     foreach my $crsid (keys(%courselogs)) {
 4222:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4223: 		          &escape($courselogs{$crsid}),
 4224: 		          $coursehombuf{$crsid}) eq 'ok') {
 4225: 	    delete $courselogs{$crsid};
 4226:         } else {
 4227:             &logthis('Failed to flush log buffer for '.$crsid);
 4228:             if (length($courselogs{$crsid})>40000) {
 4229:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4230:                         " exceeded maximum size, deleting.</font>");
 4231:                delete $courselogs{$crsid};
 4232:             }
 4233:         }
 4234:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4235:             'description' => $coursedescrbuf{$crsid},
 4236:             'inst_code'    => $courseinstcodebuf{$crsid},
 4237:             'type'        => $coursetypebuf{$crsid},
 4238:             'owner'       => $courseownerbuf{$crsid},
 4239:         };
 4240:     }
 4241: #
 4242: # Write course id database (reverse lookup) to homeserver of courses 
 4243: # Is used in pickcourse
 4244: #
 4245:     foreach my $crs_home (keys(%courseidbuffer)) {
 4246:         my $response = &courseidput(&host_domain($crs_home),
 4247:                                     $courseidbuffer{$crs_home},
 4248:                                     $crs_home,'timeonly');
 4249:     }
 4250: #
 4251: # File accesses
 4252: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4253: #
 4254:     foreach my $entry (keys(%accesshash)) {
 4255:         if ($entry =~ /___count$/) {
 4256:             my ($dom,$name);
 4257:             ($dom,$name,undef)=
 4258: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4259:             if (! defined($dom) || $dom eq '' || 
 4260:                 ! defined($name) || $name eq '') {
 4261:                 my $cid = $env{'request.course.id'};
 4262:                 $dom  = $env{'request.'.$cid.'.domain'};
 4263:                 $name = $env{'request.'.$cid.'.num'};
 4264:             }
 4265:             my $value = $accesshash{$entry};
 4266:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4267:             my %temphash=($url => $value);
 4268:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4269:             if ($result eq 'ok') {
 4270:                 delete $accesshash{$entry};
 4271:             }
 4272:         } else {
 4273:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4274:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4275:             my %temphash=($entry => $accesshash{$entry});
 4276:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4277:                 delete $accesshash{$entry};
 4278:             }
 4279:         }
 4280:     }
 4281: #
 4282: # Roles
 4283: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4284: #
 4285:     foreach my $entry (keys(%userrolehash)) {
 4286:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4287: 	    split(/\:/,$entry);
 4288:         if (&Apache::lonnet::put('nohist_userroles',
 4289:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4290:                 $rudom,$runame) eq 'ok') {
 4291: 	    delete $userrolehash{$entry};
 4292:         }
 4293:     }
 4294: #
 4295: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4296: #
 4297:     my %domrolebuffer = ();
 4298:     foreach my $entry (keys(%domainrolehash)) {
 4299:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4300:         if ($domrolebuffer{$rudom}) {
 4301:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4302:                       '='.&escape($domainrolehash{$entry});
 4303:         } else {
 4304:             $domrolebuffer{$rudom}.=&escape($entry).
 4305:                       '='.&escape($domainrolehash{$entry});
 4306:         }
 4307:         delete $domainrolehash{$entry};
 4308:     }
 4309:     foreach my $dom (keys(%domrolebuffer)) {
 4310: 	my %servers;
 4311: 	if (defined(&domain($dom,'primary'))) {
 4312: 	    my $primary=&domain($dom,'primary');
 4313: 	    my $hostname=&hostname($primary);
 4314: 	    $servers{$primary} = $hostname;
 4315: 	} else { 
 4316: 	    %servers = &get_servers($dom,'library');
 4317: 	}
 4318: 	foreach my $tryserver (keys(%servers)) {
 4319: 	    if (&reply('domroleput:'.$dom.':'.
 4320: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4321: 		last;
 4322: 	    } else {  
 4323: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4324: 	    }
 4325:         }
 4326:     }
 4327:     $dumpcount++;
 4328: }
 4329: 
 4330: sub courselog {
 4331:     my $what=shift;
 4332:     $what=time.':'.$what;
 4333:     unless ($env{'request.course.id'}) { return ''; }
 4334:     $coursedombuf{$env{'request.course.id'}}=
 4335:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4336:     $coursenumbuf{$env{'request.course.id'}}=
 4337:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4338:     $coursehombuf{$env{'request.course.id'}}=
 4339:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4340:     $coursedescrbuf{$env{'request.course.id'}}=
 4341:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4342:     $courseinstcodebuf{$env{'request.course.id'}}=
 4343:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4344:     $courseownerbuf{$env{'request.course.id'}}=
 4345:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4346:     $coursetypebuf{$env{'request.course.id'}}=
 4347:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4348:     if (defined $courselogs{$env{'request.course.id'}}) {
 4349: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4350:     } else {
 4351: 	$courselogs{$env{'request.course.id'}}.=$what;
 4352:     }
 4353:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4354: 	&flushcourselogs();
 4355:     }
 4356: }
 4357: 
 4358: sub courseacclog {
 4359:     my $fnsymb=shift;
 4360:     unless ($env{'request.course.id'}) { return ''; }
 4361:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4362:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4363:         $what.=':POST';
 4364:         # FIXME: Probably ought to escape things....
 4365: 	foreach my $key (keys(%env)) {
 4366:             if ($key=~/^form\.(.*)/) {
 4367:                 my $formitem = $1;
 4368:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4369:                     $what.=':'.$formitem.'='.$env{$key};
 4370:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4371:                     $what.=':'.$formitem.'='.$env{$key};
 4372:                 }
 4373:             }
 4374:         }
 4375:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4376:         # FIXME: We should not be depending on a form parameter that someone
 4377:         # editing lonsearchcat.pm might change in the future.
 4378:         if ($env{'form.phase'} eq 'course_search') {
 4379:             $what.= ':POST';
 4380:             # FIXME: Probably ought to escape things....
 4381:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4382:                                  'crsdiscuss') {
 4383:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4384:             }
 4385:         }
 4386:     }
 4387:     &courselog($what);
 4388: }
 4389: 
 4390: sub countacc {
 4391:     my $url=&declutter(shift);
 4392:     return if (! defined($url) || $url eq '');
 4393:     unless ($env{'request.course.id'}) { return ''; }
 4394: #
 4395: # Mark that this url was used in this course
 4396: #
 4397:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4398: #
 4399: # Increase the access count for this resource in this child process
 4400: #
 4401:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4402:     $accesshash{$key}++;
 4403: }
 4404: 
 4405: sub linklog {
 4406:     my ($from,$to)=@_;
 4407:     $from=&declutter($from);
 4408:     $to=&declutter($to);
 4409:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4410:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4411: }
 4412: 
 4413: sub statslog {
 4414:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4415:     if ($users<2) { return; }
 4416:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4417:             'course'       => $env{'request.course.id'},
 4418:             'sections'     => '"all"',
 4419:             'num_students' => $users,
 4420:             'part'         => $part,
 4421:             'symb'         => $symb,
 4422:             'mean_tries'   => $av_attempts,
 4423:             'deg_of_diff'  => $degdiff});
 4424:     foreach my $key (keys(%dynstore)) {
 4425:         $accesshash{$key}=$dynstore{$key};
 4426:     }
 4427: }
 4428:   
 4429: sub userrolelog {
 4430:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4431:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4432:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4433:        $userrolehash
 4434:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4435:                     =$tend.':'.$tstart;
 4436:     }
 4437:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4438:        $userrolehash
 4439:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4440:                     =$tend.':'.$tstart;
 4441:     }
 4442:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4443:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4444:        $domainrolehash
 4445:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4446:                     = $tend.':'.$tstart;
 4447:     }
 4448: }
 4449: 
 4450: sub courserolelog {
 4451:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4452:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4453:         my $cdom = $1;
 4454:         my $cnum = $2;
 4455:         my $sec = $3;
 4456:         my $namespace = 'rolelog';
 4457:         my %storehash = (
 4458:                            role    => $trole,
 4459:                            start   => $tstart,
 4460:                            end     => $tend,
 4461:                            selfenroll => $selfenroll,
 4462:                            context    => $context,
 4463:                         );
 4464:         if ($trole eq 'gr') {
 4465:             $namespace = 'groupslog';
 4466:             $storehash{'group'} = $sec;
 4467:         } else {
 4468:             $storehash{'section'} = $sec;
 4469:         }
 4470:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4471:                    $domain,$cnum,$cdom);
 4472:         if (($trole ne 'st') || ($sec ne '')) {
 4473:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4474:         }
 4475:     }
 4476:     return;
 4477: }
 4478: 
 4479: sub domainrolelog {
 4480:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4481:     if ($area =~ m{^/($match_domain)/$}) {
 4482:         my $cdom = $1;
 4483:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4484:         my $namespace = 'rolelog';
 4485:         my %storehash = (
 4486:                            role    => $trole,
 4487:                            start   => $tstart,
 4488:                            end     => $tend,
 4489:                            context => $context,
 4490:                         );
 4491:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4492:                    $domain,$domconfiguser,$cdom);
 4493:     }
 4494:     return;
 4495: 
 4496: }
 4497: 
 4498: sub coauthorrolelog {
 4499:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4500:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4501:         my $audom = $1;
 4502:         my $auname = $2;
 4503:         my $namespace = 'rolelog';
 4504:         my %storehash = (
 4505:                            role    => $trole,
 4506:                            start   => $tstart,
 4507:                            end     => $tend,
 4508:                            context => $context,
 4509:                         );
 4510:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4511:                    $domain,$auname,$audom);
 4512:     }
 4513:     return;
 4514: }
 4515: 
 4516: sub get_course_adv_roles {
 4517:     my ($cid,$codes) = @_;
 4518:     $cid=$env{'request.course.id'} unless (defined($cid));
 4519:     my %coursehash=&coursedescription($cid);
 4520:     my $crstype = &Apache::loncommon::course_type($cid);
 4521:     my %nothide=();
 4522:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4523:         if ($user !~ /:/) {
 4524: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4525:         } else {
 4526:             $nothide{$user}=1;
 4527:         }
 4528:     }
 4529:     my @possdoms = ($coursehash{'domain'});
 4530:     if ($coursehash{'checkforpriv'}) {
 4531:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4532:     }
 4533:     my %returnhash=();
 4534:     my %dumphash=
 4535:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4536:     my $now=time;
 4537:     my %privileged;
 4538:     foreach my $entry (keys(%dumphash)) {
 4539: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4540:         if (($tstart) && ($tstart<0)) { next; }
 4541:         if (($tend) && ($tend<$now)) { next; }
 4542:         if (($tstart) && ($now<$tstart)) { next; }
 4543:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4544: 	if ($username eq '' || $domain eq '') { next; }
 4545:         if ((&privileged($username,$domain,\@possdoms)) &&
 4546:             (!$nothide{$username.':'.$domain})) { next; }
 4547: 	if ($role eq 'cr') { next; }
 4548:         if ($codes) {
 4549:             if ($section) { $role .= ':'.$section; }
 4550:             if ($returnhash{$role}) {
 4551:                 $returnhash{$role}.=','.$username.':'.$domain;
 4552:             } else {
 4553:                 $returnhash{$role}=$username.':'.$domain;
 4554:             }
 4555:         } else {
 4556:             my $key=&plaintext($role,$crstype);
 4557:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4558:             if ($returnhash{$key}) {
 4559: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4560:             } else {
 4561:                 $returnhash{$key}=$username.':'.$domain;
 4562:             }
 4563:         }
 4564:     }
 4565:     return %returnhash;
 4566: }
 4567: 
 4568: sub get_my_roles {
 4569:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4570:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4571:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4572:     my (%dumphash,%nothide);
 4573:     if ($context eq 'userroles') {
 4574:         %dumphash = &dump('roles',$udom,$uname);
 4575:     } else {
 4576:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4577:         if ($hidepriv) {
 4578:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4579:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4580:                 if ($user !~ /:/) {
 4581:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4582:                 } else {
 4583:                     $nothide{$user} = 1;
 4584:                 }
 4585:             }
 4586:         }
 4587:     }
 4588:     my %returnhash=();
 4589:     my $now=time;
 4590:     my %privileged;
 4591:     foreach my $entry (keys(%dumphash)) {
 4592:         my ($role,$tend,$tstart);
 4593:         if ($context eq 'userroles') {
 4594:             next if ($entry =~ /^rolesdef/);
 4595: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4596:         } else {
 4597:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4598:         }
 4599:         if (($tstart) && ($tstart<0)) { next; }
 4600:         my $status = 'active';
 4601:         if (($tend) && ($tend<=$now)) {
 4602:             $status = 'previous';
 4603:         } 
 4604:         if (($tstart) && ($now<$tstart)) {
 4605:             $status = 'future';
 4606:         }
 4607:         if (ref($types) eq 'ARRAY') {
 4608:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4609:                 next;
 4610:             } 
 4611:         } else {
 4612:             if ($status ne 'active') {
 4613:                 next;
 4614:             }
 4615:         }
 4616:         my ($rolecode,$username,$domain,$section,$area);
 4617:         if ($context eq 'userroles') {
 4618:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4619:             (undef,$domain,$username,$section) = split(/\//,$area);
 4620:         } else {
 4621:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4622:         }
 4623:         if (ref($roledoms) eq 'ARRAY') {
 4624:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4625:                 next;
 4626:             }
 4627:         }
 4628:         if (ref($roles) eq 'ARRAY') {
 4629:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4630:                 if ($role =~ /^cr\//) {
 4631:                     if (!grep(/^cr$/,@{$roles})) {
 4632:                         next;
 4633:                     }
 4634:                 } elsif ($role =~ /^gr\//) {
 4635:                     if (!grep(/^gr$/,@{$roles})) {
 4636:                         next;
 4637:                     }
 4638:                 } else {
 4639:                     next;
 4640:                 }
 4641:             }
 4642:         }
 4643:         if ($hidepriv) {
 4644:             my @privroles = ('dc','su');
 4645:             if ($context eq 'userroles') {
 4646:                 next if (grep(/^\Q$role\E$/,@privroles));
 4647:             } else {
 4648:                 my $possdoms = [$domain];
 4649:                 if (ref($roledoms) eq 'ARRAY') {
 4650:                    push(@{$possdoms},@{$roledoms}); 
 4651:                 }
 4652:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4653:                     if (!$nothide{$username.':'.$domain}) {
 4654:                         next;
 4655:                     }
 4656:                 }
 4657:             }
 4658:         }
 4659:         if ($withsec) {
 4660:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4661:                 $tstart.':'.$tend;
 4662:         } else {
 4663:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4664:         }
 4665:     }
 4666:     return %returnhash;
 4667: }
 4668: 
 4669: sub get_all_adhocroles {
 4670:     my ($dom) = @_;
 4671:     my @roles_by_num = ();
 4672:     my %domdefaults = &get_domain_defaults($dom);
 4673:     my (%description,%access_in_dom,%access_info);
 4674:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4675:         my $count = 0;
 4676:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4677:         my %ordered;
 4678:         foreach my $role (sort(keys(%domcurrent))) {
 4679:             my ($order,$desc,$access_in_dom);
 4680:             if (ref($domcurrent{$role}) eq 'HASH') {
 4681:                 $order = $domcurrent{$role}{'order'};
 4682:                 $desc = $domcurrent{$role}{'desc'};
 4683:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4684:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4685:             }
 4686:             if ($order eq '') {
 4687:                 $order = $count;
 4688:             }
 4689:             $ordered{$order} = $role;
 4690:             if ($desc ne '') {
 4691:                 $description{$role} = $desc;
 4692:             } else {
 4693:                 $description{$role}= $role;
 4694:             }
 4695:             $count++;
 4696:         }
 4697:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4698:             push(@roles_by_num,$ordered{$item});
 4699:         }
 4700:     }
 4701:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4702: }
 4703: 
 4704: sub get_my_adhocroles {
 4705:     my ($cid,$checkreg) = @_;
 4706:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4707:     if ($env{'request.course.id'} eq $cid) {
 4708:         $cdom = $env{'course.'.$cid.'.domain'};
 4709:         $cnum = $env{'course.'.$cid.'.num'};
 4710:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4711:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4712:         $cdom = $1;
 4713:         $cnum = $2;
 4714:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4715:                                      $cdom,$cnum);
 4716:     }
 4717:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4718:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4719:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4720:         if ($rosterhash{$user} ne '') {
 4721:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4722:             return ([],{}) if ($type eq 'auto');
 4723:         }
 4724:     }
 4725:     if (($cdom ne '') && ($cnum ne ''))  {
 4726:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4727:             my $then=$env{'user.login.time'};
 4728:             my $update=$env{'user.update.time'};
 4729:             if (!$update) {
 4730:                 $update = $then;
 4731:             }
 4732:             my @liveroles;
 4733:             foreach my $role ('dh','da') {
 4734:                 if ($env{"user.role.$role./$cdom/"}) {
 4735:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4736:                     my $limit = $update;
 4737:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4738:                         $limit = $then;
 4739:                     }
 4740:                     my $activerole = 1;
 4741:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4742:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4743:                     if ($activerole) {
 4744:                         push(@liveroles,$role);
 4745:                     }
 4746:                 }
 4747:             }
 4748:             if (@liveroles) {
 4749:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4750:                     my ($accessref,$accessinfo,%access_in_dom);
 4751:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4752:                     if (ref($roles_by_num) eq 'ARRAY') {
 4753:                         if (@{$roles_by_num}) {
 4754:                             my %settings;
 4755:                             if ($env{'request.course.id'} eq $cid) {
 4756:                                 foreach my $envkey (keys(%env)) {
 4757:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4758:                                         $settings{$1} = $env{$envkey};
 4759:                                     }
 4760:                                 }
 4761:                             } else {
 4762:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4763:                             }
 4764:                             my %setincrs;
 4765:                             if ($settings{'internal.adhocaccess'}) {
 4766:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4767:                             }
 4768:                             my @statuses;
 4769:                             if ($env{'environment.inststatus'}) {
 4770:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4771:                             }
 4772:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4773:                             if (ref($accessref) eq 'HASH') {
 4774:                                 %access_in_dom = %{$accessref};
 4775:                             }
 4776:                             foreach my $role (@{$roles_by_num}) {
 4777:                                 my ($curraccess,@okstatus,@personnel);
 4778:                                 if ($setincrs{$role}) {
 4779:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4780:                                     if ($curraccess eq 'status') {
 4781:                                         @okstatus = split(/\&/,$rest);
 4782:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4783:                                         @personnel = split(/\&/,$rest);
 4784:                                     }
 4785:                                 } else {
 4786:                                     $curraccess = $access_in_dom{$role};
 4787:                                     if (ref($accessinfo) eq 'HASH') {
 4788:                                         if ($curraccess eq 'status') {
 4789:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4790:                                                 @okstatus = @{$accessinfo->{$role}};
 4791:                                             }
 4792:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4793:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4794:                                                 @personnel = @{$accessinfo->{$role}};
 4795:                                             }
 4796:                                         }
 4797:                                     }
 4798:                                 }
 4799:                                 if ($curraccess eq 'none') {
 4800:                                     next;
 4801:                                 } elsif ($curraccess eq 'all') {
 4802:                                     push(@possroles,$role);
 4803:                                 } elsif ($curraccess eq 'dh') {
 4804:                                     if (grep(/^dh$/,@liveroles)) {
 4805:                                         push(@possroles,$role);
 4806:                                     } else {
 4807:                                         next;
 4808:                                     }
 4809:                                 } elsif ($curraccess eq 'da') {
 4810:                                     if (grep(/^da$/,@liveroles)) {
 4811:                                         push(@possroles,$role);
 4812:                                     } else {
 4813:                                         next;
 4814:                                     }
 4815:                                 } elsif ($curraccess eq 'status') {
 4816:                                     if (@okstatus) {
 4817:                                         if (!@statuses) {
 4818:                                             if (grep(/^default$/,@okstatus)) {
 4819:                                                 push(@possroles,$role);
 4820:                                             }
 4821:                                         } else {
 4822:                                             foreach my $status (@okstatus) {
 4823:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 4824:                                                     push(@possroles,$role);
 4825:                                                     last;
 4826:                                                 }
 4827:                                             }
 4828:                                         }
 4829:                                     }
 4830:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4831:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 4832:                                         if ($curraccess eq 'exc') {
 4833:                                             push(@possroles,$role);
 4834:                                         }
 4835:                                     } elsif ($curraccess eq 'inc') {
 4836:                                         push(@possroles,$role);
 4837:                                     }
 4838:                                 }
 4839:                             }
 4840:                         }
 4841:                     }
 4842:                 }
 4843:             }
 4844:         }
 4845:     }
 4846:     unless (ref($description) eq 'HASH') {
 4847:         if (ref($roles_by_num) eq 'ARRAY') {
 4848:             my %desc;
 4849:             map { $desc{$_} = $_; } (@{$roles_by_num});
 4850:             $description = \%desc;
 4851:         } else {
 4852:             $description = {};
 4853:         }
 4854:     }
 4855:     return (\@possroles,$description);
 4856: }
 4857: 
 4858: # ----------------------------------------------------- Frontpage Announcements
 4859: #
 4860: #
 4861: 
 4862: sub postannounce {
 4863:     my ($server,$text)=@_;
 4864:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4865:     unless ($text=~/\w/) { $text=''; }
 4866:     return &reply('setannounce:'.&escape($text),$server);
 4867: }
 4868: 
 4869: sub getannounce {
 4870: 
 4871:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4872: 	my $announcement='';
 4873: 	while (my $line = <$fh>) { $announcement .= $line; }
 4874: 	close($fh);
 4875: 	if ($announcement=~/\w/) { 
 4876: 	    return 
 4877:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4878:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4879: 	} else {
 4880: 	    return '';
 4881: 	}
 4882:     } else {
 4883: 	return '';
 4884:     }
 4885: }
 4886: 
 4887: # ---------------------------------------------------------- Course ID routines
 4888: # Deal with domain's nohist_courseid.db files
 4889: #
 4890: 
 4891: sub courseidput {
 4892:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4893:     return unless (ref($storehash) eq 'HASH');
 4894:     my $outcome;
 4895:     if ($caller eq 'timeonly') {
 4896:         my $cids = '';
 4897:         foreach my $item (keys(%$storehash)) {
 4898:             $cids.=&escape($item).'&';
 4899:         }
 4900:         $cids=~s/\&$//;
 4901:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4902:                           $coursehome);       
 4903:     } else {
 4904:         my $items = '';
 4905:         foreach my $item (keys(%$storehash)) {
 4906:             $items.= &escape($item).'='.
 4907:                      &freeze_escape($$storehash{$item}).'&';
 4908:         }
 4909:         $items=~s/\&$//;
 4910:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4911:                           $coursehome);
 4912:     }
 4913:     if ($outcome eq 'unknown_cmd') {
 4914:         my $what;
 4915:         foreach my $cid (keys(%$storehash)) {
 4916:             $what .= &escape($cid).'=';
 4917:             foreach my $item ('description','inst_code','owner','type') {
 4918:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4919:             }
 4920:             $what =~ s/\:$/&/;
 4921:         }
 4922:         $what =~ s/\&$//;  
 4923:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4924:     } else {
 4925:         return $outcome;
 4926:     }
 4927: }
 4928: 
 4929: sub courseiddump {
 4930:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4931:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4932:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4933:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4934:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 4935:     my $as_hash = 1;
 4936:     my %returnhash;
 4937:     if (!$domfilter) { $domfilter=''; }
 4938:     my %libserv = &all_library();
 4939:     foreach my $tryserver (keys(%libserv)) {
 4940:         if ( (  $hostidflag == 1 
 4941: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4942: 	     || (!defined($hostidflag)) ) {
 4943: 
 4944: 	    if (($domfilter eq '') ||
 4945: 		(&host_domain($tryserver) eq $domfilter)) {
 4946:                 my $rep;
 4947:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4948:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4949:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4950:                                 &escape($descfilter), &escape($instcodefilter), 
 4951:                                 &escape($ownerfilter), &escape($coursefilter),
 4952:                                 &escape($typefilter), &escape($regexp_ok), 
 4953:                                 $as_hash, &escape($selfenrollonly), 
 4954:                                 &escape($catfilter), $showhidden, $caller, 
 4955:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4956:                                 &escape($createdbefore), &escape($createdafter), 
 4957:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 4958:                                 $reqcrsdom,&escape($reqinstcode))));
 4959:                 } else {
 4960:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4961:                              $sincefilter.':'.&escape($descfilter).':'.
 4962:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4963:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4964:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4965:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4966:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4967:                              &escape($cc_clone).':'.$cloneonly.':'.
 4968:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4969:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 4970:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 4971:                 }
 4972:                      
 4973:                 my @pairs=split(/\&/,$rep);
 4974:                 foreach my $item (@pairs) {
 4975:                     my ($key,$value)=split(/\=/,$item,2);
 4976:                     $key = &unescape($key);
 4977:                     next if ($key =~ /^error: 2 /);
 4978:                     my $result = &thaw_unescape($value);
 4979:                     if (ref($result) eq 'HASH') {
 4980:                         $returnhash{$key}=$result;
 4981:                     } else {
 4982:                         my @responses = split(/:/,$value);
 4983:                         my @items = ('description','inst_code','owner','type');
 4984:                         for (my $i=0; $i<@responses; $i++) {
 4985:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4986:                         }
 4987:                     }
 4988:                 }
 4989:             }
 4990:         }
 4991:     }
 4992:     return %returnhash;
 4993: }
 4994: 
 4995: sub courselastaccess {
 4996:     my ($cdom,$cnum,$hostidref) = @_;
 4997:     my %returnhash;
 4998:     if ($cdom && $cnum) {
 4999:         my $chome = &homeserver($cnum,$cdom);
 5000:         if ($chome ne 'no_host') {
 5001:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5002:             &extract_lastaccess(\%returnhash,$rep);
 5003:         }
 5004:     } else {
 5005:         if (!$cdom) { $cdom=''; }
 5006:         my %libserv = &all_library();
 5007:         foreach my $tryserver (keys(%libserv)) {
 5008:             if (ref($hostidref) eq 'ARRAY') {
 5009:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5010:             } 
 5011:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5012:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5013:                 &extract_lastaccess(\%returnhash,$rep);
 5014:             }
 5015:         }
 5016:     }
 5017:     return %returnhash;
 5018: }
 5019: 
 5020: sub extract_lastaccess {
 5021:     my ($returnhash,$rep) = @_;
 5022:     if (ref($returnhash) eq 'HASH') {
 5023:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5024:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5025:                  $rep eq '') {
 5026:             my @pairs=split(/\&/,$rep);
 5027:             foreach my $item (@pairs) {
 5028:                 my ($key,$value)=split(/\=/,$item,2);
 5029:                 $key = &unescape($key);
 5030:                 next if ($key =~ /^error: 2 /);
 5031:                 $returnhash->{$key} = &thaw_unescape($value);
 5032:             }
 5033:         }
 5034:     }
 5035:     return;
 5036: }
 5037: 
 5038: # ---------------------------------------------------------- DC e-mail
 5039: 
 5040: sub dcmailput {
 5041:     my ($domain,$msgid,$message,$server)=@_;
 5042:     my $status = &Apache::lonnet::critical(
 5043:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5044:        &escape($message),$server);
 5045:     return $status;
 5046: }
 5047: 
 5048: sub dcmaildump {
 5049:     my ($dom,$startdate,$enddate,$senders) = @_;
 5050:     my %returnhash=();
 5051: 
 5052:     if (defined(&domain($dom,'primary'))) {
 5053:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5054:                                                          &escape($enddate).':';
 5055: 	my @esc_senders=map { &escape($_)} @$senders;
 5056: 	$cmd.=&escape(join('&',@esc_senders));
 5057: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5058:             my ($key,$value) = split(/\=/,$line,2);
 5059:             if (($key) && ($value)) {
 5060:                 $returnhash{&unescape($key)} = &unescape($value);
 5061:             }
 5062:         }
 5063:     }
 5064:     return %returnhash;
 5065: }
 5066: # ---------------------------------------------------------- Domain roles
 5067: 
 5068: sub get_domain_roles {
 5069:     my ($dom,$roles,$startdate,$enddate)=@_;
 5070:     if ((!defined($startdate)) || ($startdate eq '')) {
 5071:         $startdate = '.';
 5072:     }
 5073:     if ((!defined($enddate)) || ($enddate eq '')) {
 5074:         $enddate = '.';
 5075:     }
 5076:     my $rolelist;
 5077:     if (ref($roles) eq 'ARRAY') {
 5078:         $rolelist = join('&',@{$roles});
 5079:     }
 5080:     my %personnel = ();
 5081: 
 5082:     my %servers = &get_servers($dom,'library');
 5083:     foreach my $tryserver (keys(%servers)) {
 5084: 	%{$personnel{$tryserver}}=();
 5085: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5086: 					    &escape($startdate).':'.
 5087: 					    &escape($enddate).':'.
 5088: 					    &escape($rolelist), $tryserver))) {
 5089: 	    my ($key,$value) = split(/\=/,$line,2);
 5090: 	    if (($key) && ($value)) {
 5091: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5092: 	    }
 5093: 	}
 5094:     }
 5095:     return %personnel;
 5096: }
 5097: 
 5098: sub get_active_domroles {
 5099:     my ($dom,$roles) = @_;
 5100:     return () unless (ref($roles) eq 'ARRAY');
 5101:     my $now = time;
 5102:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5103:     my %domroles;
 5104:     foreach my $server (keys(%dompersonnel)) {
 5105:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5106:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5107:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5108:         }
 5109:     }
 5110:     return %domroles;
 5111: }
 5112: 
 5113: # ----------------------------------------------------------- Interval timing 
 5114: 
 5115: {
 5116: # Caches needed for speedup of navmaps
 5117: # We don't want to cache this for very long at all (5 seconds at most)
 5118: # 
 5119: # The user for whom we cache
 5120: my $cachedkey='';
 5121: # The cached times for this user
 5122: my %cachedtimes=();
 5123: # When this was last done
 5124: my $cachedtime='';
 5125: 
 5126: sub load_all_first_access {
 5127:     my ($uname,$udom,$ignorecache)=@_;
 5128:     if (($cachedkey eq $uname.':'.$udom) &&
 5129:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5130:         (!$ignorecache)) {
 5131:         return;
 5132:     }
 5133:     $cachedtime=time;
 5134:     $cachedkey=$uname.':'.$udom;
 5135:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5136: }
 5137: 
 5138: sub get_first_access {
 5139:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5140:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5141:     if ($argsymb) { $symb=$argsymb; }
 5142:     my ($map,$id,$res)=&decode_symb($symb);
 5143:     if ($argmap) { $map = $argmap; }
 5144:     if ($type eq 'course') {
 5145: 	$res='course';
 5146:     } elsif ($type eq 'map') {
 5147: 	$res=&symbread($map);
 5148:     } else {
 5149: 	$res=$symb;
 5150:     }
 5151:     &load_all_first_access($uname,$udom,$ignorecache);
 5152:     return $cachedtimes{"$courseid\0$res"};
 5153: }
 5154: 
 5155: sub set_first_access {
 5156:     my ($type,$interval)=@_;
 5157:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5158:     my ($map,$id,$res)=&decode_symb($symb);
 5159:     if ($type eq 'course') {
 5160: 	$res='course';
 5161:     } elsif ($type eq 'map') {
 5162: 	$res=&symbread($map);
 5163:     } else {
 5164: 	$res=$symb;
 5165:     }
 5166:     $cachedkey='';
 5167:     my $firstaccess=&get_first_access($type,$symb,$map);
 5168:     if (!$firstaccess) {
 5169:         my $start = time;
 5170: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5171:                           $udom,$uname);
 5172:         if ($putres eq 'ok') {
 5173:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5174:                  $udom,$uname); 
 5175:             &appenv(
 5176:                      {
 5177:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5178:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5179:                      }
 5180:                   );
 5181:         }
 5182:         return $putres;
 5183:     }
 5184:     return 'already_set';
 5185: }
 5186: }
 5187: 
 5188: # --------------------------------------------- Set Expire Date for Spreadsheet
 5189: 
 5190: sub expirespread {
 5191:     my ($uname,$udom,$stype,$usymb)=@_;
 5192:     my $cid=$env{'request.course.id'}; 
 5193:     if ($cid) {
 5194:        my $now=time;
 5195:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5196:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5197:                             $env{'course.'.$cid.'.num'}.
 5198: 	        	    ':nohist_expirationdates:'.
 5199:                             &escape($key).'='.$now,
 5200:                             $env{'course.'.$cid.'.home'})
 5201:     }
 5202:     return 'ok';
 5203: }
 5204: 
 5205: # ----------------------------------------------------- Devalidate Spreadsheets
 5206: 
 5207: sub devalidate {
 5208:     my ($symb,$uname,$udom)=@_;
 5209:     my $cid=$env{'request.course.id'}; 
 5210:     if ($cid) {
 5211:         # delete the stored spreadsheets for
 5212:         # - the student level sheet of this user in course's homespace
 5213:         # - the assessment level sheet for this resource 
 5214:         #   for this user in user's homespace
 5215: 	# - current conditional state info
 5216: 	my $key=$uname.':'.$udom.':';
 5217:         my $status=
 5218: 	    &del('nohist_calculatedsheets',
 5219: 		 [$key.'studentcalc:'],
 5220: 		 $env{'course.'.$cid.'.domain'},
 5221: 		 $env{'course.'.$cid.'.num'})
 5222: 		.' '.
 5223: 	    &del('nohist_calculatedsheets_'.$cid,
 5224: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5225:         unless ($status eq 'ok ok') {
 5226:            &logthis('Could not devalidate spreadsheet '.
 5227:                     $uname.' at '.$udom.' for '.
 5228: 		    $symb.': '.$status);
 5229:         }
 5230: 	&delenv('user.state.'.$cid);
 5231:     }
 5232: }
 5233: 
 5234: sub get_scalar {
 5235:     my ($string,$end) = @_;
 5236:     my $value;
 5237:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5238: 	$value = $1;
 5239:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5240: 	$value = $1;
 5241:     }
 5242:     return &unescape($value);
 5243: }
 5244: 
 5245: sub array2str {
 5246:   my (@array) = @_;
 5247:   my $result=&arrayref2str(\@array);
 5248:   $result=~s/^__ARRAY_REF__//;
 5249:   $result=~s/__END_ARRAY_REF__$//;
 5250:   return $result;
 5251: }
 5252: 
 5253: sub arrayref2str {
 5254:   my ($arrayref) = @_;
 5255:   my $result='__ARRAY_REF__';
 5256:   foreach my $elem (@$arrayref) {
 5257:     if(ref($elem) eq 'ARRAY') {
 5258:       $result.=&arrayref2str($elem).'&';
 5259:     } elsif(ref($elem) eq 'HASH') {
 5260:       $result.=&hashref2str($elem).'&';
 5261:     } elsif(ref($elem)) {
 5262:       #print("Got a ref of ".(ref($elem))." skipping.");
 5263:     } else {
 5264:       $result.=&escape($elem).'&';
 5265:     }
 5266:   }
 5267:   $result=~s/\&$//;
 5268:   $result .= '__END_ARRAY_REF__';
 5269:   return $result;
 5270: }
 5271: 
 5272: sub hash2str {
 5273:   my (%hash) = @_;
 5274:   my $result=&hashref2str(\%hash);
 5275:   $result=~s/^__HASH_REF__//;
 5276:   $result=~s/__END_HASH_REF__$//;
 5277:   return $result;
 5278: }
 5279: 
 5280: sub hashref2str {
 5281:   my ($hashref)=@_;
 5282:   my $result='__HASH_REF__';
 5283:   foreach my $key (sort(keys(%$hashref))) {
 5284:     if (ref($key) eq 'ARRAY') {
 5285:       $result.=&arrayref2str($key).'=';
 5286:     } elsif (ref($key) eq 'HASH') {
 5287:       $result.=&hashref2str($key).'=';
 5288:     } elsif (ref($key)) {
 5289:       $result.='=';
 5290:       #print("Got a ref of ".(ref($key))." skipping.");
 5291:     } else {
 5292: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5293:     }
 5294: 
 5295:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5296:       $result.=&arrayref2str($hashref->{$key}).'&';
 5297:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5298:       $result.=&hashref2str($hashref->{$key}).'&';
 5299:     } elsif(ref($hashref->{$key})) {
 5300:        $result.='&';
 5301:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5302:     } else {
 5303:       $result.=&escape($hashref->{$key}).'&';
 5304:     }
 5305:   }
 5306:   $result=~s/\&$//;
 5307:   $result .= '__END_HASH_REF__';
 5308:   return $result;
 5309: }
 5310: 
 5311: sub str2hash {
 5312:     my ($string)=@_;
 5313:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5314:     return %$hash;
 5315: }
 5316: 
 5317: sub str2hashref {
 5318:   my ($string) = @_;
 5319: 
 5320:   my %hash;
 5321: 
 5322:   if($string !~ /^__HASH_REF__/) {
 5323:       if (! ($string eq '' || !defined($string))) {
 5324: 	  $hash{'error'}='Not hash reference';
 5325:       }
 5326:       return (\%hash, $string);
 5327:   }
 5328: 
 5329:   $string =~ s/^__HASH_REF__//;
 5330: 
 5331:   while($string !~ /^__END_HASH_REF__/) {
 5332:       #key
 5333:       my $key='';
 5334:       if($string =~ /^__HASH_REF__/) {
 5335:           ($key, $string)=&str2hashref($string);
 5336:           if(defined($key->{'error'})) {
 5337:               $hash{'error'}='Bad data';
 5338:               return (\%hash, $string);
 5339:           }
 5340:       } elsif($string =~ /^__ARRAY_REF__/) {
 5341:           ($key, $string)=&str2arrayref($string);
 5342:           if($key->[0] eq 'Array reference error') {
 5343:               $hash{'error'}='Bad data';
 5344:               return (\%hash, $string);
 5345:           }
 5346:       } else {
 5347:           $string =~ s/^(.*?)=//;
 5348: 	  $key=&unescape($1);
 5349:       }
 5350:       $string =~ s/^=//;
 5351: 
 5352:       #value
 5353:       my $value='';
 5354:       if($string =~ /^__HASH_REF__/) {
 5355:           ($value, $string)=&str2hashref($string);
 5356:           if(defined($value->{'error'})) {
 5357:               $hash{'error'}='Bad data';
 5358:               return (\%hash, $string);
 5359:           }
 5360:       } elsif($string =~ /^__ARRAY_REF__/) {
 5361:           ($value, $string)=&str2arrayref($string);
 5362:           if($value->[0] eq 'Array reference error') {
 5363:               $hash{'error'}='Bad data';
 5364:               return (\%hash, $string);
 5365:           }
 5366:       } else {
 5367: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5368:       }
 5369:       $string =~ s/^&//;
 5370: 
 5371:       $hash{$key}=$value;
 5372:   }
 5373: 
 5374:   $string =~ s/^__END_HASH_REF__//;
 5375: 
 5376:   return (\%hash, $string);
 5377: }
 5378: 
 5379: sub str2array {
 5380:     my ($string)=@_;
 5381:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5382:     return @$array;
 5383: }
 5384: 
 5385: sub str2arrayref {
 5386:   my ($string) = @_;
 5387:   my @array;
 5388: 
 5389:   if($string !~ /^__ARRAY_REF__/) {
 5390:       if (! ($string eq '' || !defined($string))) {
 5391: 	  $array[0]='Array reference error';
 5392:       }
 5393:       return (\@array, $string);
 5394:   }
 5395: 
 5396:   $string =~ s/^__ARRAY_REF__//;
 5397: 
 5398:   while($string !~ /^__END_ARRAY_REF__/) {
 5399:       my $value='';
 5400:       if($string =~ /^__HASH_REF__/) {
 5401:           ($value, $string)=&str2hashref($string);
 5402:           if(defined($value->{'error'})) {
 5403:               $array[0] ='Array reference error';
 5404:               return (\@array, $string);
 5405:           }
 5406:       } elsif($string =~ /^__ARRAY_REF__/) {
 5407:           ($value, $string)=&str2arrayref($string);
 5408:           if($value->[0] eq 'Array reference error') {
 5409:               $array[0] ='Array reference error';
 5410:               return (\@array, $string);
 5411:           }
 5412:       } else {
 5413: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5414:       }
 5415:       $string =~ s/^&//;
 5416: 
 5417:       push(@array, $value);
 5418:   }
 5419: 
 5420:   $string =~ s/^__END_ARRAY_REF__//;
 5421: 
 5422:   return (\@array, $string);
 5423: }
 5424: 
 5425: # -------------------------------------------------------------------Temp Store
 5426: 
 5427: sub tmpreset {
 5428:   my ($symb,$namespace,$domain,$stuname) = @_;
 5429:   if (!$symb) {
 5430:     $symb=&symbread();
 5431:     if (!$symb) { $symb= $env{'request.url'}; }
 5432:   }
 5433:   $symb=escape($symb);
 5434: 
 5435:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5436:   $namespace=~s/\//\_/g;
 5437:   $namespace=~s/\W//g;
 5438: 
 5439:   if (!$domain) { $domain=$env{'user.domain'}; }
 5440:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5441:   if ($domain eq 'public' && $stuname eq 'public') {
 5442:       $stuname=$ENV{'REMOTE_ADDR'};
 5443:   }
 5444:   my $path=LONCAPA::tempdir();
 5445:   my %hash;
 5446:   if (tie(%hash,'GDBM_File',
 5447: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5448: 	  &GDBM_WRCREAT(),0640)) {
 5449:     foreach my $key (keys(%hash)) {
 5450:       if ($key=~ /:$symb/) {
 5451: 	delete($hash{$key});
 5452:       }
 5453:     }
 5454:   }
 5455: }
 5456: 
 5457: sub tmpstore {
 5458:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5459: 
 5460:   if (!$symb) {
 5461:     $symb=&symbread();
 5462:     if (!$symb) { $symb= $env{'request.url'}; }
 5463:   }
 5464:   $symb=escape($symb);
 5465: 
 5466:   if (!$namespace) {
 5467:     # I don't think we would ever want to store this for a course.
 5468:     # it seems this will only be used if we don't have a course.
 5469:     #$namespace=$env{'request.course.id'};
 5470:     #if (!$namespace) {
 5471:       $namespace=$env{'request.state'};
 5472:     #}
 5473:   }
 5474:   $namespace=~s/\//\_/g;
 5475:   $namespace=~s/\W//g;
 5476:   if (!$domain) { $domain=$env{'user.domain'}; }
 5477:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5478:   if ($domain eq 'public' && $stuname eq 'public') {
 5479:       $stuname=$ENV{'REMOTE_ADDR'};
 5480:   }
 5481:   my $now=time;
 5482:   my %hash;
 5483:   my $path=LONCAPA::tempdir();
 5484:   if (tie(%hash,'GDBM_File',
 5485: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5486: 	  &GDBM_WRCREAT(),0640)) {
 5487:     $hash{"version:$symb"}++;
 5488:     my $version=$hash{"version:$symb"};
 5489:     my $allkeys=''; 
 5490:     foreach my $key (keys(%$storehash)) {
 5491:       $allkeys.=$key.':';
 5492:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5493:     }
 5494:     $hash{"$version:$symb:timestamp"}=$now;
 5495:     $allkeys.='timestamp';
 5496:     $hash{"$version:keys:$symb"}=$allkeys;
 5497:     if (untie(%hash)) {
 5498:       return 'ok';
 5499:     } else {
 5500:       return "error:$!";
 5501:     }
 5502:   } else {
 5503:     return "error:$!";
 5504:   }
 5505: }
 5506: 
 5507: # -----------------------------------------------------------------Temp Restore
 5508: 
 5509: sub tmprestore {
 5510:   my ($symb,$namespace,$domain,$stuname) = @_;
 5511: 
 5512:   if (!$symb) {
 5513:     $symb=&symbread();
 5514:     if (!$symb) { $symb= $env{'request.url'}; }
 5515:   }
 5516:   $symb=escape($symb);
 5517: 
 5518:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5519: 
 5520:   if (!$domain) { $domain=$env{'user.domain'}; }
 5521:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5522:   if ($domain eq 'public' && $stuname eq 'public') {
 5523:       $stuname=$ENV{'REMOTE_ADDR'};
 5524:   }
 5525:   my %returnhash;
 5526:   $namespace=~s/\//\_/g;
 5527:   $namespace=~s/\W//g;
 5528:   my %hash;
 5529:   my $path=LONCAPA::tempdir();
 5530:   if (tie(%hash,'GDBM_File',
 5531: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5532: 	  &GDBM_READER(),0640)) {
 5533:     my $version=$hash{"version:$symb"};
 5534:     $returnhash{'version'}=$version;
 5535:     my $scope;
 5536:     for ($scope=1;$scope<=$version;$scope++) {
 5537:       my $vkeys=$hash{"$scope:keys:$symb"};
 5538:       my @keys=split(/:/,$vkeys);
 5539:       my $key;
 5540:       $returnhash{"$scope:keys"}=$vkeys;
 5541:       foreach $key (@keys) {
 5542: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5543: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5544:       }
 5545:     }
 5546:     if (!(untie(%hash))) {
 5547:       return "error:$!";
 5548:     }
 5549:   } else {
 5550:     return "error:$!";
 5551:   }
 5552:   return %returnhash;
 5553: }
 5554: 
 5555: # ----------------------------------------------------------------------- Store
 5556: 
 5557: sub store {
 5558:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5559:     my $home='';
 5560: 
 5561:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5562: 
 5563:     $symb=&symbclean($symb);
 5564:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5565: 
 5566:     if (!$domain) { $domain=$env{'user.domain'}; }
 5567:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5568: 
 5569:     &devalidate($symb,$stuname,$domain);
 5570: 
 5571:     $symb=escape($symb);
 5572:     if (!$namespace) { 
 5573:        unless ($namespace=$env{'request.course.id'}) { 
 5574:           return ''; 
 5575:        } 
 5576:     }
 5577:     if (!$home) { $home=$env{'user.home'}; }
 5578: 
 5579:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5580:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5581: 
 5582:     my $namevalue='';
 5583:     foreach my $key (keys(%$storehash)) {
 5584:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5585:     }
 5586:     $namevalue=~s/\&$//;
 5587:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5588:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5589: }
 5590: 
 5591: # -------------------------------------------------------------- Critical Store
 5592: 
 5593: sub cstore {
 5594:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5595:     my $home='';
 5596: 
 5597:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5598: 
 5599:     $symb=&symbclean($symb);
 5600:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5601: 
 5602:     if (!$domain) { $domain=$env{'user.domain'}; }
 5603:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5604: 
 5605:     &devalidate($symb,$stuname,$domain);
 5606: 
 5607:     $symb=escape($symb);
 5608:     if (!$namespace) { 
 5609:        unless ($namespace=$env{'request.course.id'}) { 
 5610:           return ''; 
 5611:        } 
 5612:     }
 5613:     if (!$home) { $home=$env{'user.home'}; }
 5614: 
 5615:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5616:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5617: 
 5618:     my $namevalue='';
 5619:     foreach my $key (keys(%$storehash)) {
 5620:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5621:     }
 5622:     $namevalue=~s/\&$//;
 5623:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5624:     return critical
 5625:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5626: }
 5627: 
 5628: # --------------------------------------------------------------------- Restore
 5629: 
 5630: sub restore {
 5631:     my ($symb,$namespace,$domain,$stuname) = @_;
 5632:     my $home='';
 5633: 
 5634:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5635: 
 5636:     if (!$symb) {
 5637:         return if ($namespace eq 'courserequests');
 5638:         unless ($symb=escape(&symbread())) { return ''; }
 5639:     } else {
 5640:         unless ($namespace eq 'courserequests') {
 5641:             $symb=&escape(&symbclean($symb));
 5642:         }
 5643:     }
 5644:     if (!$namespace) { 
 5645:        unless ($namespace=$env{'request.course.id'}) { 
 5646:           return ''; 
 5647:        } 
 5648:     }
 5649:     if (!$domain) { $domain=$env{'user.domain'}; }
 5650:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5651:     if (!$home) { $home=$env{'user.home'}; }
 5652:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5653: 
 5654:     my %returnhash=();
 5655:     foreach my $line (split(/\&/,$answer)) {
 5656: 	my ($name,$value)=split(/\=/,$line);
 5657:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5658:     }
 5659:     my $version;
 5660:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5661:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5662:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5663:        }
 5664:     }
 5665:     return %returnhash;
 5666: }
 5667: 
 5668: # ---------------------------------------------------------- Course Description
 5669: #
 5670: #  
 5671: 
 5672: sub coursedescription {
 5673:     my ($courseid,$args)=@_;
 5674:     $courseid=~s/^\///;
 5675:     $courseid=~s/\_/\//g;
 5676:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5677:     my $chome=&homeserver($cnum,$cdomain);
 5678:     my $normalid=$cdomain.'_'.$cnum;
 5679:     # need to always cache even if we get errors otherwise we keep 
 5680:     # trying and trying and trying to get the course description.
 5681:     my %envhash=();
 5682:     my %returnhash=();
 5683:     
 5684:     my $expiretime=600;
 5685:     if ($env{'request.course.id'} eq $normalid) {
 5686: 	$expiretime=120;
 5687:     }
 5688: 
 5689:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5690:     if (!$args->{'freshen_cache'}
 5691: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5692: 	foreach my $key (keys(%env)) {
 5693: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5694: 	    my ($setting) = $1;
 5695: 	    $returnhash{$setting} = $env{$key};
 5696: 	}
 5697: 	return %returnhash;
 5698:     }
 5699: 
 5700:     # get the data again
 5701: 
 5702:     if (!$args->{'one_time'}) {
 5703: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5704:     }
 5705: 
 5706:     if ($chome ne 'no_host') {
 5707:        %returnhash=&dump('environment',$cdomain,$cnum);
 5708:        if (!exists($returnhash{'con_lost'})) {
 5709: 	   my $username = $env{'user.name'}; # Defult username
 5710: 	   if(defined $args->{'user'}) {
 5711: 	       $username = $args->{'user'};
 5712: 	   }
 5713:            $returnhash{'home'}= $chome;
 5714: 	   $returnhash{'domain'} = $cdomain;
 5715: 	   $returnhash{'num'} = $cnum;
 5716:            if (!defined($returnhash{'type'})) {
 5717:                $returnhash{'type'} = 'Course';
 5718:            }
 5719:            while (my ($name,$value) = each %returnhash) {
 5720:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5721:            }
 5722:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5723:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5724: 	       $username.'_'.$cdomain.'_'.$cnum;
 5725:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5726:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5727:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5728:        }
 5729:     }
 5730:     if (!$args->{'one_time'}) {
 5731: 	&appenv(\%envhash);
 5732:     }
 5733:     return %returnhash;
 5734: }
 5735: 
 5736: sub update_released_required {
 5737:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5738:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5739:         $cid = $env{'request.course.id'};
 5740:         $cdom = $env{'course.'.$cid.'.domain'};
 5741:         $cnum = $env{'course.'.$cid.'.num'};
 5742:         $chome = $env{'course.'.$cid.'.home'};
 5743:     }
 5744:     if ($needsrelease) {
 5745:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5746:         my $needsupdate;
 5747:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5748:             $needsupdate = 1;
 5749:         } else {
 5750:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5751:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5752:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5753:                 $needsupdate = 1;
 5754:             }
 5755:         }
 5756:         if ($needsupdate) {
 5757:             my %needshash = (
 5758:                              'internal.releaserequired' => $needsrelease,
 5759:                             );
 5760:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5761:             if ($putresult eq 'ok') {
 5762:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5763:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5764:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5765:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5766:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5767:                 }
 5768:             }
 5769:         }
 5770:     }
 5771:     return;
 5772: }
 5773: 
 5774: # -------------------------------------------------See if a user is privileged
 5775: 
 5776: sub privileged {
 5777:     my ($username,$domain,$possdomains,$possroles)=@_;
 5778:     my $now = time;
 5779:     my $roles;
 5780:     if (ref($possroles) eq 'ARRAY') {
 5781:         $roles = $possroles; 
 5782:     } else {
 5783:         $roles = ['dc','su'];
 5784:     }
 5785:     if (ref($possdomains) eq 'ARRAY') {
 5786:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5787:         foreach my $dom (@{$possdomains}) {
 5788:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5789:                 (ref($privileged{$dom}) eq 'HASH')) {
 5790:                 foreach my $role (@{$roles}) {
 5791:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5792:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5793:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5794:                             return 1 unless (($end && $end < $now) ||
 5795:                                              ($start && $start > $now));
 5796:                         }
 5797:                     }
 5798:                 }
 5799:             }
 5800:         }
 5801:     } else {
 5802:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5803:         my $now = time;
 5804: 
 5805:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5806:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5807:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5808:                 return 1 unless ($tend && $tend < $now) 
 5809:                         or ($tstart && $tstart > $now);
 5810:             }
 5811:         }
 5812:     }
 5813:     return 0;
 5814: }
 5815: 
 5816: sub privileged_by_domain {
 5817:     my ($domains,$roles) = @_;
 5818:     my %privileged = ();
 5819:     my $cachetime = 60*60*24;
 5820:     my $now = time;
 5821:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5822:         return %privileged;
 5823:     }
 5824:     foreach my $dom (@{$domains}) {
 5825:         next if (ref($privileged{$dom}) eq 'HASH');
 5826:         my $needroles;
 5827:         foreach my $role (@{$roles}) {
 5828:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5829:             if (defined($cached)) {
 5830:                 if (ref($result) eq 'HASH') {
 5831:                     $privileged{$dom}{$role} = $result;
 5832:                 }
 5833:             } else {
 5834:                 $needroles = 1;
 5835:             }
 5836:         }
 5837:         if ($needroles) {
 5838:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5839:             $privileged{$dom} = {};
 5840:             foreach my $server (keys(%dompersonnel)) {
 5841:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5842:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5843:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5844:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5845:                         next if ($end && $end < $now);
 5846:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5847:                             $dompersonnel{$server}{$item};
 5848:                     }
 5849:                 }
 5850:             }
 5851:             if (ref($privileged{$dom}) eq 'HASH') {
 5852:                 foreach my $role (@{$roles}) {
 5853:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5854:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5855:                     } else {
 5856:                         my %hash = ();
 5857:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5858:                     }
 5859:                 }
 5860:             }
 5861:         }
 5862:     }
 5863:     return %privileged;
 5864: }
 5865: 
 5866: # -------------------------------------------------------- Get user privileges
 5867: 
 5868: sub rolesinit {
 5869:     my ($domain, $username) = @_;
 5870:     my %userroles = ('user.login.time' => time);
 5871:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5872: 
 5873:     # firstaccess and timerinterval are related to timed maps/resources. 
 5874:     # also, blocking can be triggered by an activating timer
 5875:     # it's saved in the user's %env.
 5876:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5877:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5878:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5879:         %timerintchk, %timerintenv);
 5880: 
 5881:     foreach my $key (keys(%firstaccess)) {
 5882:         my ($cid, $rest) = split(/\0/, $key);
 5883:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5884:     }
 5885: 
 5886:     foreach my $key (keys(%timerinterval)) {
 5887:         my ($cid,$rest) = split(/\0/,$key);
 5888:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5889:     }
 5890: 
 5891:     my %allroles=();
 5892:     my %allgroups=();
 5893: 
 5894:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5895:         my $role = $rolesdump{$area};
 5896:         $area =~ s/\_\w\w$//;
 5897: 
 5898:         my ($trole, $tend, $tstart, $group_privs);
 5899: 
 5900:         if ($role =~ /^cr/) {
 5901:         # Custom role, defined by a user 
 5902:         # e.g., user.role.cr/msu/smith/mynewrole
 5903:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5904:                 $trole = $1;
 5905:                 ($tend, $tstart) = split('_', $2);
 5906:             } else {
 5907:                 $trole = $role;
 5908:             }
 5909:         } elsif ($role =~ m|^gr/|) {
 5910:         # Role of member in a group, defined within a course/community
 5911:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5912:             ($trole, $tend, $tstart) = split(/_/, $role);
 5913:             next if $tstart eq '-1';
 5914:             ($trole, $group_privs) = split(/\//, $trole);
 5915:             $group_privs = &unescape($group_privs);
 5916:         } else {
 5917:         # Just a normal role, defined in roles.tab
 5918:             ($trole, $tend, $tstart) = split(/_/,$role);
 5919:         }
 5920: 
 5921:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5922:                  $username);
 5923:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5924: 
 5925:         # role expired or not available yet?
 5926:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5927:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5928: 
 5929:         next if $area eq '' or $trole eq '';
 5930: 
 5931:         my $spec = "$trole.$area";
 5932:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5933: 
 5934:         if ($trole =~ /^cr\//) {
 5935:         # Custom role, defined by a user
 5936:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5937:         } elsif ($trole eq 'gr') {
 5938:         # Role of a member in a group, defined within a course/community
 5939:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5940:             next;
 5941:         } else {
 5942:         # Normal role, defined in roles.tab
 5943:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5944:         }
 5945: 
 5946:         my $cid = $tdomain.'_'.$trest;
 5947:         unless ($firstaccchk{$cid}) {
 5948:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5949:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5950:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5951:                         $coursetimerstarts{$cid}{$item}; 
 5952:                 }
 5953:             }
 5954:             $firstaccchk{$cid} = 1;
 5955:         }
 5956:         unless ($timerintchk{$cid}) {
 5957:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5958:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5959:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5960:                        $coursetimerintervals{$cid}{$item};
 5961:                 }
 5962:             }
 5963:             $timerintchk{$cid} = 1;
 5964:         }
 5965:     }
 5966: 
 5967:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 5968:                                                           \%allroles, \%allgroups);
 5969:     $env{'user.adv'} = $userroles{'user.adv'};
 5970:     $env{'user.rar'} = $userroles{'user.rar'};
 5971: 
 5972:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5973: }
 5974: 
 5975: sub set_arearole {
 5976:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5977:     unless ($nolog) {
 5978: # log the associated role with the area
 5979:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5980:     }
 5981:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5982: }
 5983: 
 5984: sub custom_roleprivs {
 5985:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5986:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5987:     my $homsvr = &homeserver($rauthor,$rdomain);
 5988:     if (&hostname($homsvr) ne '') {
 5989:         my ($rdummy,$roledef)=
 5990:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5991:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5992:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5993:             if (defined($syspriv)) {
 5994:                 if ($trest =~ /^$match_community$/) {
 5995:                     $syspriv =~ s/bre\&S//; 
 5996:                 }
 5997:                 $$allroles{'cm./'}.=':'.$syspriv;
 5998:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5999:             }
 6000:             if ($tdomain ne '') {
 6001:                 if (defined($dompriv)) {
 6002:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6003:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6004:                 }
 6005:                 if (($trest ne '') && (defined($coursepriv))) {
 6006:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6007:                         my $rolename = $1;
 6008:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6009:                     }
 6010:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6011:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6012:                 }
 6013:             }
 6014:         }
 6015:     }
 6016: }
 6017: 
 6018: sub course_adhocrole_privs {
 6019:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6020:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6021:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6022:         my (%currprivs,%storeprivs);
 6023:         foreach my $item (split(/:/,$coursepriv)) {
 6024:             my ($priv,$restrict) = split(/\&/,$item);
 6025:             $currprivs{$priv} = $restrict;
 6026:         }
 6027:         my (%possadd,%possremove,%full);
 6028:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6029:             my ($priv,$restrict)=split(/\&/,$item);
 6030:             $full{$priv} = $restrict;
 6031:         }
 6032:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6033:              next if ($item eq '');
 6034:              my ($rule,$rest) = split(/=/,$item);
 6035:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6036:              foreach my $priv (split(/:/,$rest)) {
 6037:                  if ($priv ne '') {
 6038:                      if ($rule eq 'off') {
 6039:                          $possremove{$priv} = 1;
 6040:                      } else {
 6041:                          $possadd{$priv} = 1;
 6042:                      }
 6043:                  }
 6044:              }
 6045:          }
 6046:          foreach my $priv (sort(keys(%full))) {
 6047:              if (exists($currprivs{$priv})) {
 6048:                  unless (exists($possremove{$priv})) {
 6049:                      $storeprivs{$priv} = $currprivs{$priv};
 6050:                  }
 6051:              } elsif (exists($possadd{$priv})) {
 6052:                  $storeprivs{$priv} = $full{$priv};
 6053:              }
 6054:          }
 6055:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6056:      }
 6057:      return $coursepriv;
 6058: }
 6059: 
 6060: sub group_roleprivs {
 6061:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6062:     my $access = 1;
 6063:     my $now = time;
 6064:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6065:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6066:     if ($access) {
 6067:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6068:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6069:     }
 6070: }
 6071: 
 6072: sub standard_roleprivs {
 6073:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6074:     if (defined($pr{$trole.':s'})) {
 6075:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6076:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6077:     }
 6078:     if ($tdomain ne '') {
 6079:         if (defined($pr{$trole.':d'})) {
 6080:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6081:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6082:         }
 6083:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6084:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6085:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6086:         }
 6087:     }
 6088: }
 6089: 
 6090: sub set_userprivs {
 6091:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6092:     my $author=0;
 6093:     my $adv=0;
 6094:     my $rar=0;
 6095:     my %grouproles = ();
 6096:     if (keys(%{$allgroups}) > 0) {
 6097:         my @groupkeys; 
 6098:         foreach my $role (keys(%{$allroles})) {
 6099:             push(@groupkeys,$role);
 6100:         }
 6101:         if (ref($groups_roles) eq 'HASH') {
 6102:             foreach my $key (keys(%{$groups_roles})) {
 6103:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6104:                     push(@groupkeys,$key);
 6105:                 }
 6106:             }
 6107:         }
 6108:         if (@groupkeys > 0) {
 6109:             foreach my $role (@groupkeys) {
 6110:                 my ($trole,$area,$sec,$extendedarea);
 6111:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6112:                     $trole = $1;
 6113:                     $area = $2;
 6114:                     $sec = $3;
 6115:                     $extendedarea = $area.$sec;
 6116:                     if (exists($$allgroups{$area})) {
 6117:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6118:                             my $spec = $trole.'.'.$extendedarea;
 6119:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6120:                                                 $$allgroups{$area}{$group};
 6121:                         }
 6122:                     }
 6123:                 }
 6124:             }
 6125:         }
 6126:     }
 6127:     foreach my $group (keys(%grouproles)) {
 6128:         $$allroles{$group} = $grouproles{$group};
 6129:     }
 6130:     foreach my $role (keys(%{$allroles})) {
 6131:         my %thesepriv;
 6132:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6133:         foreach my $item (split(/:/,$$allroles{$role})) {
 6134:             if ($item ne '') {
 6135:                 my ($privilege,$restrictions)=split(/&/,$item);
 6136:                 if ($restrictions eq '') {
 6137:                     $thesepriv{$privilege}='F';
 6138:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6139:                     $thesepriv{$privilege}.=$restrictions;
 6140:                 }
 6141:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6142:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6143:             }
 6144:         }
 6145:         my $thesestr='';
 6146:         foreach my $priv (sort(keys(%thesepriv))) {
 6147: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6148: 	}
 6149:         $userroles->{'user.priv.'.$role} = $thesestr;
 6150:     }
 6151:     return ($author,$adv,$rar);
 6152: }
 6153: 
 6154: sub role_status {
 6155:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6156:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6157:         my ($one,$two) = split(m{\./},$rolekey,2);
 6158:         (undef,undef,$$role) = split(/\./,$one,3);
 6159:         unless (!defined($$role) || $$role eq '') {
 6160:             $$where = '/'.$two;
 6161:             $$trolecode=$$role.'.'.$$where;
 6162:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6163:             $$tstatus='is';
 6164:             if ($$tstart && $$tstart>$update) {
 6165:                 $$tstatus='future';
 6166:                 if ($$tstart<$now) {
 6167:                     if ($$tstart && $$tstart>$refresh) {
 6168:                         if (($$where ne '') && ($$role ne '')) {
 6169:                             my (%allroles,%allgroups,$group_privs,
 6170:                                 %groups_roles,@rolecodes);
 6171:                             my %userroles = (
 6172:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6173:                             );
 6174:                             @rolecodes = ('cm'); 
 6175:                             my $spec=$$role.'.'.$$where;
 6176:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6177:                             if ($$role =~ /^cr\//) {
 6178:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6179:                                 push(@rolecodes,'cr');
 6180:                             } elsif ($$role eq 'gr') {
 6181:                                 push(@rolecodes,$$role);
 6182:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6183:                                                     $env{'user.name'});
 6184:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6185:                                 (undef,my $group_privs) = split(/\//,$trole);
 6186:                                 $group_privs = &unescape($group_privs);
 6187:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6188:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6189:                                 &get_groups_roles($tdomain,$trest,
 6190:                                                   \%course_roles,\@rolecodes,
 6191:                                                   \%groups_roles);
 6192:                             } else {
 6193:                                 push(@rolecodes,$$role);
 6194:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6195:                             }
 6196:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6197:                                                                    \%groups_roles);
 6198:                             &appenv(\%userroles,\@rolecodes);
 6199:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6200:                         }
 6201:                     }
 6202:                     $$tstatus = 'is';
 6203:                 }
 6204:             }
 6205:             if ($$tend) {
 6206:                 if ($$tend<$update) {
 6207:                     $$tstatus='expired';
 6208:                 } elsif ($$tend<$now) {
 6209:                     $$tstatus='will_not';
 6210:                 }
 6211:             }
 6212:         }
 6213:     }
 6214: }
 6215: 
 6216: sub get_groups_roles {
 6217:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6218:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6219:                   (ref($rolecodes) eq 'ARRAY') && 
 6220:                   (ref($groups_roles) eq 'HASH')); 
 6221:     if (keys(%{$cdom_courseroles}) > 0) {
 6222:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6223:         if ($cdom ne '' && $cnum ne '') {
 6224:             foreach my $key (keys(%{$cdom_courseroles})) {
 6225:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6226:                     my $crsrole = $1;
 6227:                     my $crssec = $2;
 6228:                     if ($crsrole =~ /^cr/) {
 6229:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6230:                             push(@{$rolecodes},'cr');
 6231:                         }
 6232:                     } else {
 6233:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6234:                             push(@{$rolecodes},$crsrole);
 6235:                         }
 6236:                     }
 6237:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6238:                     if ($crssec ne '') {
 6239:                         $rolekey .= "/$crssec";
 6240:                     }
 6241:                     $rolekey .= './';
 6242:                     $groups_roles->{$rolekey} = $rolecodes;
 6243:                 }
 6244:             }
 6245:         }
 6246:     }
 6247:     return;
 6248: }
 6249: 
 6250: sub delete_env_groupprivs {
 6251:     my ($where,$courseroles,$possroles) = @_;
 6252:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6253:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6254:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6255:         %{$courseroles->{$udom}} =
 6256:             &get_my_roles('','','userroles',['active'],
 6257:                           $possroles,[$udom],1);
 6258:     }
 6259:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6260:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6261:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6262:             my $area = '/'.$cdom.'/'.$cnum;
 6263:             my $privkey = "user.priv.$crsrole.$area";
 6264:             if ($crssec ne '') {
 6265:                 $privkey .= '/'.$crssec;
 6266:             }
 6267:             $privkey .= ".$area/$group";
 6268:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6269:         }
 6270:     }
 6271:     return;
 6272: }
 6273: 
 6274: sub check_adhoc_privs {
 6275:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6276:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6277:     if ($sec) {
 6278:         $cckey .= '/'.$sec;
 6279:     } 
 6280:     my $setprivs;
 6281:     if ($env{$cckey}) {
 6282:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6283:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6284:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6285:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6286:             $setprivs = 1;
 6287:         }
 6288:     } else {
 6289:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6290:         $setprivs = 1;
 6291:     }
 6292:     return $setprivs;
 6293: }
 6294: 
 6295: sub set_adhoc_privileges {
 6296: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6297:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6298:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6299:     if ($sec ne '') {
 6300:         $area .= '/'.$sec;
 6301:     }
 6302:     my $spec = $role.'.'.$area;
 6303:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6304:                                   $env{'user.name'},1);
 6305:     my %rolehash = ();
 6306:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6307:         my $rolename = $1;
 6308:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6309:         my %domdef = &get_domain_defaults($dcdom);
 6310:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6311:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6312:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6313:             }
 6314:         }
 6315:     } else {
 6316:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6317:     }
 6318:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6319:     &appenv(\%userroles,[$role,'cm']);
 6320:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6321:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6322:         &appenv( {'request.role'        => $spec,
 6323:                   'request.role.domain' => $dcdom,
 6324:                   'request.course.sec'  => $sec,
 6325:                  }
 6326:                );
 6327:         my $tadv=0;
 6328:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6329:         &appenv({'request.role.adv'    => $tadv});
 6330:     }
 6331: }
 6332: 
 6333: # --------------------------------------------------------------- get interface
 6334: 
 6335: sub get {
 6336:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6337:    my $items='';
 6338:    foreach my $item (@$storearr) {
 6339:        $items.=&escape($item).'&';
 6340:    }
 6341:    $items=~s/\&$//;
 6342:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6343:    if (!$uname) { $uname=$env{'user.name'}; }
 6344:    my $uhome=&homeserver($uname,$udomain);
 6345: 
 6346:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6347:    my @pairs=split(/\&/,$rep);
 6348:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6349:      return @pairs;
 6350:    }
 6351:    my %returnhash=();
 6352:    my $i=0;
 6353:    foreach my $item (@$storearr) {
 6354:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6355:       $i++;
 6356:    }
 6357:    return %returnhash;
 6358: }
 6359: 
 6360: # --------------------------------------------------------------- del interface
 6361: 
 6362: sub del {
 6363:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6364:    my $items='';
 6365:    foreach my $item (@$storearr) {
 6366:        $items.=&escape($item).'&';
 6367:    }
 6368: 
 6369:    $items=~s/\&$//;
 6370:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6371:    if (!$uname) { $uname=$env{'user.name'}; }
 6372:    my $uhome=&homeserver($uname,$udomain);
 6373:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6374: }
 6375: 
 6376: # -------------------------------------------------------------- dump interface
 6377: 
 6378: sub unserialize {
 6379:     my ($rep, $escapedkeys) = @_;
 6380: 
 6381:     return {} if $rep =~ /^error/;
 6382: 
 6383:     my %returnhash=();
 6384: 	foreach my $item (split(/\&/,$rep)) {
 6385: 	    my ($key, $value) = split(/=/, $item, 2);
 6386: 	    $key = unescape($key) unless $escapedkeys;
 6387: 	    next if $key =~ /^error: 2 /;
 6388: 	    $returnhash{$key} = &thaw_unescape($value);
 6389: 	}
 6390:     #return %returnhash;
 6391:     return \%returnhash;
 6392: }        
 6393: 
 6394: # see Lond::dump_with_regexp
 6395: # if $escapedkeys hash keys won't get unescaped.
 6396: sub dump {
 6397:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6398:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6399:     if (!$uname) { $uname=$env{'user.name'}; }
 6400:     my $uhome=&homeserver($uname,$udomain);
 6401: 
 6402:     if ($regexp) {
 6403:         $regexp=&escape($regexp);
 6404:     } else {
 6405:         $regexp='.';
 6406:     }
 6407:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6408:         # user is hosted on this machine
 6409:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6410:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6411:         return %{unserialize($reply, $escapedkeys)};
 6412:     }
 6413:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6414:     my @pairs=split(/\&/,$rep);
 6415:     my %returnhash=();
 6416:     if (!($rep =~ /^error/ )) {
 6417: 	foreach my $item (@pairs) {
 6418: 	    my ($key,$value)=split(/=/,$item,2);
 6419:         $key = unescape($key) unless $escapedkeys;
 6420:         #$key = &unescape($key);
 6421: 	    next if ($key =~ /^error: 2 /);
 6422: 	    $returnhash{$key}=&thaw_unescape($value);
 6423: 	}
 6424:     }
 6425:     return %returnhash;
 6426: }
 6427: 
 6428: 
 6429: # --------------------------------------------------------- dumpstore interface
 6430: 
 6431: sub dumpstore {
 6432:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6433:    # same as dump but keys must be escaped. They may contain colon separated
 6434:    # lists of values that may themself contain colons (e.g. symbs).
 6435:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6436: }
 6437: 
 6438: # -------------------------------------------------------------- keys interface
 6439: 
 6440: sub getkeys {
 6441:    my ($namespace,$udomain,$uname)=@_;
 6442:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6443:    if (!$uname) { $uname=$env{'user.name'}; }
 6444:    my $uhome=&homeserver($uname,$udomain);
 6445:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6446:    my @keyarray=();
 6447:    foreach my $key (split(/\&/,$rep)) {
 6448:       next if ($key =~ /^error: 2 /);
 6449:       push(@keyarray,&unescape($key));
 6450:    }
 6451:    return @keyarray;
 6452: }
 6453: 
 6454: # --------------------------------------------------------------- currentdump
 6455: sub currentdump {
 6456:    my ($courseid,$sdom,$sname)=@_;
 6457:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6458:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6459:    $sname    = $env{'user.name'}         if (! defined($sname));
 6460:    my $uhome = &homeserver($sname,$sdom);
 6461:    my $rep;
 6462: 
 6463:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6464:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6465:                    $courseid)));
 6466:    } else {
 6467:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6468:    }
 6469: 
 6470:    return if ($rep =~ /^(error:|no_such_host)/);
 6471:    #
 6472:    my %returnhash=();
 6473:    #
 6474:    if ($rep eq 'unknown_cmd') {
 6475:        # an old lond will not know currentdump
 6476:        # Do a dump and make it look like a currentdump
 6477:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6478:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6479:        my %hash = @tmp;
 6480:        @tmp=();
 6481:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6482:    } else {
 6483:        my @pairs=split(/\&/,$rep);
 6484:        foreach my $pair (@pairs) {
 6485:            my ($key,$value)=split(/=/,$pair,2);
 6486:            my ($symb,$param) = split(/:/,$key);
 6487:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6488:                                                         &thaw_unescape($value);
 6489:        }
 6490:    }
 6491:    return %returnhash;
 6492: }
 6493: 
 6494: sub convert_dump_to_currentdump{
 6495:     my %hash = %{shift()};
 6496:     my %returnhash;
 6497:     # Code ripped from lond, essentially.  The only difference
 6498:     # here is the unescaping done by lonnet::dump().  Conceivably
 6499:     # we might run in to problems with parameter names =~ /^v\./
 6500:     while (my ($key,$value) = each(%hash)) {
 6501:         my ($v,$symb,$param) = split(/:/,$key);
 6502: 	$symb  = &unescape($symb);
 6503: 	$param = &unescape($param);
 6504:         next if ($v eq 'version' || $symb eq 'keys');
 6505:         next if (exists($returnhash{$symb}) &&
 6506:                  exists($returnhash{$symb}->{$param}) &&
 6507:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6508:         $returnhash{$symb}->{$param}=$value;
 6509:         $returnhash{$symb}->{'v.'.$param}=$v;
 6510:     }
 6511:     #
 6512:     # Remove all of the keys in the hashes which keep track of
 6513:     # the version of the parameter.
 6514:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6515:         # use a foreach because we are going to delete from the hash.
 6516:         foreach my $key (keys(%$param_hash)) {
 6517:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6518:         }
 6519:     }
 6520:     return \%returnhash;
 6521: }
 6522: 
 6523: # ------------------------------------------------------ critical inc interface
 6524: 
 6525: sub cinc {
 6526:     return &inc(@_,'critical');
 6527: }
 6528: 
 6529: # --------------------------------------------------------------- inc interface
 6530: 
 6531: sub inc {
 6532:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6533:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6534:     if (!$uname) { $uname=$env{'user.name'}; }
 6535:     my $uhome=&homeserver($uname,$udomain);
 6536:     my $items='';
 6537:     if (! ref($store)) {
 6538:         # got a single value, so use that instead
 6539:         $items = &escape($store).'=&';
 6540:     } elsif (ref($store) eq 'SCALAR') {
 6541:         $items = &escape($$store).'=&';        
 6542:     } elsif (ref($store) eq 'ARRAY') {
 6543:         $items = join('=&',map {&escape($_);} @{$store});
 6544:     } elsif (ref($store) eq 'HASH') {
 6545:         while (my($key,$value) = each(%{$store})) {
 6546:             $items.= &escape($key).'='.&escape($value).'&';
 6547:         }
 6548:     }
 6549:     $items=~s/\&$//;
 6550:     if ($critical) {
 6551: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6552:     } else {
 6553: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6554:     }
 6555: }
 6556: 
 6557: # --------------------------------------------------------------- put interface
 6558: 
 6559: sub put {
 6560:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6561:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6562:    if (!$uname) { $uname=$env{'user.name'}; }
 6563:    my $uhome=&homeserver($uname,$udomain);
 6564:    my $items='';
 6565:    foreach my $item (keys(%$storehash)) {
 6566:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6567:    }
 6568:    $items=~s/\&$//;
 6569:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6570: }
 6571: 
 6572: # ------------------------------------------------------------ newput interface
 6573: 
 6574: sub newput {
 6575:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6576:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6577:    if (!$uname) { $uname=$env{'user.name'}; }
 6578:    my $uhome=&homeserver($uname,$udomain);
 6579:    my $items='';
 6580:    foreach my $key (keys(%$storehash)) {
 6581:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6582:    }
 6583:    $items=~s/\&$//;
 6584:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6585: }
 6586: 
 6587: # ---------------------------------------------------------  putstore interface
 6588: 
 6589: sub putstore {
 6590:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6591:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6592:    if (!$uname) { $uname=$env{'user.name'}; }
 6593:    my $uhome=&homeserver($uname,$udomain);
 6594:    my $items='';
 6595:    foreach my $key (keys(%$storehash)) {
 6596:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6597:    }
 6598:    $items=~s/\&$//;
 6599:    my $esc_symb=&escape($symb);
 6600:    my $esc_v=&escape($version);
 6601:    my $reply =
 6602:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6603: 	      $uhome);
 6604:    if (($tolog) && ($reply eq 'ok')) {
 6605:        my $namevalue='';
 6606:        foreach my $key (keys(%{$storehash})) {
 6607:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6608:        }
 6609:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6610:                      '&host='.&escape($perlvar{'lonHostID'}).
 6611:                      '&version='.$esc_v.
 6612:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6613:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6614:    }
 6615:    if ($reply eq 'unknown_cmd') {
 6616:        # gfall back to way things use to be done
 6617:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6618: 			    $uname);
 6619:    }
 6620:    return $reply;
 6621: }
 6622: 
 6623: sub old_putstore {
 6624:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6625:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6626:     if (!$uname) { $uname=$env{'user.name'}; }
 6627:     my $uhome=&homeserver($uname,$udomain);
 6628:     my %newstorehash;
 6629:     foreach my $item (keys(%$storehash)) {
 6630: 	my $key = $version.':'.&escape($symb).':'.$item;
 6631: 	$newstorehash{$key} = $storehash->{$item};
 6632:     }
 6633:     my $items='';
 6634:     my %allitems = ();
 6635:     foreach my $item (keys(%newstorehash)) {
 6636: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6637: 	    my $key = $1.':keys:'.$2;
 6638: 	    $allitems{$key} .= $3.':';
 6639: 	}
 6640: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6641:     }
 6642:     foreach my $item (keys(%allitems)) {
 6643: 	$allitems{$item} =~ s/\:$//;
 6644: 	$items.= $item.'='.$allitems{$item}.'&';
 6645:     }
 6646:     $items=~s/\&$//;
 6647:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6648: }
 6649: 
 6650: # ------------------------------------------------------ critical put interface
 6651: 
 6652: sub cput {
 6653:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6654:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6655:    if (!$uname) { $uname=$env{'user.name'}; }
 6656:    my $uhome=&homeserver($uname,$udomain);
 6657:    my $items='';
 6658:    foreach my $item (keys(%$storehash)) {
 6659:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6660:    }
 6661:    $items=~s/\&$//;
 6662:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6663: }
 6664: 
 6665: # -------------------------------------------------------------- eget interface
 6666: 
 6667: sub eget {
 6668:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6669:    my $items='';
 6670:    foreach my $item (@$storearr) {
 6671:        $items.=&escape($item).'&';
 6672:    }
 6673:    $items=~s/\&$//;
 6674:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6675:    if (!$uname) { $uname=$env{'user.name'}; }
 6676:    my $uhome=&homeserver($uname,$udomain);
 6677:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6678:    my @pairs=split(/\&/,$rep);
 6679:    my %returnhash=();
 6680:    my $i=0;
 6681:    foreach my $item (@$storearr) {
 6682:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6683:       $i++;
 6684:    }
 6685:    return %returnhash;
 6686: }
 6687: 
 6688: # ------------------------------------------------------------ tmpput interface
 6689: sub tmpput {
 6690:     my ($storehash,$server,$context)=@_;
 6691:     my $items='';
 6692:     foreach my $item (keys(%$storehash)) {
 6693: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6694:     }
 6695:     $items=~s/\&$//;
 6696:     if (defined($context)) {
 6697:         $items .= ':'.&escape($context);
 6698:     }
 6699:     return &reply("tmpput:$items",$server);
 6700: }
 6701: 
 6702: # ------------------------------------------------------------ tmpget interface
 6703: sub tmpget {
 6704:     my ($token,$server)=@_;
 6705:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6706:     my $rep=&reply("tmpget:$token",$server);
 6707:     my %returnhash;
 6708:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6709:         return %returnhash;
 6710:     }
 6711:     foreach my $item (split(/\&/,$rep)) {
 6712: 	my ($key,$value)=split(/=/,$item);
 6713: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6714:     }
 6715:     return %returnhash;
 6716: }
 6717: 
 6718: # ------------------------------------------------------------ tmpdel interface
 6719: sub tmpdel {
 6720:     my ($token,$server)=@_;
 6721:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6722:     return &reply("tmpdel:$token",$server);
 6723: }
 6724: 
 6725: # ------------------------------------------------------------ get_timebased_id 
 6726: 
 6727: sub get_timebased_id {
 6728:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6729:         $maxtries) = @_;
 6730:     my ($newid,$error,$dellock);
 6731:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6732:         return ('','ok','invalid call to get suffix');
 6733:     }
 6734: 
 6735: # set defaults for any optional args for which values were not supplied
 6736:     if ($who eq '') {
 6737:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6738:     }
 6739:     if (!$locktries) {
 6740:         $locktries = 3;
 6741:     }
 6742:     if (!$maxtries) {
 6743:         $maxtries = 10;
 6744:     }
 6745:     
 6746:     if (($cdom eq '') || ($cnum eq '')) {
 6747:         if ($env{'request.course.id'}) {
 6748:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6749:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6750:         }
 6751:         if (($cdom eq '') || ($cnum eq '')) {
 6752:             return ('','ok','call to get suffix not in course context');
 6753:         }
 6754:     }
 6755: 
 6756: # construct locking item
 6757:     my $lockhash = {
 6758:                       $prefix."\0".'locked_'.$keyid => $who,
 6759:                    };
 6760:     my $tries = 0;
 6761: 
 6762: # attempt to get lock on nohist_$namespace file
 6763:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6764:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6765:         $tries ++;
 6766:         sleep 1;
 6767:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6768:     }
 6769: 
 6770: # attempt to get unique identifier, based on current timestamp
 6771:     if ($gotlock eq 'ok') {
 6772:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6773:         my $id = time;
 6774:         $newid = $id;
 6775:         if ($idtype eq 'addcode') {
 6776:             $newid .= &sixnum_code();
 6777:         }
 6778:         my $idtries = 0;
 6779:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6780:             if ($idtype eq 'concat') {
 6781:                 $newid = $id.$idtries;
 6782:             } elsif ($idtype eq 'addcode') {
 6783:                 $newid = $newid.&sixnum_code();
 6784:             } else {
 6785:                 $newid ++;
 6786:             }
 6787:             $idtries ++;
 6788:         }
 6789:         if (!exists($inuse{$prefix."\0".$newid})) {
 6790:             my %new_item =  (
 6791:                               $prefix."\0".$newid => $who,
 6792:                             );
 6793:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6794:                                                  $cdom,$cnum);
 6795:             if ($putresult ne 'ok') {
 6796:                 undef($newid);
 6797:                 $error = 'error saving new item: '.$putresult;
 6798:             }
 6799:         } else {
 6800:              undef($newid);
 6801:              $error = ('error: no unique suffix available for the new item ');
 6802:         }
 6803: #  remove lock
 6804:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6805:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6806:     } else {
 6807:         $error = "error: could not obtain lockfile\n";
 6808:         $dellock = 'ok';
 6809:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6810:             $dellock = 'nolock';
 6811:         }
 6812:     }
 6813:     return ($newid,$dellock,$error);
 6814: }
 6815: 
 6816: sub sixnum_code {
 6817:     my $code;
 6818:     for (0..6) {
 6819:         $code .= int( rand(9) );
 6820:     }
 6821:     return $code;
 6822: }
 6823: 
 6824: # -------------------------------------------------- portfolio access checking
 6825: 
 6826: sub portfolio_access {
 6827:     my ($requrl,$clientip) = @_;
 6828:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6829:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6830:     if ($result) {
 6831:         my %setters;
 6832:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6833:             my ($startblock,$endblock) =
 6834:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6835:             if ($startblock && $endblock) {
 6836:                 return 'B';
 6837:             }
 6838:         } else {
 6839:             my ($startblock,$endblock) =
 6840:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6841:             if ($startblock && $endblock) {
 6842:                 return 'B';
 6843:             }
 6844:         }
 6845:     }
 6846:     if ($result eq 'ok') {
 6847:        return 'F';
 6848:     } elsif ($result =~ /^[^:]+:guest_/) {
 6849:        return 'A';
 6850:     }
 6851:     return '';
 6852: }
 6853: 
 6854: sub get_portfolio_access {
 6855:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6856: 
 6857:     if (!ref($access_hash)) {
 6858: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6859: 	my %access_controls = &get_access_controls($current_perms,$group,
 6860: 						   $file_name);
 6861: 	$access_hash = $access_controls{$file_name};
 6862:     }
 6863: 
 6864:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6865:     my $now = time;
 6866:     if (ref($access_hash) eq 'HASH') {
 6867:         foreach my $key (keys(%{$access_hash})) {
 6868:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6869:             if ($start > $now) {
 6870:                 next;
 6871:             }
 6872:             if ($end && $end<$now) {
 6873:                 next;
 6874:             }
 6875:             if ($scope eq 'public') {
 6876:                 $public = $key;
 6877:                 last;
 6878:             } elsif ($scope eq 'guest') {
 6879:                 $guest = $key;
 6880:             } elsif ($scope eq 'domains') {
 6881:                 push(@domains,$key);
 6882:             } elsif ($scope eq 'users') {
 6883:                 push(@users,$key);
 6884:             } elsif ($scope eq 'course') {
 6885:                 push(@courses,$key);
 6886:             } elsif ($scope eq 'group') {
 6887:                 push(@groups,$key);
 6888:             } elsif ($scope eq 'ip') {
 6889:                 push(@ips,$key);
 6890:             }
 6891:         }
 6892:         if ($public) {
 6893:             return 'ok';
 6894:         } elsif (@ips > 0) {
 6895:             my $allowed;
 6896:             foreach my $ipkey (@ips) {
 6897:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6898:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6899:                         $allowed = 1;
 6900:                         last; 
 6901:                     }
 6902:                 }
 6903:             }
 6904:             if ($allowed) {
 6905:                 return 'ok';
 6906:             }
 6907:         }
 6908:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6909:             if ($guest) {
 6910:                 return $guest;
 6911:             }
 6912:         } else {
 6913:             if (@domains > 0) {
 6914:                 foreach my $domkey (@domains) {
 6915:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6916:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6917:                             return 'ok';
 6918:                         }
 6919:                     }
 6920:                 }
 6921:             }
 6922:             if (@users > 0) {
 6923:                 foreach my $userkey (@users) {
 6924:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6925:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6926:                             if (ref($item) eq 'HASH') {
 6927:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6928:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6929:                                     return 'ok';
 6930:                                 }
 6931:                             }
 6932:                         }
 6933:                     } 
 6934:                 }
 6935:             }
 6936:             my %roleshash;
 6937:             my @courses_and_groups = @courses;
 6938:             push(@courses_and_groups,@groups); 
 6939:             if (@courses_and_groups > 0) {
 6940:                 my (%allgroups,%allroles); 
 6941:                 my ($start,$end,$role,$sec,$group);
 6942:                 foreach my $envkey (%env) {
 6943:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6944:                         my $cid = $2.'_'.$3; 
 6945:                         if ($1 eq 'gr') {
 6946:                             $group = $4;
 6947:                             $allgroups{$cid}{$group} = $env{$envkey};
 6948:                         } else {
 6949:                             if ($4 eq '') {
 6950:                                 $sec = 'none';
 6951:                             } else {
 6952:                                 $sec = $4;
 6953:                             }
 6954:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6955:                         }
 6956:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6957:                         my $cid = $2.'_'.$3;
 6958:                         if ($4 eq '') {
 6959:                             $sec = 'none';
 6960:                         } else {
 6961:                             $sec = $4;
 6962:                         }
 6963:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6964:                     }
 6965:                 }
 6966:                 if (keys(%allroles) == 0) {
 6967:                     return;
 6968:                 }
 6969:                 foreach my $key (@courses_and_groups) {
 6970:                     my %content = %{$$access_hash{$key}};
 6971:                     my $cnum = $content{'number'};
 6972:                     my $cdom = $content{'domain'};
 6973:                     my $cid = $cdom.'_'.$cnum;
 6974:                     if (!exists($allroles{$cid})) {
 6975:                         next;
 6976:                     }    
 6977:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6978:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6979:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6980:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6981:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6982:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6983:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6984:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6985:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6986:                                         if (grep/^all$/,@sections) {
 6987:                                             return 'ok';
 6988:                                         } else {
 6989:                                             if (grep/^$sec$/,@sections) {
 6990:                                                 return 'ok';
 6991:                                             }
 6992:                                         }
 6993:                                     }
 6994:                                 }
 6995:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6996:                                     if (grep/^none$/,@groups) {
 6997:                                         return 'ok';
 6998:                                     }
 6999:                                 } else {
 7000:                                     if (grep/^all$/,@groups) {
 7001:                                         return 'ok';
 7002:                                     } 
 7003:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7004:                                         if (grep/^$group$/,@groups) {
 7005:                                             return 'ok';
 7006:                                         }
 7007:                                     }
 7008:                                 } 
 7009:                             }
 7010:                         }
 7011:                     }
 7012:                 }
 7013:             }
 7014:             if ($guest) {
 7015:                 return $guest;
 7016:             }
 7017:         }
 7018:     }
 7019:     return;
 7020: }
 7021: 
 7022: sub course_group_datechecker {
 7023:     my ($dates,$now,$status) = @_;
 7024:     my ($start,$end) = split(/\./,$dates);
 7025:     if (!$start && !$end) {
 7026:         return 'ok';
 7027:     }
 7028:     if (grep/^active$/,@{$status}) {
 7029:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7030:             return 'ok';
 7031:         }
 7032:     }
 7033:     if (grep/^previous$/,@{$status}) {
 7034:         if ($end > $now ) {
 7035:             return 'ok';
 7036:         }
 7037:     }
 7038:     if (grep/^future$/,@{$status}) {
 7039:         if ($start > $now) {
 7040:             return 'ok';
 7041:         }
 7042:     }
 7043:     return; 
 7044: }
 7045: 
 7046: sub parse_portfolio_url {
 7047:     my ($url) = @_;
 7048: 
 7049:     my ($type,$udom,$unum,$group,$file_name);
 7050:     
 7051:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7052: 	$type = 1;
 7053:         $udom = $1;
 7054:         $unum = $2;
 7055:         $file_name = $3;
 7056:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7057: 	$type = 2;
 7058:         $udom = $1;
 7059:         $unum = $2;
 7060:         $group = $3;
 7061:         $file_name = $3.'/'.$4;
 7062:     }
 7063:     if (wantarray) {
 7064: 	return ($type,$udom,$unum,$file_name,$group);
 7065:     }
 7066:     return $type;
 7067: }
 7068: 
 7069: sub is_portfolio_url {
 7070:     my ($url) = @_;
 7071:     return scalar(&parse_portfolio_url($url));
 7072: }
 7073: 
 7074: sub is_portfolio_file {
 7075:     my ($file) = @_;
 7076:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7077:         return 1;
 7078:     }
 7079:     return;
 7080: }
 7081: 
 7082: sub usertools_access {
 7083:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7084:     my ($access,%tools);
 7085:     if ($context eq '') {
 7086:         $context = 'tools';
 7087:     }
 7088:     if ($context eq 'requestcourses') {
 7089:         %tools = (
 7090:                       official   => 1,
 7091:                       unofficial => 1,
 7092:                       community  => 1,
 7093:                       textbook   => 1,
 7094:                       placement  => 1,
 7095:                  );
 7096:     } elsif ($context eq 'requestauthor') {
 7097:         %tools = (
 7098:                       requestauthor => 1,
 7099:                  );
 7100:     } else {
 7101:         %tools = (
 7102:                       aboutme   => 1,
 7103:                       blog      => 1,
 7104:                       webdav    => 1,
 7105:                       portfolio => 1,
 7106:                  );
 7107:     }
 7108:     return if (!defined($tools{$tool}));
 7109: 
 7110:     if (($udom eq '') || ($uname eq '')) {
 7111:         $udom = $env{'user.domain'};
 7112:         $uname = $env{'user.name'};
 7113:     }
 7114: 
 7115:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7116:         if ($action ne 'reload') {
 7117:             if ($context eq 'requestcourses') {
 7118:                 return $env{'environment.canrequest.'.$tool};
 7119:             } elsif ($context eq 'requestauthor') {
 7120:                 return $env{'environment.canrequest.author'};
 7121:             } else {
 7122:                 return $env{'environment.availabletools.'.$tool};
 7123:             }
 7124:         }
 7125:     }
 7126: 
 7127:     my ($toolstatus,$inststatus,$envkey);
 7128:     if ($context eq 'requestauthor') {
 7129:         $envkey = $context; 
 7130:     } else {
 7131:         $envkey = $context.'.'.$tool;
 7132:     }
 7133: 
 7134:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7135:          ($action ne 'reload')) {
 7136:         $toolstatus = $env{'environment.'.$envkey};
 7137:         $inststatus = $env{'environment.inststatus'};
 7138:     } else {
 7139:         if (ref($userenvref) eq 'HASH') {
 7140:             $toolstatus = $userenvref->{$envkey};
 7141:             $inststatus = $userenvref->{'inststatus'};
 7142:         } else {
 7143:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7144:             $toolstatus = $userenv{$envkey};
 7145:             $inststatus = $userenv{'inststatus'};
 7146:         }
 7147:     }
 7148: 
 7149:     if ($toolstatus ne '') {
 7150:         if ($toolstatus) {
 7151:             $access = 1;
 7152:         } else {
 7153:             $access = 0;
 7154:         }
 7155:         return $access;
 7156:     }
 7157: 
 7158:     my ($is_adv,%domdef);
 7159:     if (ref($is_advref) eq 'HASH') {
 7160:         $is_adv = $is_advref->{'is_adv'};
 7161:     } else {
 7162:         $is_adv = &is_advanced_user($udom,$uname);
 7163:     }
 7164:     if (ref($domdefref) eq 'HASH') {
 7165:         %domdef = %{$domdefref};
 7166:     } else {
 7167:         %domdef = &get_domain_defaults($udom);
 7168:     }
 7169:     if (ref($domdef{$tool}) eq 'HASH') {
 7170:         if ($is_adv) {
 7171:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7172:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7173:                     $access = 1;
 7174:                 } else {
 7175:                     $access = 0;
 7176:                 }
 7177:                 return $access;
 7178:             }
 7179:         }
 7180:         if ($inststatus ne '') {
 7181:             my ($hasaccess,$hasnoaccess);
 7182:             foreach my $affiliation (split(/:/,$inststatus)) {
 7183:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7184:                     if ($domdef{$tool}{$affiliation}) {
 7185:                         $hasaccess = 1;
 7186:                     } else {
 7187:                         $hasnoaccess = 1;
 7188:                     }
 7189:                 }
 7190:             }
 7191:             if ($hasaccess || $hasnoaccess) {
 7192:                 if ($hasaccess) {
 7193:                     $access = 1;
 7194:                 } elsif ($hasnoaccess) {
 7195:                     $access = 0; 
 7196:                 }
 7197:                 return $access;
 7198:             }
 7199:         } else {
 7200:             if ($domdef{$tool}{'default'} ne '') {
 7201:                 if ($domdef{$tool}{'default'}) {
 7202:                     $access = 1;
 7203:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7204:                     $access = 0;
 7205:                 }
 7206:                 return $access;
 7207:             }
 7208:         }
 7209:     } else {
 7210:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7211:             $access = 1;
 7212:         } else {
 7213:             $access = 0;
 7214:         }
 7215:         return $access;
 7216:     }
 7217: }
 7218: 
 7219: sub is_course_owner {
 7220:     my ($cdom,$cnum,$udom,$uname) = @_;
 7221:     if (($udom eq '') || ($uname eq '')) {
 7222:         $udom = $env{'user.domain'};
 7223:         $uname = $env{'user.name'};
 7224:     }
 7225:     unless (($udom eq '') || ($uname eq '')) {
 7226:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7227:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7228:                 return 1;
 7229:             } else {
 7230:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7231:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7232:                     return 1;
 7233:                 }
 7234:             }
 7235:         }
 7236:     }
 7237:     return;
 7238: }
 7239: 
 7240: sub is_advanced_user {
 7241:     my ($udom,$uname) = @_;
 7242:     if ($udom ne '' && $uname ne '') {
 7243:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7244:             if (wantarray) {
 7245:                 return ($env{'user.adv'},$env{'user.author'});
 7246:             } else {
 7247:                 return $env{'user.adv'};
 7248:             }
 7249:         }
 7250:     }
 7251:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7252:     my %allroles;
 7253:     my ($is_adv,$is_author);
 7254:     foreach my $role (keys(%roleshash)) {
 7255:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7256:         my $area = '/'.$tdomain.'/'.$trest;
 7257:         if ($sec ne '') {
 7258:             $area .= '/'.$sec;
 7259:         }
 7260:         if (($area ne '') && ($trole ne '')) {
 7261:             my $spec=$trole.'.'.$area;
 7262:             if ($trole =~ /^cr\//) {
 7263:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7264:             } elsif ($trole ne 'gr') {
 7265:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7266:             }
 7267:             if ($trole eq 'au') {
 7268:                 $is_author = 1;
 7269:             }
 7270:         }
 7271:     }
 7272:     foreach my $role (keys(%allroles)) {
 7273:         last if ($is_adv);
 7274:         foreach my $item (split(/:/,$allroles{$role})) {
 7275:             if ($item ne '') {
 7276:                 my ($privilege,$restrictions)=split(/&/,$item);
 7277:                 if ($privilege eq 'adv') {
 7278:                     $is_adv = 1;
 7279:                     last;
 7280:                 }
 7281:             }
 7282:         }
 7283:     }
 7284:     if (wantarray) {
 7285:         return ($is_adv,$is_author);
 7286:     }
 7287:     return $is_adv;
 7288: }
 7289: 
 7290: sub check_can_request {
 7291:     my ($dom,$can_request,$request_domains) = @_;
 7292:     my $canreq = 0;
 7293:     my ($types,$typename) = &Apache::loncommon::course_types();
 7294:     my @options = ('approval','validate','autolimit');
 7295:     my $optregex = join('|',@options);
 7296:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7297:         foreach my $type (@{$types}) {
 7298:             if (&usertools_access($env{'user.name'},
 7299:                                   $env{'user.domain'},
 7300:                                   $type,undef,'requestcourses')) {
 7301:                 $canreq ++;
 7302:                 if (ref($request_domains) eq 'HASH') {
 7303:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 7304:                 }
 7305:                 if ($dom eq $env{'user.domain'}) {
 7306:                     $can_request->{$type} = 1;
 7307:                 }
 7308:             }
 7309:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 7310:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7311:                 if (@curr > 0) {
 7312:                     foreach my $item (@curr) {
 7313:                         if (ref($request_domains) eq 'HASH') {
 7314:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7315:                             if ($otherdom ne '') {
 7316:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7317:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7318:                                         push(@{$request_domains->{$type}},$otherdom);
 7319:                                     }
 7320:                                 } else {
 7321:                                     push(@{$request_domains->{$type}},$otherdom);
 7322:                                 }
 7323:                             }
 7324:                         }
 7325:                     }
 7326:                     unless($dom eq $env{'user.domain'}) {
 7327:                         $canreq ++;
 7328:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7329:                             $can_request->{$type} = 1;
 7330:                         }
 7331:                     }
 7332:                 }
 7333:             }
 7334:         }
 7335:     }
 7336:     return $canreq;
 7337: }
 7338: 
 7339: # ---------------------------------------------- Custom access rule evaluation
 7340: 
 7341: sub customaccess {
 7342:     my ($priv,$uri)=@_;
 7343:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7344:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7345:     $udom = &LONCAPA::clean_domain($udom);
 7346:     $ucrs = &LONCAPA::clean_username($ucrs);
 7347:     my $access=0;
 7348:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7349: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7350: 	if ($type eq 'user') {
 7351: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7352: 		my ($tdom,$tuname)=split(m{/},$scope);
 7353: 		if ($tdom) {
 7354: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7355: 		}
 7356: 		if ($tuname) {
 7357: 		    if ($tuname ne $env{'user.name'}) { next; }
 7358: 		}
 7359: 		$access=($effect eq 'allow');
 7360: 		last;
 7361: 	    }
 7362: 	} else {
 7363: 	    if ($role) {
 7364: 		if ($role ne $urole) { next; }
 7365: 	    }
 7366: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7367: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7368: 		if ($tdom) {
 7369: 		    if ($tdom ne $udom) { next; }
 7370: 		}
 7371: 		if ($tcrs) {
 7372: 		    if ($tcrs ne $ucrs) { next; }
 7373: 		}
 7374: 		if ($tsec) {
 7375: 		    if ($tsec ne $usec) { next; }
 7376: 		}
 7377: 		$access=($effect eq 'allow');
 7378: 		last;
 7379: 	    }
 7380: 	    if ($realm eq '' && $role eq '') {
 7381: 		$access=($effect eq 'allow');
 7382: 	    }
 7383: 	}
 7384:     }
 7385:     return $access;
 7386: }
 7387: 
 7388: # ------------------------------------------------- Check for a user privilege
 7389: 
 7390: sub allowed {
 7391:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7392:     my $ver_orguri=$uri;
 7393:     $uri=&deversion($uri);
 7394:     my $orguri=$uri;
 7395:     $uri=&declutter($uri);
 7396: 
 7397:     if ($priv eq 'evb') {
 7398: # Evade communication block restrictions for specified role in a course
 7399:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7400:             return $1;
 7401:         } else {
 7402:             return;
 7403:         }
 7404:     }
 7405: 
 7406:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7407: # Free bre access to adm and meta resources
 7408:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7409: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7410: 	&& ($priv eq 'bre')) {
 7411: 	return 'F';
 7412:     }
 7413: 
 7414: # Free bre access to user's own portfolio contents
 7415:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7416:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7417: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7418:         my %setters;
 7419:         my ($startblock,$endblock) = 
 7420:             &Apache::loncommon::blockcheck(\%setters,'port');
 7421:         if ($startblock && $endblock) {
 7422:             return 'B';
 7423:         } else {
 7424:             return 'F';
 7425:         }
 7426:     }
 7427: 
 7428: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7429:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7430:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7431:         if (exists($env{'request.course.id'})) {
 7432:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7433:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7434:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7435:                 my $courseprivid=$env{'request.course.id'};
 7436:                 $courseprivid=~s/\_/\//;
 7437:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7438:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7439:                     return $1; 
 7440:                 } else {
 7441:                     if ($env{'request.course.sec'}) {
 7442:                         $courseprivid.='/'.$env{'request.course.sec'};
 7443:                     }
 7444:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7445:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7446:                         return $2;
 7447:                     }
 7448:                 }
 7449:             }
 7450:         }
 7451:     }
 7452: 
 7453: # Free bre to public access
 7454: 
 7455:     if ($priv eq 'bre') {
 7456:         my $copyright=&metadata($uri,'copyright');
 7457: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7458:            return 'F'; 
 7459:         }
 7460:         if ($copyright eq 'priv') {
 7461:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7462: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7463: 		return '';
 7464:             }
 7465:         }
 7466:         if ($copyright eq 'domain') {
 7467:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7468: 	    unless (($env{'user.domain'} eq $1) ||
 7469:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7470: 		return '';
 7471:             }
 7472:         }
 7473:         if ($env{'request.role'}=~ /li\.\//) {
 7474:             # Library role, so allow browsing of resources in this domain.
 7475:             return 'F';
 7476:         }
 7477:         if ($copyright eq 'custom') {
 7478: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7479:         }
 7480:     }
 7481:     # Domain coordinator is trying to create a course
 7482:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7483:         # uri is the requested domain in this case.
 7484:         # comparison to 'request.role.domain' shows if the user has selected
 7485:         # a role of dc for the domain in question.
 7486:         return 'F' if ($uri eq $env{'request.role.domain'});
 7487:     }
 7488: 
 7489:     my $thisallowed='';
 7490:     my $statecond=0;
 7491:     my $courseprivid='';
 7492: 
 7493:     my $ownaccess;
 7494:     # Community Coordinator or Assistant Co-author browsing resource space.
 7495:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7496:         if ($uri eq '') {
 7497:             $ownaccess = 1;
 7498:         } else {
 7499:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7500:                 my $udom = $env{'user.domain'};
 7501:                 my $uname = $env{'user.name'};
 7502:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7503:                     $ownaccess = 1;
 7504:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7505:                     unless ($uri =~ m{\.\./}) {
 7506:                         $ownaccess = 1;
 7507:                     }
 7508:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7509:                     my $now = time;
 7510:                     if ($uri =~ m{^([^/]+)/?$}) {
 7511:                         my $adom = $1;
 7512:                         foreach my $key (keys(%env)) {
 7513:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7514:                                 my ($start,$end) = split('.',$env{$key});
 7515:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7516:                                     $ownaccess = 1;
 7517:                                     last;
 7518:                                 }
 7519:                             }
 7520:                         }
 7521:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7522:                         my $adom = $1;
 7523:                         my $aname = $2;
 7524:                         foreach my $role ('ca','aa') { 
 7525:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7526:                                 my ($start,$end) =
 7527:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7528:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7529:                                     $ownaccess = 1;
 7530:                                     last;
 7531:                                 }
 7532:                             }
 7533:                         }
 7534:                     }
 7535:                 }
 7536:             }
 7537:         }
 7538:     }
 7539: 
 7540: # Course
 7541: 
 7542:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7543:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7544:             $thisallowed.=$1;
 7545:         }
 7546:     }
 7547: 
 7548: # Domain
 7549: 
 7550:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7551:        =~/\Q$priv\E\&([^\:]*)/) {
 7552:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7553:             $thisallowed.=$1;
 7554:         }
 7555:     }
 7556: 
 7557: # User who is not author or co-author might still be able to edit
 7558: # resource of an author in the domain (e.g., if Domain Coordinator).
 7559:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7560:         (&allowed('mdc',$env{'request.course.id'}))) {
 7561:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7562:             $thisallowed.=$1;
 7563:         }
 7564:     }
 7565: 
 7566: # Course: uri itself is a course
 7567:     my $courseuri=$uri;
 7568:     $courseuri=~s/\_(\d)/\/$1/;
 7569:     $courseuri=~s/^([^\/])/\/$1/;
 7570: 
 7571:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7572:        =~/\Q$priv\E\&([^\:]*)/) {
 7573:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7574:             $thisallowed.=$1;
 7575:         }
 7576:     }
 7577: 
 7578: # URI is an uploaded document for this course, default permissions don't matter
 7579: # not allowing 'edit' access (editupload) to uploaded course docs
 7580:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7581: 	$thisallowed='';
 7582:         my ($match)=&is_on_map($uri);
 7583:         if ($match) {
 7584:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7585:                   =~/\Q$priv\E\&([^\:]*)/) {
 7586:                 my $value = $1;
 7587:                 if ($noblockcheck) {
 7588:                     $thisallowed.=$value;
 7589:                 } else {
 7590:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7591:                     if (@blockers > 0) {
 7592:                         $thisallowed = 'B';
 7593:                     } else {
 7594:                         $thisallowed.=$value;
 7595:                     }
 7596:                 }
 7597:             }
 7598:         } else {
 7599:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7600:             if ($refuri) {
 7601:                 if ($refuri =~ m|^/adm/|) {
 7602:                     $thisallowed='F';
 7603:                 } else {
 7604:                     $refuri=&declutter($refuri);
 7605:                     my ($match) = &is_on_map($refuri);
 7606:                     if ($match) {
 7607:                         if ($noblockcheck) {
 7608:                             $thisallowed='F';
 7609:                         } else {
 7610:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7611:                             if (@blockers > 0) {
 7612:                                 $thisallowed = 'B';
 7613:                             } else {
 7614:                                 $thisallowed='F';
 7615:                             }
 7616:                         }
 7617:                     }
 7618:                 }
 7619:             }
 7620:         }
 7621:     }
 7622: 
 7623:     if ($priv eq 'bre'
 7624: 	&& $thisallowed ne 'F' 
 7625: 	&& $thisallowed ne '2'
 7626: 	&& &is_portfolio_url($uri)) {
 7627: 	$thisallowed = &portfolio_access($uri,$clientip);
 7628:     }
 7629: 
 7630: # Full access at system, domain or course-wide level? Exit.
 7631:     if ($thisallowed=~/F/) {
 7632: 	return 'F';
 7633:     }
 7634: 
 7635: # If this is generating or modifying users, exit with special codes
 7636: 
 7637:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7638: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7639: 	    my ($audom,$auname)=split('/',$uri);
 7640: # no author name given, so this just checks on the general right to make a co-author in this domain
 7641: 	    unless ($auname) { return $thisallowed; }
 7642: # an author name is given, so we are about to actually make a co-author for a certain account
 7643: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7644: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7645: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7646: 	}
 7647: 	return $thisallowed;
 7648:     }
 7649: #
 7650: # Gathered so far: system, domain and course wide privileges
 7651: #
 7652: # Course: See if uri or referer is an individual resource that is part of 
 7653: # the course
 7654: 
 7655:     if ($env{'request.course.id'}) {
 7656: 
 7657:        $courseprivid=$env{'request.course.id'};
 7658:        if ($env{'request.course.sec'}) {
 7659:           $courseprivid.='/'.$env{'request.course.sec'};
 7660:        }
 7661:        $courseprivid=~s/\_/\//;
 7662:        my $checkreferer=1;
 7663:        my ($match,$cond)=&is_on_map($uri);
 7664:        if ($match) {
 7665:            $statecond=$cond;
 7666:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7667:                =~/\Q$priv\E\&([^\:]*)/) {
 7668:                my $value = $1;
 7669:                if ($priv eq 'bre') {
 7670:                    if ($noblockcheck) {
 7671:                        $thisallowed.=$value;
 7672:                    } else {
 7673:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7674:                        if (@blockers > 0) {
 7675:                            $thisallowed = 'B';
 7676:                        } else {
 7677:                            $thisallowed.=$value;
 7678:                        }
 7679:                    }
 7680:                } else {
 7681:                    $thisallowed.=$value;
 7682:                }
 7683:                $checkreferer=0;
 7684:            }
 7685:        }
 7686:        
 7687:        if ($checkreferer) {
 7688: 	  my $refuri=$env{'httpref.'.$orguri};
 7689:             unless ($refuri) {
 7690:                 foreach my $key (keys(%env)) {
 7691: 		    if ($key=~/^httpref\..*\*/) {
 7692: 			my $pattern=$key;
 7693:                         $pattern=~s/^httpref\.\/res\///;
 7694:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7695:                         $pattern=~s/\//\\\//g;
 7696:                         if ($orguri=~/$pattern/) {
 7697: 			    $refuri=$env{$key};
 7698:                         }
 7699:                     }
 7700:                 }
 7701:             }
 7702: 
 7703:          if ($refuri) { 
 7704: 	  $refuri=&declutter($refuri);
 7705:           my ($match,$cond)=&is_on_map($refuri);
 7706:             if ($match) {
 7707:               my $refstatecond=$cond;
 7708:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7709:                   =~/\Q$priv\E\&([^\:]*)/) {
 7710:                   my $value = $1;
 7711:                   if ($priv eq 'bre') {
 7712:                       if ($noblockcheck) {
 7713:                           $thisallowed.=$value;
 7714:                       } else {
 7715:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7716:                           if (@blockers > 0) {
 7717:                               $thisallowed = 'B';
 7718:                           } else {
 7719:                               $thisallowed.=$value;
 7720:                           }
 7721:                       }
 7722:                   } else {
 7723:                       $thisallowed.=$value;
 7724:                   }
 7725:                   $uri=$refuri;
 7726:                   $statecond=$refstatecond;
 7727:               }
 7728:           }
 7729:         }
 7730:        }
 7731:    }
 7732: 
 7733: #
 7734: # Gathered now: all privileges that could apply, and condition number
 7735: # 
 7736: #
 7737: # Full or no access?
 7738: #
 7739: 
 7740:     if ($thisallowed=~/F/) {
 7741: 	return 'F';
 7742:     }
 7743: 
 7744:     unless ($thisallowed) {
 7745:         return '';
 7746:     }
 7747: 
 7748: # Restrictions exist, deal with them
 7749: #
 7750: #   C:according to course preferences
 7751: #   R:according to resource settings
 7752: #   L:unless locked
 7753: #   X:according to user session state
 7754: #
 7755: 
 7756: # Possibly locked functionality, check all courses
 7757: # Locks might take effect only after 10 minutes cache expiration for other
 7758: # courses, and 2 minutes for current course
 7759: 
 7760:     my $envkey;
 7761:     if ($thisallowed=~/L/) {
 7762:         foreach $envkey (keys(%env)) {
 7763:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7764:                my $courseid=$2;
 7765:                my $roleid=$1.'.'.$2;
 7766:                $courseid=~s/^\///;
 7767:                my $expiretime=600;
 7768:                if ($env{'request.role'} eq $roleid) {
 7769: 		  $expiretime=120;
 7770:                }
 7771: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7772:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7773:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7774: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7775:                }
 7776:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7777:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7778: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7779:                        &log($env{'user.domain'},$env{'user.name'},
 7780:                             $env{'user.home'},
 7781:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7782:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7783:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7784: 		       return '';
 7785:                    }
 7786:                }
 7787:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7788:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7789: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7790:                        &log($env{'user.domain'},$env{'user.name'},
 7791:                             $env{'user.home'},
 7792:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7793:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7794:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7795: 		       return '';
 7796:                    }
 7797:                }
 7798: 	   }
 7799:        }
 7800:     }
 7801:    
 7802: #
 7803: # Rest of the restrictions depend on selected course
 7804: #
 7805: 
 7806:     unless ($env{'request.course.id'}) {
 7807: 	if ($thisallowed eq 'A') {
 7808: 	    return 'A';
 7809:         } elsif ($thisallowed eq 'B') {
 7810:             return 'B';
 7811: 	} else {
 7812: 	    return '1';
 7813: 	}
 7814:     }
 7815: 
 7816: #
 7817: # Now user is definitely in a course
 7818: #
 7819: 
 7820: 
 7821: # Course preferences
 7822: 
 7823:    if ($thisallowed=~/C/) {
 7824:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7825:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7826:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7827: 	   =~/\Q$rolecode\E/) {
 7828: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7829: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7830: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7831: 			$env{'request.course.id'});
 7832: 	   }
 7833:            return '';
 7834:        }
 7835: 
 7836:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7837: 	   =~/\Q$unamedom\E/) {
 7838: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7839: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7840: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7841: 			$env{'request.course.id'});
 7842: 	   }
 7843:            return '';
 7844:        }
 7845:    }
 7846: 
 7847: # Resource preferences
 7848: 
 7849:    if ($thisallowed=~/R/) {
 7850:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7851:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7852: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7853: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7854: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7855: 	   }
 7856: 	   return '';
 7857:        }
 7858:    }
 7859: 
 7860: # Restricted by state or randomout?
 7861: 
 7862:    if ($thisallowed=~/X/) {
 7863:       if ($env{'acc.randomout'}) {
 7864: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7865:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7866:             return ''; 
 7867:          }
 7868:       }
 7869:       if (&condval($statecond)) {
 7870: 	 return '2';
 7871:       } else {
 7872:          return '';
 7873:       }
 7874:    }
 7875: 
 7876:     if ($thisallowed eq 'A') {
 7877: 	return 'A';
 7878:     } elsif ($thisallowed eq 'B') {
 7879:         return 'B';
 7880:     }
 7881:    return 'F';
 7882: }
 7883: 
 7884: # ------------------------------------------- Check construction space access
 7885: 
 7886: sub constructaccess {
 7887:     my ($url,$setpriv)=@_;
 7888: 
 7889: # We do not allow editing of previous versions of files
 7890:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7891: 
 7892: # Get username and domain from URL
 7893:     my ($ownername,$ownerdomain,$ownerhome);
 7894: 
 7895:     ($ownerdomain,$ownername) =
 7896:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 7897: 
 7898: # The URL does not really point to any authorspace, forget it
 7899:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7900: 
 7901: # Now we need to see if the user has access to the authorspace of
 7902: # $ownername at $ownerdomain
 7903: 
 7904:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7905: # Real author for this?
 7906:        $ownerhome = $env{'user.home'};
 7907:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7908:           return ($ownername,$ownerdomain,$ownerhome);
 7909:        }
 7910:     } else {
 7911: # Co-author for this?
 7912:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7913:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7914:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7915:             return ($ownername,$ownerdomain,$ownerhome);
 7916:         }
 7917:         if ($env{'request.course.id'}) {
 7918:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 7919:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 7920:                 if (&allowed('mdc',$env{'request.course.id'})) {
 7921:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 7922:                     return ($ownername,$ownerdomain,$ownerhome);
 7923:                 }
 7924:             }
 7925:         }
 7926:     }
 7927: 
 7928: # We don't have any access right now. If we are not possibly going to do anything about this,
 7929: # we might as well leave
 7930:    unless ($setpriv) { return ''; }
 7931: 
 7932: # Backdoor access?
 7933:     my $allowed=&allowed('eco',$ownerdomain);
 7934: # Nope
 7935:     unless ($allowed) { return ''; }
 7936: # Looks like we may have access, but could be locked by the owner of the construction space
 7937:     if ($allowed eq 'U') {
 7938:         my %blocked=&get('environment',['domcoord.author'],
 7939:                          $ownerdomain,$ownername);
 7940: # Is blocked by owner
 7941:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7942:     }
 7943:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7944: # Grant temporary access
 7945:         my $then=$env{'user.login.time'};
 7946:         my $update=$env{'user.update.time'};
 7947:         if (!$update) { $update = $then; }
 7948:         my $refresh=$env{'user.refresh.time'};
 7949:         if (!$refresh) { $refresh = $update; }
 7950:         my $now = time;
 7951:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7952:                            $now,'ca','constructaccess');
 7953:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7954:         return($ownername,$ownerdomain,$ownerhome);
 7955:     }
 7956: # No business here
 7957:     return '';
 7958: }
 7959: 
 7960: # ----------------------------------------------------------- Content Blocking
 7961: 
 7962: {
 7963: # Caches for faster Course Contents display where content blocking
 7964: # is in operation (i.e., interval param set) for timed quiz.
 7965: #
 7966: # User for whom data are being temporarily cached.
 7967: my $cacheduser='';
 7968: # Cached blockers for this user (a hash of blocking items). 
 7969: my %cachedblockers=();
 7970: # When the data were last cached.
 7971: my $cachedlast='';
 7972: 
 7973: sub load_all_blockers {
 7974:     my ($uname,$udom,$blocks)=@_;
 7975:     if (($uname ne '') && ($udom ne '')) { 
 7976:         if (($cacheduser eq $uname.':'.$udom) &&
 7977:             (abs($cachedlast-time)<5)) {
 7978:             return;
 7979:         }
 7980:     }
 7981:     $cachedlast=time;
 7982:     $cacheduser=$uname.':'.$udom;
 7983:     %cachedblockers = &get_commblock_resources($blocks);
 7984: }
 7985: 
 7986: sub get_comm_blocks {
 7987:     my ($cdom,$cnum) = @_;
 7988:     if ($cdom eq '' || $cnum eq '') {
 7989:         return unless ($env{'request.course.id'});
 7990:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7991:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7992:     }
 7993:     my %commblocks;
 7994:     my $hashid=$cdom.'_'.$cnum;
 7995:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7996:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7997:         %commblocks = %{$blocksref};
 7998:     } else {
 7999:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8000:         my $cachetime = 600;
 8001:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8002:     }
 8003:     return %commblocks;
 8004: }
 8005: 
 8006: sub get_commblock_resources {
 8007:     my ($blocks) = @_;
 8008:     my %blockers = ();
 8009:     return %blockers unless ($env{'request.course.id'});
 8010:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8011:     my %commblocks;
 8012:     if (ref($blocks) eq 'HASH') {
 8013:         %commblocks = %{$blocks};
 8014:     } else {
 8015:         %commblocks = &get_comm_blocks();
 8016:     }
 8017:     return %blockers unless (keys(%commblocks) > 0); 
 8018:     my $navmap = Apache::lonnavmaps::navmap->new();
 8019:     return %blockers unless (ref($navmap));
 8020:     my $now = time;
 8021:     foreach my $block (keys(%commblocks)) {
 8022:         if ($block =~ /^(\d+)____(\d+)$/) {
 8023:             my ($start,$end) = ($1,$2);
 8024:             if ($start <= $now && $end >= $now) {
 8025:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8026:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8027:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8028:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8029:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8030:                             }
 8031:                         }
 8032:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8033:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8034:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8035:                             }
 8036:                         }
 8037:                     }
 8038:                 }
 8039:             }
 8040:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8041:             my $item = $1;
 8042:             my @to_test;
 8043:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8044:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8045:                     my @interval;
 8046:                     my $type = 'map';
 8047:                     if ($item eq 'course') {
 8048:                         $type = 'course';
 8049:                         @interval=&EXT("resource.0.interval");
 8050:                     } else {
 8051:                         if ($item =~ /___\d+___/) {
 8052:                             $type = 'resource';
 8053:                             @interval=&EXT("resource.0.interval",$item);
 8054:                             if (ref($navmap)) {                        
 8055:                                 my $res = $navmap->getBySymb($item); 
 8056:                                 push(@to_test,$res);
 8057:                             }
 8058:                         } else {
 8059:                             my $mapsymb = &symbread($item,1);
 8060:                             if ($mapsymb) {
 8061:                                 if (ref($navmap)) {
 8062:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8063:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8064:                                     foreach my $res (@to_test) {
 8065:                                         my $symb = $res->symb();
 8066:                                         next if ($symb eq $mapsymb);
 8067:                                         if ($symb ne '') {
 8068:                                             @interval=&EXT("resource.0.interval",$symb);
 8069:                                             if ($interval[1] eq 'map') {
 8070:                                                 last;
 8071:                                             }
 8072:                                         }
 8073:                                     }
 8074:                                 }
 8075:                             }
 8076:                         }
 8077:                     }
 8078:                     if ($interval[0] =~ /^(\d+)/) {
 8079:                         my $timelimit = $1; 
 8080:                         my $first_access;
 8081:                         if ($type eq 'resource') {
 8082:                             $first_access=&get_first_access($interval[1],$item);
 8083:                         } elsif ($type eq 'map') {
 8084:                             $first_access=&get_first_access($interval[1],undef,$item);
 8085:                         } else {
 8086:                             $first_access=&get_first_access($interval[1]);
 8087:                         }
 8088:                         if ($first_access) {
 8089:                             my $timesup = $first_access+$timelimit;
 8090:                             if ($timesup > $now) {
 8091:                                 my $activeblock;
 8092:                                 foreach my $res (@to_test) {
 8093:                                     if ($res->answerable()) {
 8094:                                         $activeblock = 1;
 8095:                                         last;
 8096:                                     }
 8097:                                 }
 8098:                                 if ($activeblock) {
 8099:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8100:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8101:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8102:                                          }
 8103:                                     }
 8104:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8105:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8106:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8107:                                         }
 8108:                                     }
 8109:                                 }
 8110:                             }
 8111:                         }
 8112:                     }
 8113:                 }
 8114:             }
 8115:         }
 8116:     }
 8117:     return %blockers;
 8118: }
 8119: 
 8120: sub has_comm_blocking {
 8121:     my ($priv,$symb,$uri,$blocks) = @_;
 8122:     my @blockers;
 8123:     return unless ($env{'request.course.id'});
 8124:     return unless ($priv eq 'bre');
 8125:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8126:     return if ($env{'request.state'} eq 'construct');
 8127:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8128:     return unless (keys(%cachedblockers) > 0);
 8129:     my (%possibles,@symbs);
 8130:     if (!$symb) {
 8131:         $symb = &symbread($uri,1,1,1,\%possibles);
 8132:     }
 8133:     if ($symb) {
 8134:         @symbs = ($symb);
 8135:     } elsif (keys(%possibles)) { 
 8136:         @symbs = keys(%possibles);
 8137:     }
 8138:     my $noblock;
 8139:     foreach my $symb (@symbs) {
 8140:         last if ($noblock);
 8141:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8142:         foreach my $block (keys(%cachedblockers)) {
 8143:             if ($block =~ /^firstaccess____(.+)$/) {
 8144:                 my $item = $1;
 8145:                 if (($item eq $map) || ($item eq $symb)) {
 8146:                     $noblock = 1;
 8147:                     last;
 8148:                 }
 8149:             }
 8150:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8151:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8152:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8153:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8154:                             push(@blockers,$block);
 8155:                         }
 8156:                     }
 8157:                 }
 8158:             }
 8159:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8160:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8161:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8162:                         push(@blockers,$block);
 8163:                     }
 8164:                 }
 8165:             }
 8166:         }
 8167:     }
 8168:     return if ($noblock);
 8169:     return @blockers;
 8170: }
 8171: }
 8172: 
 8173: # -------------------------------- Deversion and split uri into path an filename   
 8174: 
 8175: #
 8176: #   Removes the version from a URI and
 8177: #   splits it in to its filename and path to the filename.
 8178: #   Seems like File::Basename could have done this more clearly.
 8179: #   Parameters:
 8180: #      $uri   - input URI
 8181: #   Returns:
 8182: #     Two element list consisting of 
 8183: #     $pathname  - the URI up to and excluding the trailing /
 8184: #     $filename  - The part of the URI following the last /
 8185: #  NOTE:
 8186: #    Another realization of this is simply:
 8187: #    use File::Basename;
 8188: #    ...
 8189: #    $uri = shift;
 8190: #    $filename = basename($uri);
 8191: #    $path     = dirname($uri);
 8192: #    return ($filename, $path);
 8193: #
 8194: #     The implementation below is probably faster however.
 8195: #
 8196: sub split_uri_for_cond {
 8197:     my $uri=&deversion(&declutter(shift));
 8198:     my @uriparts=split(/\//,$uri);
 8199:     my $filename=pop(@uriparts);
 8200:     my $pathname=join('/',@uriparts);
 8201:     return ($pathname,$filename);
 8202: }
 8203: # --------------------------------------------------- Is a resource on the map?
 8204: 
 8205: sub is_on_map {
 8206:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8207:     #Trying to find the conditional for the file
 8208:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8209: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8210:     if ($match) {
 8211: 	return (1,$1);
 8212:     } else {
 8213: 	return (0,0);
 8214:     }
 8215: }
 8216: 
 8217: # --------------------------------------------------------- Get symb from alias
 8218: 
 8219: sub get_symb_from_alias {
 8220:     my $symb=shift;
 8221:     my ($map,$resid,$url)=&decode_symb($symb);
 8222: # Already is a symb
 8223:     if ($url) { return $symb; }
 8224: # Must be an alias
 8225:     my $aliassymb='';
 8226:     my %bighash;
 8227:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8228:                             &GDBM_READER(),0640)) {
 8229:         my $rid=$bighash{'mapalias_'.$symb};
 8230: 	if ($rid) {
 8231: 	    my ($mapid,$resid)=split(/\./,$rid);
 8232: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8233: 				    $resid,$bighash{'src_'.$rid});
 8234: 	}
 8235:         untie %bighash;
 8236:     }
 8237:     return $aliassymb;
 8238: }
 8239: 
 8240: # ----------------------------------------------------------------- Define Role
 8241: 
 8242: sub definerole {
 8243:   if (allowed('mcr','/')) {
 8244:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8245:     foreach my $role (split(':',$sysrole)) {
 8246: 	my ($crole,$cqual)=split(/\&/,$role);
 8247:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8248:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8249: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8250:                return "refused:s:$crole&$cqual"; 
 8251:             }
 8252:         }
 8253:     }
 8254:     foreach my $role (split(':',$domrole)) {
 8255: 	my ($crole,$cqual)=split(/\&/,$role);
 8256:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8257:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8258: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8259:                return "refused:d:$crole&$cqual"; 
 8260:             }
 8261:         }
 8262:     }
 8263:     foreach my $role (split(':',$courole)) {
 8264: 	my ($crole,$cqual)=split(/\&/,$role);
 8265:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8266:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8267: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8268:                return "refused:c:$crole&$cqual"; 
 8269:             }
 8270:         }
 8271:     }
 8272:     my $uhome;
 8273:     if (($uname ne '') && ($udom ne '')) {
 8274:         $uhome = &homeserver($uname,$udom);
 8275:         return $uhome if ($uhome eq 'no_host');
 8276:     } else {
 8277:         $uname = $env{'user.name'};
 8278:         $udom = $env{'user.domain'};
 8279:         $uhome = $env{'user.home'};
 8280:     }
 8281:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8282:                 "$udom:$uname:rolesdef_$rolename=".
 8283:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8284:     return reply($command,$uhome);
 8285:   } else {
 8286:     return 'refused';
 8287:   }
 8288: }
 8289: 
 8290: # ---------------- Make a metadata query against the network of library servers
 8291: 
 8292: sub metadata_query {
 8293:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8294:     my %rhash;
 8295:     my %libserv = &all_library();
 8296:     my @server_list = (defined($server_array) ? @$server_array
 8297:                                               : keys(%libserv) );
 8298:     for my $server (@server_list) {
 8299:         my $domains = ''; 
 8300:         if (ref($domains_hash) eq 'HASH') {
 8301:             $domains = $domains_hash->{$server}; 
 8302:         }
 8303: 	unless ($custom or $customshow) {
 8304: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8305: 	    $rhash{$server}=$reply;
 8306: 	}
 8307: 	else {
 8308: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8309: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8310: 			     $server);
 8311: 	    $rhash{$server}=$reply;
 8312: 	}
 8313:     }
 8314:     return \%rhash;
 8315: }
 8316: 
 8317: # ----------------------------------------- Send log queries and wait for reply
 8318: 
 8319: sub log_query {
 8320:     my ($uname,$udom,$query,%filters)=@_;
 8321:     my $uhome=&homeserver($uname,$udom);
 8322:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8323:     my $uhost=&hostname($uhome);
 8324:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8325:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8326:                        $uhome);
 8327:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8328:     return get_query_reply($queryid);
 8329: }
 8330: 
 8331: # -------------------------- Update MySQL table for portfolio file
 8332: 
 8333: sub update_portfolio_table {
 8334:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8335:     if ($group ne '') {
 8336:         $file_name =~s /^\Q$group\E//;
 8337:     }
 8338:     my $homeserver = &homeserver($uname,$udom);
 8339:     my $queryid=
 8340:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8341:                ':'.&escape($file_name).':'.$action,$homeserver);
 8342:     my $reply = &get_query_reply($queryid);
 8343:     return $reply;
 8344: }
 8345: 
 8346: # -------------------------- Update MySQL allusers table
 8347: 
 8348: sub update_allusers_table {
 8349:     my ($uname,$udom,$names) = @_;
 8350:     my $homeserver = &homeserver($uname,$udom);
 8351:     my $queryid=
 8352:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8353:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8354:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8355:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8356:                'generation='.&escape($names->{'generation'}).'%%'.
 8357:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8358:                'id='.&escape($names->{'id'}),$homeserver);
 8359:     return;
 8360: }
 8361: 
 8362: # ------- Request retrieval of institutional classlists for course(s)
 8363: 
 8364: sub fetch_enrollment_query {
 8365:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8366:     my ($homeserver,$sleep,$loopmax);
 8367:     my $maxtries = 1;
 8368:     if ($context eq 'automated') {
 8369:         $homeserver = $perlvar{'lonHostID'};
 8370:         $sleep = 2;
 8371:         $loopmax = 100;
 8372:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8373:     } else {
 8374:         $homeserver = &homeserver($cnum,$dom);
 8375:     }
 8376:     my $host=&hostname($homeserver);
 8377:     my $cmd = '';
 8378:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8379:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8380:     }
 8381:     $cmd =~ s/%%$//;
 8382:     $cmd = &escape($cmd);
 8383:     my $query = 'fetchenrollment';
 8384:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8385:     unless ($queryid=~/^\Q$host\E\_/) { 
 8386:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8387:         return 'error: '.$queryid;
 8388:     }
 8389:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8390:     my $tries = 1;
 8391:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8392:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8393:         $tries ++;
 8394:     }
 8395:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8396:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8397:     } else {
 8398:         my @responses = split(/:/,$reply);
 8399:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8400:             foreach my $line (@responses) {
 8401:                 my ($key,$value) = split(/=/,$line,2);
 8402:                 $$replyref{$key} = $value;
 8403:             }
 8404:         } else {
 8405:             my $pathname = LONCAPA::tempdir();
 8406:             foreach my $line (@responses) {
 8407:                 my ($key,$value) = split(/=/,$line);
 8408:                 $$replyref{$key} = $value;
 8409:                 if ($value > 0) {
 8410:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8411:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8412:                         my $destname = $pathname.'/'.$filename;
 8413:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8414:                         if ($xml_classlist =~ /^error/) {
 8415:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8416:                         } else {
 8417:                             if ( open(FILE,">$destname") ) {
 8418:                                 print FILE &unescape($xml_classlist);
 8419:                                 close(FILE);
 8420:                             } else {
 8421:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8422:                             }
 8423:                         }
 8424:                     }
 8425:                 }
 8426:             }
 8427:         }
 8428:         return 'ok';
 8429:     }
 8430:     return 'error';
 8431: }
 8432: 
 8433: sub get_query_reply {
 8434:     my ($queryid,$sleep,$loopmax) = @_;;
 8435:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8436:         $sleep = 0.2;
 8437:     }
 8438:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8439:         $loopmax = 100;
 8440:     }
 8441:     my $replyfile=LONCAPA::tempdir().$queryid;
 8442:     my $reply='';
 8443:     for (1..$loopmax) {
 8444: 	sleep($sleep);
 8445:         if (-e $replyfile.'.end') {
 8446: 	    if (open(my $fh,$replyfile)) {
 8447: 		$reply = join('',<$fh>);
 8448: 		close($fh);
 8449: 	   } else { return 'error: reply_file_error'; }
 8450:            return &unescape($reply);
 8451: 	}
 8452:     }
 8453:     return 'timeout:'.$queryid;
 8454: }
 8455: 
 8456: sub courselog_query {
 8457: #
 8458: # possible filters:
 8459: # url: url or symb
 8460: # username
 8461: # domain
 8462: # action: view, submit, grade
 8463: # start: timestamp
 8464: # end: timestamp
 8465: #
 8466:     my (%filters)=@_;
 8467:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8468:     if ($filters{'url'}) {
 8469: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8470:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8471:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8472:     }
 8473:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8474:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8475:     return &log_query($cname,$cdom,'courselog',%filters);
 8476: }
 8477: 
 8478: sub userlog_query {
 8479: #
 8480: # possible filters:
 8481: # action: log check role
 8482: # start: timestamp
 8483: # end: timestamp
 8484: #
 8485:     my ($uname,$udom,%filters)=@_;
 8486:     return &log_query($uname,$udom,'userlog',%filters);
 8487: }
 8488: 
 8489: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8490: 
 8491: sub auto_run {
 8492:     my ($cnum,$cdom) = @_;
 8493:     my $response = 0;
 8494:     my $settings;
 8495:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8496:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8497:         $settings = $domconfig{'autoenroll'};
 8498:         if ($settings->{'run'} eq '1') {
 8499:             $response = 1;
 8500:         }
 8501:     } else {
 8502:         my $homeserver;
 8503:         if (&is_course($cdom,$cnum)) {
 8504:             $homeserver = &homeserver($cnum,$cdom);
 8505:         } else {
 8506:             $homeserver = &domain($cdom,'primary');
 8507:         }
 8508:         if ($homeserver ne 'no_host') {
 8509:             $response = &reply('autorun:'.$cdom,$homeserver);
 8510:         }
 8511:     }
 8512:     return $response;
 8513: }
 8514: 
 8515: sub auto_get_sections {
 8516:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8517:     my $homeserver;
 8518:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8519:         $homeserver = &homeserver($cnum,$cdom);
 8520:     }
 8521:     if (!defined($homeserver)) { 
 8522:         if ($cdom =~ /^$match_domain$/) {
 8523:             $homeserver = &domain($cdom,'primary');
 8524:         }
 8525:     }
 8526:     my @secs;
 8527:     if (defined($homeserver)) {
 8528:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8529:         unless ($response eq 'refused') {
 8530:             @secs = split(/:/,$response);
 8531:         }
 8532:     }
 8533:     return @secs;
 8534: }
 8535: 
 8536: sub auto_new_course {
 8537:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8538:     my $homeserver = &homeserver($cnum,$cdom);
 8539:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8540:     return $response;
 8541: }
 8542: 
 8543: sub auto_validate_courseID {
 8544:     my ($cnum,$cdom,$inst_course_id) = @_;
 8545:     my $homeserver = &homeserver($cnum,$cdom);
 8546:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8547:     return $response;
 8548: }
 8549: 
 8550: sub auto_validate_instcode {
 8551:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8552:     my ($homeserver,$response);
 8553:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8554:         $homeserver = &homeserver($cnum,$cdom);
 8555:     }
 8556:     if (!defined($homeserver)) {
 8557:         if ($cdom =~ /^$match_domain$/) {
 8558:             $homeserver = &domain($cdom,'primary');
 8559:         }
 8560:     }
 8561:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8562:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8563:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8564:     return ($outcome,$description,$defaultcredits);
 8565: }
 8566: 
 8567: sub auto_create_password {
 8568:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8569:     my ($homeserver,$response);
 8570:     my $create_passwd = 0;
 8571:     my $authchk = '';
 8572:     if ($udom =~ /^$match_domain$/) {
 8573:         $homeserver = &domain($udom,'primary');
 8574:     }
 8575:     if ($homeserver eq '') {
 8576:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8577:             $homeserver = &homeserver($cnum,$cdom);
 8578:         }
 8579:     }
 8580:     if ($homeserver eq '') {
 8581:         $authchk = 'nodomain';
 8582:     } else {
 8583:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8584:         if ($response eq 'refused') {
 8585:             $authchk = 'refused';
 8586:         } else {
 8587:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8588:         }
 8589:     }
 8590:     return ($authparam,$create_passwd,$authchk);
 8591: }
 8592: 
 8593: sub auto_photo_permission {
 8594:     my ($cnum,$cdom,$students) = @_;
 8595:     my $homeserver = &homeserver($cnum,$cdom);
 8596:     my ($outcome,$perm_reqd,$conditions) = 
 8597: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8598:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8599: 	return (undef,undef);
 8600:     }
 8601:     return ($outcome,$perm_reqd,$conditions);
 8602: }
 8603: 
 8604: sub auto_checkphotos {
 8605:     my ($uname,$udom,$pid) = @_;
 8606:     my $homeserver = &homeserver($uname,$udom);
 8607:     my ($result,$resulttype);
 8608:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8609: 				   &escape($uname).':'.&escape($pid),
 8610: 				   $homeserver));
 8611:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8612: 	return (undef,undef);
 8613:     }
 8614:     if ($outcome) {
 8615:         ($result,$resulttype) = split(/:/,$outcome);
 8616:     } 
 8617:     return ($result,$resulttype);
 8618: }
 8619: 
 8620: sub auto_photochoice {
 8621:     my ($cnum,$cdom) = @_;
 8622:     my $homeserver = &homeserver($cnum,$cdom);
 8623:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8624: 						       &escape($cdom),
 8625: 						       $homeserver)));
 8626:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8627: 	return (undef,undef);
 8628:     }
 8629:     return ($update,$comment);
 8630: }
 8631: 
 8632: sub auto_photoupdate {
 8633:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8634:     my $homeserver = &homeserver($cnum,$dom);
 8635:     my $host=&hostname($homeserver);
 8636:     my $cmd = '';
 8637:     my $maxtries = 1;
 8638:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8639:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8640:     }
 8641:     $cmd =~ s/%%$//;
 8642:     $cmd = &escape($cmd);
 8643:     my $query = 'institutionalphotos';
 8644:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8645:     unless ($queryid=~/^\Q$host\E\_/) {
 8646:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8647:         return 'error: '.$queryid;
 8648:     }
 8649:     my $reply = &get_query_reply($queryid);
 8650:     my $tries = 1;
 8651:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8652:         $reply = &get_query_reply($queryid);
 8653:         $tries ++;
 8654:     }
 8655:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8656:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8657:     } else {
 8658:         my @responses = split(/:/,$reply);
 8659:         my $outcome = shift(@responses); 
 8660:         foreach my $item (@responses) {
 8661:             my ($key,$value) = split(/=/,$item);
 8662:             $$photo{$key} = $value;
 8663:         }
 8664:         return $outcome;
 8665:     }
 8666:     return 'error';
 8667: }
 8668: 
 8669: sub auto_instcode_format {
 8670:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8671: 	$cat_order) = @_;
 8672:     my $courses = '';
 8673:     my @homeservers;
 8674:     if ($caller eq 'global') {
 8675: 	my %servers = &get_servers($codedom,'library');
 8676: 	foreach my $tryserver (keys(%servers)) {
 8677: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8678: 		push(@homeservers,$tryserver);
 8679: 	    }
 8680:         }
 8681:     } elsif ($caller eq 'requests') {
 8682:         if ($codedom =~ /^$match_domain$/) {
 8683:             my $chome = &domain($codedom,'primary');
 8684:             unless ($chome eq 'no_host') {
 8685:                 push(@homeservers,$chome);
 8686:             }
 8687:         }
 8688:     } else {
 8689:         push(@homeservers,&homeserver($caller,$codedom));
 8690:     }
 8691:     foreach my $code (keys(%{$instcodes})) {
 8692:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8693:     }
 8694:     chop($courses);
 8695:     my $ok_response = 0;
 8696:     my $response;
 8697:     while (@homeservers > 0 && $ok_response == 0) {
 8698:         my $server = shift(@homeservers); 
 8699:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8700:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8701:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8702: 		split(/:/,$response);
 8703:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8704:             push(@{$codetitles},&str2array($codetitles_str));
 8705:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8706:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8707:             $ok_response = 1;
 8708:         }
 8709:     }
 8710:     if ($ok_response) {
 8711:         return 'ok';
 8712:     } else {
 8713:         return $response;
 8714:     }
 8715: }
 8716: 
 8717: sub auto_instcode_defaults {
 8718:     my ($domain,$returnhash,$code_order) = @_;
 8719:     my @homeservers;
 8720: 
 8721:     my %servers = &get_servers($domain,'library');
 8722:     foreach my $tryserver (keys(%servers)) {
 8723: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8724: 	    push(@homeservers,$tryserver);
 8725: 	}
 8726:     }
 8727: 
 8728:     my $response;
 8729:     foreach my $server (@homeservers) {
 8730:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8731:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8732: 	
 8733: 	foreach my $pair (split(/\&/,$response)) {
 8734: 	    my ($name,$value)=split(/\=/,$pair);
 8735: 	    if ($name eq 'code_order') {
 8736: 		@{$code_order} = split(/\&/,&unescape($value));
 8737: 	    } else {
 8738: 		$returnhash->{&unescape($name)}=&unescape($value);
 8739: 	    }
 8740: 	}
 8741: 	return 'ok';
 8742:     }
 8743: 
 8744:     return $response;
 8745: }
 8746: 
 8747: sub auto_possible_instcodes {
 8748:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8749:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8750:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8751:         return;
 8752:     }
 8753:     my (@homeservers,$uhome);
 8754:     if (defined(&domain($domain,'primary'))) {
 8755:         $uhome=&domain($domain,'primary');
 8756:         push(@homeservers,&domain($domain,'primary'));
 8757:     } else {
 8758:         my %servers = &get_servers($domain,'library');
 8759:         foreach my $tryserver (keys(%servers)) {
 8760:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8761:                 push(@homeservers,$tryserver);
 8762:             }
 8763:         }
 8764:     }
 8765:     my $response;
 8766:     foreach my $server (@homeservers) {
 8767:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8768:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8769:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8770:             split(':',$response);
 8771:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8772:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8773:         foreach my $item (split('&',$cat_title)) {   
 8774:             my ($name,$value)=split('=',$item);
 8775:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8776:         }
 8777:         foreach my $item (split('&',$cat_order)) {
 8778:             my ($name,$value)=split('=',$item);
 8779:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8780:         }
 8781:         return 'ok';
 8782:     }
 8783:     return $response;
 8784: }
 8785: 
 8786: sub auto_courserequest_checks {
 8787:     my ($dom) = @_;
 8788:     my ($homeserver,%validations);
 8789:     if ($dom =~ /^$match_domain$/) {
 8790:         $homeserver = &domain($dom,'primary');
 8791:     }
 8792:     unless ($homeserver eq 'no_host') {
 8793:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8794:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8795:             my @items = split(/&/,$response);
 8796:             foreach my $item (@items) {
 8797:                 my ($key,$value) = split('=',$item);
 8798:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8799:             }
 8800:         }
 8801:     }
 8802:     return %validations; 
 8803: }
 8804: 
 8805: sub auto_courserequest_validation {
 8806:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8807:     my ($homeserver,$response);
 8808:     if ($dom =~ /^$match_domain$/) {
 8809:         $homeserver = &domain($dom,'primary');
 8810:     }
 8811:     unless ($homeserver eq 'no_host') {
 8812:         my $customdata;
 8813:         if (ref($custominfo) eq 'HASH') {
 8814:             $customdata = &freeze_escape($custominfo);
 8815:         }
 8816:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8817:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8818:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8819:                                     $customdata,$homeserver));
 8820:     }
 8821:     return $response;
 8822: }
 8823: 
 8824: sub auto_validate_class_sec {
 8825:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8826:     my $homeserver = &homeserver($cnum,$cdom);
 8827:     my $ownerlist;
 8828:     if (ref($owners) eq 'ARRAY') {
 8829:         $ownerlist = join(',',@{$owners});
 8830:     } else {
 8831:         $ownerlist = $owners;
 8832:     }
 8833:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8834:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8835:     return $response;
 8836: }
 8837: 
 8838: sub auto_crsreq_update {
 8839:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8840:         $code,$accessstart,$accessend,$inbound) = @_;
 8841:     my ($homeserver,%crsreqresponse);
 8842:     if ($cdom =~ /^$match_domain$/) {
 8843:         $homeserver = &domain($cdom,'primary');
 8844:     }
 8845:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8846:         my $info;
 8847:         if (ref($inbound) eq 'HASH') {
 8848:             $info = &freeze_escape($inbound);
 8849:         }
 8850:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8851:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8852:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8853:                             &escape($title).':'.&escape($code).':'.
 8854:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8855:                             $homeserver);
 8856:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8857:             my @items = split(/&/,$response);
 8858:             foreach my $item (@items) {
 8859:                 my ($key,$value) = split('=',$item);
 8860:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8861:             }
 8862:         }
 8863:     }
 8864:     return \%crsreqresponse;
 8865: }
 8866: 
 8867: sub auto_export_grades {
 8868:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 8869:     my ($homeserver,%exportresponse);
 8870:     if ($cdom =~ /^$match_domain$/) {
 8871:         $homeserver = &domain($cdom,'primary');
 8872:     }
 8873:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8874:         my $info;
 8875:         if (ref($inforef) eq 'HASH') {
 8876:             $info = &freeze_escape($inforef);
 8877:         }
 8878:         if (ref($gradesref) eq 'HASH') {
 8879:             my $grades = &freeze_escape($gradesref);
 8880:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 8881:                                 $info.':'.$grades,$homeserver);
 8882:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 8883:                 my @items = split(/&/,$response);
 8884:                 foreach my $item (@items) {
 8885:                     my ($key,$value) = split('=',$item);
 8886:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 8887:                 }
 8888:             }
 8889:         }
 8890:     }
 8891:     return \%exportresponse;
 8892: }
 8893: 
 8894: sub check_instcode_cloning {
 8895:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 8896:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8897:         return;
 8898:     }
 8899:     my $canclone;
 8900:     if (@{$code_order} > 0) {
 8901:         my $instcoderegexp ='^';
 8902:         my @clonecodes = split(/\&/,$cloner);
 8903:         foreach my $item (@{$code_order}) {
 8904:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 8905:                 foreach my $pair (@clonecodes) {
 8906:                     my ($key,$val) = split(/\=/,$pair,2);
 8907:                     $val = &unescape($val);
 8908:                     if ($key eq $item) {
 8909:                         $instcoderegexp .= '('.$val.')';
 8910:                         last;
 8911:                     }
 8912:                 }
 8913:             } else {
 8914:                 $instcoderegexp .= $codedefaults->{$item};
 8915:             }
 8916:         }
 8917:         $instcoderegexp .= '$';
 8918:         my (@from,@to);
 8919:         eval {
 8920:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8921:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 8922:         };
 8923:         if ((@from > 0) && (@to > 0)) {
 8924:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8925:             if (!@diffs) {
 8926:                 $canclone = 1;
 8927:             }
 8928:         }
 8929:     }
 8930:     return $canclone;
 8931: }
 8932: 
 8933: sub default_instcode_cloning {
 8934:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 8935:     my (%codedefaults,@code_order,$canclone);
 8936:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 8937:         %codedefaults = %{$codedefaultsref};
 8938:         @code_order = @{$codeorderref};
 8939:     } elsif ($clonedom) {
 8940:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 8941:     }
 8942:     if (($domdefclone) && (@code_order)) {
 8943:         my @clonecodes = split(/\+/,$domdefclone);
 8944:         my $instcoderegexp ='^';
 8945:         foreach my $item (@code_order) {
 8946:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 8947:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 8948:             } else {
 8949:                 $instcoderegexp .= $codedefaults{$item};
 8950:             }
 8951:         }
 8952:         $instcoderegexp .= '$';
 8953:         my (@from,@to);
 8954:         eval {
 8955:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8956:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 8957:         };
 8958:         if ((@from > 0) && (@to > 0)) {
 8959:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8960:             if (!@diffs) {
 8961:                 $canclone = 1;
 8962:             }
 8963:         }
 8964:     }
 8965:     return $canclone;
 8966: }
 8967: 
 8968: # ------------------------------------------------------- Course Group routines
 8969: 
 8970: sub get_coursegroups {
 8971:     my ($cdom,$cnum,$group,$namespace) = @_;
 8972:     return(&dump($namespace,$cdom,$cnum,$group));
 8973: }
 8974: 
 8975: sub modify_coursegroup {
 8976:     my ($cdom,$cnum,$groupsettings) = @_;
 8977:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 8978: }
 8979: 
 8980: sub toggle_coursegroup_status {
 8981:     my ($cdom,$cnum,$group,$action) = @_;
 8982:     my ($from_namespace,$to_namespace);
 8983:     if ($action eq 'delete') {
 8984:         $from_namespace = 'coursegroups';
 8985:         $to_namespace = 'deleted_groups';
 8986:     } else {
 8987:         $from_namespace = 'deleted_groups';
 8988:         $to_namespace = 'coursegroups';
 8989:     }
 8990:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 8991:     if (my $tmp = &error(%curr_group)) {
 8992:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 8993:         return ('read error',$tmp);
 8994:     } else {
 8995:         my %savedsettings = %curr_group; 
 8996:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 8997:         my $deloutcome;
 8998:         if ($result eq 'ok') {
 8999:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9000:         } else {
 9001:             return ('write error',$result);
 9002:         }
 9003:         if ($deloutcome eq 'ok') {
 9004:             return 'ok';
 9005:         } else {
 9006:             return ('delete error',$deloutcome);
 9007:         }
 9008:     }
 9009: }
 9010: 
 9011: sub modify_group_roles {
 9012:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9013:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9014:     my $role = 'gr/'.&escape($userprivs);
 9015:     my ($uname,$udom) = split(/:/,$user);
 9016:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9017:     if ($result eq 'ok') {
 9018:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9019:     }
 9020:     return $result;
 9021: }
 9022: 
 9023: sub modify_coursegroup_membership {
 9024:     my ($cdom,$cnum,$membership) = @_;
 9025:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9026:     return $result;
 9027: }
 9028: 
 9029: sub get_active_groups {
 9030:     my ($udom,$uname,$cdom,$cnum) = @_;
 9031:     my $now = time;
 9032:     my %groups = ();
 9033:     foreach my $key (keys(%env)) {
 9034:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9035:             my ($start,$end) = split(/\./,$env{$key});
 9036:             if (($end!=0) && ($end<$now)) { next; }
 9037:             if (($start!=0) && ($start>$now)) { next; }
 9038:             if ($1 eq $cdom && $2 eq $cnum) {
 9039:                 $groups{$3} = $env{$key} ;
 9040:             }
 9041:         }
 9042:     }
 9043:     return %groups;
 9044: }
 9045: 
 9046: sub get_group_membership {
 9047:     my ($cdom,$cnum,$group) = @_;
 9048:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9049: }
 9050: 
 9051: sub get_users_groups {
 9052:     my ($udom,$uname,$courseid) = @_;
 9053:     my @usersgroups;
 9054:     my $cachetime=1800;
 9055: 
 9056:     my $hashid="$udom:$uname:$courseid";
 9057:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9058:     if (defined($cached)) {
 9059:         @usersgroups = split(/:/,$grouplist);
 9060:     } else {  
 9061:         $grouplist = '';
 9062:         my $courseurl = &courseid_to_courseurl($courseid);
 9063:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9064:         my $access_end = $env{'course.'.$courseid.
 9065:                               '.default_enrollment_end_date'};
 9066:         my $now = time;
 9067:         foreach my $key (keys(%roleshash)) {
 9068:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9069:                 my $group = $1;
 9070:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9071:                     my $start = $2;
 9072:                     my $end = $1;
 9073:                     if ($start == -1) { next; } # deleted from group
 9074:                     if (($start!=0) && ($start>$now)) { next; }
 9075:                     if (($end!=0) && ($end<$now)) {
 9076:                         if ($access_end && $access_end < $now) {
 9077:                             if ($access_end - $end < 86400) {
 9078:                                 push(@usersgroups,$group);
 9079:                             }
 9080:                         }
 9081:                         next;
 9082:                     }
 9083:                     push(@usersgroups,$group);
 9084:                 }
 9085:             }
 9086:         }
 9087:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9088:         $grouplist = join(':',@usersgroups);
 9089:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9090:     }
 9091:     return @usersgroups;
 9092: }
 9093: 
 9094: sub devalidate_getgroups_cache {
 9095:     my ($udom,$uname,$cdom,$cnum)=@_;
 9096:     my $courseid = $cdom.'_'.$cnum;
 9097: 
 9098:     my $hashid="$udom:$uname:$courseid";
 9099:     &devalidate_cache_new('getgroups',$hashid);
 9100: }
 9101: 
 9102: # ------------------------------------------------------------------ Plain Text
 9103: 
 9104: sub plaintext {
 9105:     my ($short,$type,$cid,$forcedefault) = @_;
 9106:     if ($short =~ m{^cr/}) {
 9107: 	return (split('/',$short))[-1];
 9108:     }
 9109:     if (!defined($cid)) {
 9110:         $cid = $env{'request.course.id'};
 9111:     }
 9112:     my %rolenames = (
 9113:                       Course    => 'std',
 9114:                       Community => 'alt1',
 9115:                       Placement => 'std',
 9116:                     );
 9117:     if ($cid ne '') {
 9118:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9119:             unless ($forcedefault) {
 9120:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9121:                 &Apache::lonlocal::mt_escape(\$roletext);
 9122:                 return &Apache::lonlocal::mt($roletext);
 9123:             }
 9124:         }
 9125:     }
 9126:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9127:         (defined($rolenames{$type})) && 
 9128:         (defined($prp{$short}{$rolenames{$type}}))) {
 9129:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9130:     } elsif ($cid ne '') {
 9131:         my $crstype = $env{'course.'.$cid.'.type'};
 9132:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9133:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9134:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9135:         }
 9136:     }
 9137:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9138: }
 9139: 
 9140: # ----------------------------------------------------------------- Assign Role
 9141: 
 9142: sub assignrole {
 9143:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9144:         $context)=@_;
 9145:     my $mrole;
 9146:     if ($role =~ /^cr\//) {
 9147:         my $cwosec=$url;
 9148:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9149: 	unless (&allowed('ccr',$cwosec)) {
 9150:            my $refused = 1;
 9151:            if ($context eq 'requestcourses') {
 9152:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9153:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9154:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9155:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9156:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9157:                            if ($crsenv{'internal.courseowner'} eq
 9158:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9159:                                $refused = '';
 9160:                            }
 9161:                        }
 9162:                    }
 9163:                }
 9164:            }
 9165:            if ($refused) {
 9166:                &logthis('Refused custom assignrole: '.
 9167:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9168:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9169:                return 'refused';
 9170:            }
 9171:         }
 9172:         $mrole='cr';
 9173:     } elsif ($role =~ /^gr\//) {
 9174:         my $cwogrp=$url;
 9175:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9176:         unless (&allowed('mdg',$cwogrp)) {
 9177:             &logthis('Refused group assignrole: '.
 9178:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9179:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9180:             return 'refused';
 9181:         }
 9182:         $mrole='gr';
 9183:     } else {
 9184:         my $cwosec=$url;
 9185:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9186:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9187:             my $refused;
 9188:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9189:                 if (!(&allowed('c'.$role,$url))) {
 9190:                     $refused = 1;
 9191:                 }
 9192:             } else {
 9193:                 $refused = 1;
 9194:             }
 9195:             if ($refused) {
 9196:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9197:                 if (!$selfenroll && $context eq 'course') {
 9198:                     my %crsenv;
 9199:                     if ($role eq 'cc' || $role eq 'co') {
 9200:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9201:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9202:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9203:                                 if ($crsenv{'internal.courseowner'} eq 
 9204:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9205:                                     $refused = '';
 9206:                                 }
 9207:                             }
 9208:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9209:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9210:                                 if ($crsenv{'internal.courseowner'} eq 
 9211:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9212:                                     $refused = '';
 9213:                                 }
 9214:                             }
 9215:                         }
 9216:                     }
 9217:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9218:                     $refused = '';
 9219:                 } elsif ($context eq 'requestcourses') {
 9220:                     my @possroles = ('st','ta','ep','in','cc','co');
 9221:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9222:                         my $wrongcc;
 9223:                         if ($cnum =~ /^$match_community$/) {
 9224:                             $wrongcc = 1 if ($role eq 'cc');
 9225:                         } else {
 9226:                             $wrongcc = 1 if ($role eq 'co');
 9227:                         }
 9228:                         unless ($wrongcc) {
 9229:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9230:                             if ($crsenv{'internal.courseowner'} eq 
 9231:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9232:                                 $refused = '';
 9233:                             }
 9234:                         }
 9235:                     }
 9236:                 } elsif ($context eq 'requestauthor') {
 9237:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9238:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9239:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9240:                             $refused = '';
 9241:                         } else {
 9242:                             my %domdefaults = &get_domain_defaults($udom);
 9243:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9244:                                 my $checkbystatus;
 9245:                                 if ($env{'user.adv'}) { 
 9246:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9247:                                     if ($disposition eq 'automatic') {
 9248:                                         $refused = '';
 9249:                                     } elsif ($disposition eq '') {
 9250:                                         $checkbystatus = 1;
 9251:                                     } 
 9252:                                 } else {
 9253:                                     $checkbystatus = 1;
 9254:                                 }
 9255:                                 if ($checkbystatus) {
 9256:                                     if ($env{'environment.inststatus'}) {
 9257:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9258:                                         foreach my $type (@inststatuses) {
 9259:                                             if (($type ne '') &&
 9260:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9261:                                                 $refused = '';
 9262:                                             }
 9263:                                         }
 9264:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9265:                                         $refused = '';
 9266:                                     }
 9267:                                 }
 9268:                             }
 9269:                         }
 9270:                     }
 9271:                 }
 9272:                 if ($refused) {
 9273:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9274:                              ' '.$role.' '.$end.' '.$start.' by '.
 9275: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9276:                     return 'refused';
 9277:                 }
 9278:             }
 9279:         } elsif ($role eq 'au') {
 9280:             if ($url ne '/'.$udom.'/') {
 9281:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9282:                          ' to assign author role for '.$uname.':'.$udom.
 9283:                          ' in domain: '.$url.' refused (wrong domain).');
 9284:                 return 'refused';
 9285:             }
 9286:         }
 9287:         $mrole=$role;
 9288:     }
 9289:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9290:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9291:     if ($end) { $command.='_'.$end; }
 9292:     if ($start) {
 9293: 	if ($end) { 
 9294:            $command.='_'.$start; 
 9295:         } else {
 9296:            $command.='_0_'.$start;
 9297:         }
 9298:     }
 9299:     my $origstart = $start;
 9300:     my $origend = $end;
 9301:     my $delflag;
 9302: # actually delete
 9303:     if ($deleteflag) {
 9304: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9305: # modify command to delete the role
 9306:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9307:                 "$udom:$uname:$url".'_'."$mrole";
 9308: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9309: # set start and finish to negative values for userrolelog
 9310:            $start=-1;
 9311:            $end=-1;
 9312:            $delflag = 1;
 9313:         }
 9314:     }
 9315: # send command
 9316:     my $answer=&reply($command,&homeserver($uname,$udom));
 9317: # log new user role if status is ok
 9318:     if ($answer eq 'ok') {
 9319: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9320:         if (($role eq 'cc') || ($role eq 'in') ||
 9321:             ($role eq 'ep') || ($role eq 'ad') ||
 9322:             ($role eq 'ta') || ($role eq 'st') ||
 9323:             ($role=~/^cr/) || ($role eq 'gr') ||
 9324:             ($role eq 'co')) {
 9325: # for course roles, perform group memberships changes triggered by role change.
 9326:             unless ($role =~ /^gr/) {
 9327:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9328:                                                  $origstart,$selfenroll,$context);
 9329:             }
 9330:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9331:                            $selfenroll,$context);
 9332:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9333:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9334:                  ($role eq 'da')) {
 9335:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9336:                            $context);
 9337:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9338:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9339:                              $context); 
 9340:         }
 9341:         if ($role eq 'cc') {
 9342:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9343:         }
 9344:     }
 9345:     return $answer;
 9346: }
 9347: 
 9348: sub autoupdate_coowners {
 9349:     my ($url,$end,$start,$uname,$udom) = @_;
 9350:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9351:     if (($cdom ne '') && ($cnum ne '')) {
 9352:         my $now = time;
 9353:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9354:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9355:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9356:             my $instcode = $coursehash{'internal.coursecode'};
 9357:             if ($instcode ne '') {
 9358:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9359:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9360:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9361:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9362:                         if ($result eq 'valid') {
 9363:                             if ($coursehash{'internal.co-owners'}) {
 9364:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9365:                                     push(@newcoowners,$coowner);
 9366:                                 }
 9367:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9368:                                     push(@newcoowners,$uname.':'.$udom);
 9369:                                 }
 9370:                                 @newcoowners = sort(@newcoowners);
 9371:                             } else {
 9372:                                 push(@newcoowners,$uname.':'.$udom);
 9373:                             }
 9374:                         } else {
 9375:                             if ($coursehash{'internal.co-owners'}) {
 9376:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9377:                                     unless ($coowner eq $uname.':'.$udom) {
 9378:                                         push(@newcoowners,$coowner);
 9379:                                     }
 9380:                                 }
 9381:                                 unless (@newcoowners > 0) {
 9382:                                     $delcoowners = 1;
 9383:                                     $coowners = '';
 9384:                                 }
 9385:                             }
 9386:                         }
 9387:                         if (@newcoowners || $delcoowners) {
 9388:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9389:                                             $delcoowners,@newcoowners);
 9390:                         }
 9391:                     }
 9392:                 }
 9393:             }
 9394:         }
 9395:     }
 9396: }
 9397: 
 9398: sub store_coowners {
 9399:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9400:     my $cid = $cdom.'_'.$cnum;
 9401:     my ($coowners,$delresult,$putresult);
 9402:     if (@newcoowners) {
 9403:         $coowners = join(',',@newcoowners);
 9404:         my %coownershash = (
 9405:                             'internal.co-owners' => $coowners,
 9406:                            );
 9407:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9408:         if ($putresult eq 'ok') {
 9409:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9410:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9411:             }
 9412:         }
 9413:     }
 9414:     if ($delcoowners) {
 9415:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9416:         if ($delresult eq 'ok') {
 9417:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9418:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9419:             }
 9420:         }
 9421:     }
 9422:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9423:         my %crsinfo =
 9424:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9425:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9426:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9427:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9428:         }
 9429:     }
 9430: }
 9431: 
 9432: # -------------------------------------------------- Modify user authentication
 9433: # Overrides without validation
 9434: 
 9435: sub modifyuserauth {
 9436:     my ($udom,$uname,$umode,$upass)=@_;
 9437:     my $uhome=&homeserver($uname,$udom);
 9438:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9439:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9440:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9441:              ' in domain '.$env{'request.role.domain'});  
 9442:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9443: 		     &escape($upass),$uhome);
 9444:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9445:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9446:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9447:     &log($udom,,$uname,$uhome,
 9448:         'Authentication changed by '.$env{'user.domain'}.', '.
 9449:                                      $env{'user.name'}.', '.$umode.
 9450:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9451:     unless ($reply eq 'ok') {
 9452:         &logthis('Authentication mode error: '.$reply);
 9453: 	return 'error: '.$reply;
 9454:     }   
 9455:     return 'ok';
 9456: }
 9457: 
 9458: # --------------------------------------------------------------- Modify a user
 9459: 
 9460: sub modifyuser {
 9461:     my ($udom,    $uname, $uid,
 9462:         $umode,   $upass, $first,
 9463:         $middle,  $last,  $gene,
 9464:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9465:     $udom= &LONCAPA::clean_domain($udom);
 9466:     $uname=&LONCAPA::clean_username($uname);
 9467:     my $showcandelete = 'none';
 9468:     if (ref($candelete) eq 'ARRAY') {
 9469:         if (@{$candelete} > 0) {
 9470:             $showcandelete = join(', ',@{$candelete});
 9471:         }
 9472:     }
 9473:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9474:              $umode.', '.$first.', '.$middle.', '.
 9475: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9476:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9477:                                      ' desiredhome not specified'). 
 9478:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9479:              ' in domain '.$env{'request.role.domain'});
 9480:     my $uhome=&homeserver($uname,$udom,'true');
 9481:     my $newuser;
 9482:     if ($uhome eq 'no_host') {
 9483:         $newuser = 1;
 9484:     }
 9485: # ----------------------------------------------------------------- Create User
 9486:     if (($uhome eq 'no_host') && 
 9487: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 9488:         my $unhome='';
 9489:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9490:             $unhome = $desiredhome;
 9491: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9492: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9493:         } else { # load balancing routine for determining $unhome
 9494:             my $loadm=10000000;
 9495: 	    my %servers = &get_servers($udom,'library');
 9496: 	    foreach my $tryserver (keys(%servers)) {
 9497: 		my $answer=reply('load',$tryserver);
 9498: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9499: 		    $loadm=$answer;
 9500: 		    $unhome=$tryserver;
 9501: 		}
 9502: 	    }
 9503:         }
 9504:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9505: 	    return 'error: unable to find a home server for '.$uname.
 9506:                    ' in domain '.$udom;
 9507:         }
 9508:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9509:                          &escape($upass),$unhome);
 9510: 	unless ($reply eq 'ok') {
 9511:             return 'error: '.$reply;
 9512:         }   
 9513:         $uhome=&homeserver($uname,$udom,'true');
 9514:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9515: 	    return 'error: unable verify users home machine.';
 9516:         }
 9517:     }   # End of creation of new user
 9518: # ---------------------------------------------------------------------- Add ID
 9519:     if ($uid) {
 9520:        $uid=~tr/A-Z/a-z/;
 9521:        my %uidhash=&idrget($udom,$uname);
 9522:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9523:          && (!$forceid)) {
 9524: 	  unless ($uid eq $uidhash{$uname}) {
 9525: 	      return 'error: user id "'.$uid.'" does not match '.
 9526:                   'current user id "'.$uidhash{$uname}.'".';
 9527:           }
 9528:        } else {
 9529: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9530:        }
 9531:     }
 9532: # -------------------------------------------------------------- Add names, etc
 9533:     my @tmp=&get('environment',
 9534: 		   ['firstname','middlename','lastname','generation','id',
 9535:                     'permanentemail','inststatus'],
 9536: 		   $udom,$uname);
 9537:     my (%names,%oldnames);
 9538:     if ($tmp[0] =~ m/^error:.*/) { 
 9539:         %names=(); 
 9540:     } else {
 9541:         %names = @tmp;
 9542:         %oldnames = %names;
 9543:     }
 9544: #
 9545: # If name, email and/or uid are blank (e.g., because an uploaded file
 9546: # of users did not contain them), do not overwrite existing values
 9547: # unless field is in $candelete array ref.  
 9548: #
 9549: 
 9550:     my @fields = ('firstname','middlename','lastname','generation',
 9551:                   'permanentemail','id');
 9552:     my %newvalues;
 9553:     if (ref($candelete) eq 'ARRAY') {
 9554:         foreach my $field (@fields) {
 9555:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9556:                 if ($field eq 'firstname') {
 9557:                     $names{$field} = $first;
 9558:                 } elsif ($field eq 'middlename') {
 9559:                     $names{$field} = $middle;
 9560:                 } elsif ($field eq 'lastname') {
 9561:                     $names{$field} = $last;
 9562:                 } elsif ($field eq 'generation') { 
 9563:                     $names{$field} = $gene;
 9564:                 } elsif ($field eq 'permanentemail') {
 9565:                     $names{$field} = $email;
 9566:                 } elsif ($field eq 'id') {
 9567:                     $names{$field}  = $uid;
 9568:                 }
 9569:             }
 9570:         }
 9571:     }
 9572:     if ($first)  { $names{'firstname'}  = $first; }
 9573:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9574:     if ($last)   { $names{'lastname'}   = $last; }
 9575:     if (defined($gene))   { $names{'generation'} = $gene; }
 9576:     if ($email) {
 9577:        $email=~s/[^\w\@\.\-\,]//gs;
 9578:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9579:     }
 9580:     if ($uid) { $names{'id'}  = $uid; }
 9581:     if (defined($inststatus)) {
 9582:         $names{'inststatus'} = '';
 9583:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9584:         if (ref($usertypes) eq 'HASH') {
 9585:             my @okstatuses; 
 9586:             foreach my $item (split(/:/,$inststatus)) {
 9587:                 if (defined($usertypes->{$item})) {
 9588:                     push(@okstatuses,$item);  
 9589:                 }
 9590:             }
 9591:             if (@okstatuses) {
 9592:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9593:             }
 9594:         }
 9595:     }
 9596:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9597:                  $umode.', '.$first.', '.$middle.', '.
 9598:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9599:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9600:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9601:     } else {
 9602:         $logmsg .= ' during self creation';
 9603:     }
 9604:     my $changed;
 9605:     if ($newuser) {
 9606:         $changed = 1;
 9607:     } else {
 9608:         foreach my $field (@fields) {
 9609:             if ($names{$field} ne $oldnames{$field}) {
 9610:                 $changed = 1;
 9611:                 last;
 9612:             }
 9613:         }
 9614:     }
 9615:     unless ($changed) {
 9616:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9617:         &logthis($logmsg);
 9618:         return 'ok';
 9619:     }
 9620:     my $reply = &put('environment', \%names, $udom,$uname);
 9621:     if ($reply ne 'ok') { 
 9622:         return 'error: '.$reply;
 9623:     }
 9624:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9625:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9626:     }
 9627:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9628:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9629:     $logmsg = 'Success modifying user '.$logmsg;
 9630:     &logthis($logmsg);
 9631:     return 'ok';
 9632: }
 9633: 
 9634: # -------------------------------------------------------------- Modify student
 9635: 
 9636: sub modifystudent {
 9637:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9638:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9639:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9640:     if (!$cid) {
 9641: 	unless ($cid=$env{'request.course.id'}) {
 9642: 	    return 'not_in_class';
 9643: 	}
 9644:     }
 9645: # --------------------------------------------------------------- Make the user
 9646:     my $reply=&modifyuser
 9647: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9648:          $desiredhome,$email,$inststatus);
 9649:     unless ($reply eq 'ok') { return $reply; }
 9650:     # This will cause &modify_student_enrollment to get the uid from the
 9651:     # student's environment
 9652:     $uid = undef if (!$forceid);
 9653:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9654:                                         $gene,$usec,$end,$start,$type,$locktype,
 9655:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9656:     return $reply;
 9657: }
 9658: 
 9659: sub modify_student_enrollment {
 9660:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9661:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9662:     my ($cdom,$cnum,$chome);
 9663:     if (!$cid) {
 9664: 	unless ($cid=$env{'request.course.id'}) {
 9665: 	    return 'not_in_class';
 9666: 	}
 9667: 	$cdom=$env{'course.'.$cid.'.domain'};
 9668: 	$cnum=$env{'course.'.$cid.'.num'};
 9669:     } else {
 9670: 	($cdom,$cnum)=split(/_/,$cid);
 9671:     }
 9672:     $chome=$env{'course.'.$cid.'.home'};
 9673:     if (!$chome) {
 9674: 	$chome=&homeserver($cnum,$cdom);
 9675:     }
 9676:     if (!$chome) { return 'unknown_course'; }
 9677:     # Make sure the user exists
 9678:     my $uhome=&homeserver($uname,$udom);
 9679:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9680: 	return 'error: no such user';
 9681:     }
 9682:     # Get student data if we were not given enough information
 9683:     if (!defined($first)  || $first  eq '' || 
 9684:         !defined($last)   || $last   eq '' || 
 9685:         !defined($uid)    || $uid    eq '' || 
 9686:         !defined($middle) || $middle eq '' || 
 9687:         !defined($gene)   || $gene   eq '') {
 9688:         # They did not supply us with enough data to enroll the student, so
 9689:         # we need to pick up more information.
 9690:         my %tmp = &get('environment',
 9691:                        ['firstname','middlename','lastname', 'generation','id']
 9692:                        ,$udom,$uname);
 9693: 
 9694:         #foreach my $key (keys(%tmp)) {
 9695:         #    &logthis("key $key = ".$tmp{$key});
 9696:         #}
 9697:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9698:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9699:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9700:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9701:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9702:     }
 9703:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9704:     my $user = "$uname:$udom";
 9705:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9706:     my $reply=cput('classlist',
 9707: 		   {$user => 
 9708: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9709: 		   $cdom,$cnum);
 9710:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9711:         &devalidate_getsection_cache($udom,$uname,$cid);
 9712:     } else { 
 9713: 	return 'error: '.$reply;
 9714:     }
 9715:     # Add student role to user
 9716:     my $uurl='/'.$cid;
 9717:     $uurl=~s/\_/\//g;
 9718:     if ($usec) {
 9719: 	$uurl.='/'.$usec;
 9720:     }
 9721:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9722:                              $selfenroll,$context);
 9723:     if ($result ne 'ok') {
 9724:         if ($old_entry{$user} ne '') {
 9725:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9726:         } else {
 9727:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9728:         }
 9729:     }
 9730:     return $result; 
 9731: }
 9732: 
 9733: sub format_name {
 9734:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9735:     my $name;
 9736:     if ($first ne 'lastname') {
 9737: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9738:     } else {
 9739: 	if ($lastname=~/\S/) {
 9740: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9741: 	    $name=~s/\s+,/,/;
 9742: 	} else {
 9743: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9744: 	}
 9745:     }
 9746:     $name=~s/^\s+//;
 9747:     $name=~s/\s+$//;
 9748:     $name=~s/\s+/ /g;
 9749:     return $name;
 9750: }
 9751: 
 9752: # ------------------------------------------------- Write to course preferences
 9753: 
 9754: sub writecoursepref {
 9755:     my ($courseid,%prefs)=@_;
 9756:     $courseid=~s/^\///;
 9757:     $courseid=~s/\_/\//g;
 9758:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9759:     my $chome=homeserver($cnum,$cdomain);
 9760:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9761: 	return 'error: no such course';
 9762:     }
 9763:     my $cstring='';
 9764:     foreach my $pref (keys(%prefs)) {
 9765: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9766:     }
 9767:     $cstring=~s/\&$//;
 9768:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9769: }
 9770: 
 9771: # ---------------------------------------------------------- Make/modify course
 9772: 
 9773: sub createcourse {
 9774:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9775:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9776:     $url=&declutter($url);
 9777:     my $cid='';
 9778:     if ($context eq 'requestcourses') {
 9779:         my $can_create = 0;
 9780:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9781:         if ($udom eq $ownerdom) {
 9782:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9783:                                   $context)) {
 9784:                 $can_create = 1;
 9785:             }
 9786:         } else {
 9787:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9788:                                            $category);
 9789:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9790:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9791:                 if (@curr > 0) {
 9792:                     my @options = qw(approval validate autolimit);
 9793:                     my $optregex = join('|',@options);
 9794:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9795:                         $can_create = 1;
 9796:                     }
 9797:                 }
 9798:             }
 9799:         }
 9800:         if ($can_create) {
 9801:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 9802:                 unless (&allowed('ccc',$udom)) {
 9803:                     return 'refused'; 
 9804:                 }
 9805:             }
 9806:         } else {
 9807:             return 'refused';
 9808:         }
 9809:     } elsif (!&allowed('ccc',$udom)) {
 9810:         return 'refused';
 9811:     }
 9812: # --------------------------------------------------------------- Get Unique ID
 9813:     my $uname;
 9814:     if ($cnum =~ /^$match_courseid$/) {
 9815:         my $chome=&homeserver($cnum,$udom,'true');
 9816:         if (($chome eq '') || ($chome eq 'no_host')) {
 9817:             $uname = $cnum;
 9818:         } else {
 9819:             $uname = &generate_coursenum($udom,$crstype);
 9820:         }
 9821:     } else {
 9822:         $uname = &generate_coursenum($udom,$crstype);
 9823:     }
 9824:     return $uname if ($uname =~ /^error/);
 9825: # -------------------------------------------------- Check supplied server name
 9826:     if (!defined($course_server)) {
 9827:         if (defined(&domain($udom,'primary'))) {
 9828:             $course_server = &domain($udom,'primary');
 9829:         } else {
 9830:             $course_server = $env{'user.home'}; 
 9831:         }
 9832:     }
 9833:     my %host_servers =
 9834:         &Apache::lonnet::get_servers($udom,'library');
 9835:     unless ($host_servers{$course_server}) {
 9836:         return 'error: invalid home server for course: '.$course_server;
 9837:     }
 9838: # ------------------------------------------------------------- Make the course
 9839:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 9840:                       $course_server);
 9841:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 9842:     my $uhome=&homeserver($uname,$udom,'true');
 9843:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9844: 	return 'error: no such course';
 9845:     }
 9846: # ----------------------------------------------------------------- Course made
 9847: # log existence
 9848:     my $now = time;
 9849:     my $newcourse = {
 9850:                     $udom.'_'.$uname => {
 9851:                                      description => $description,
 9852:                                      inst_code   => $inst_code,
 9853:                                      owner       => $course_owner,
 9854:                                      type        => $crstype,
 9855:                                      creator     => $env{'user.name'}.':'.
 9856:                                                     $env{'user.domain'},
 9857:                                      created     => $now,
 9858:                                      context     => $context,
 9859:                                                 },
 9860:                     };
 9861:     &courseidput($udom,$newcourse,$uhome,'notime');
 9862: # set toplevel url
 9863:     my $topurl=$url;
 9864:     unless ($nonstandard) {
 9865: # ------------------------------------------ For standard courses, make top url
 9866:         my $mapurl=&clutter($url);
 9867:         if ($mapurl eq '/res/') { $mapurl=''; }
 9868:         $env{'form.initmap'}=(<<ENDINITMAP);
 9869: <map>
 9870: <resource id="1" type="start"></resource>
 9871: <resource id="2" src="$mapurl"></resource>
 9872: <resource id="3" type="finish"></resource>
 9873: <link index="1" from="1" to="2"></link>
 9874: <link index="2" from="2" to="3"></link>
 9875: </map>
 9876: ENDINITMAP
 9877:         $topurl=&declutter(
 9878:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 9879:                           );
 9880:     }
 9881: # ----------------------------------------------------------- Write preferences
 9882:     &writecoursepref($udom.'_'.$uname,
 9883:                      ('description'              => $description,
 9884:                       'url'                      => $topurl,
 9885:                       'internal.creator'         => $env{'user.name'}.':'.
 9886:                                                     $env{'user.domain'},
 9887:                       'internal.created'         => $now,
 9888:                       'internal.creationcontext' => $context)
 9889:                     );
 9890:     return '/'.$udom.'/'.$uname;
 9891: }
 9892: 
 9893: # ------------------------------------------------------------------- Create ID
 9894: sub generate_coursenum {
 9895:     my ($udom,$crstype) = @_;
 9896:     my $domdesc = &domain($udom);
 9897:     return 'error: invalid domain' if ($domdesc eq '');
 9898:     my $first;
 9899:     if ($crstype eq 'Community') {
 9900:         $first = '0';
 9901:     } else {
 9902:         $first = int(1+rand(9)); 
 9903:     } 
 9904:     my $uname=$first.
 9905:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9906:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9907:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9908: # ----------------------------------------------- Make sure that does not exist
 9909:     my $uhome=&homeserver($uname,$udom,'true');
 9910:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9911:         if ($crstype eq 'Community') {
 9912:             $first = '0';
 9913:         } else {
 9914:             $first = int(1+rand(9));
 9915:         }
 9916:         $uname=$first.
 9917:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9918:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9919:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9920:         $uhome=&homeserver($uname,$udom,'true');
 9921:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9922:             return 'error: unable to generate unique course-ID';
 9923:         }
 9924:     }
 9925:     return $uname;
 9926: }
 9927: 
 9928: sub is_course {
 9929:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 9930:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 9931: 
 9932:     return unless $cdom and $cnum;
 9933: 
 9934:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 9935:         '.');
 9936: 
 9937:     return unless(exists($courses{$cdom.'_'.$cnum}));
 9938:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 9939: }
 9940: 
 9941: sub store_userdata {
 9942:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 9943:     my $result;
 9944:     if ($datakey ne '') {
 9945:         if (ref($storehash) eq 'HASH') {
 9946:             if ($udom eq '' || $uname eq '') {
 9947:                 $udom = $env{'user.domain'};
 9948:                 $uname = $env{'user.name'};
 9949:             }
 9950:             my $uhome=&homeserver($uname,$udom);
 9951:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 9952:                 $result = 'error: no_host';
 9953:             } else {
 9954:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 9955:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 9956: 
 9957:                 my $namevalue='';
 9958:                 foreach my $key (keys(%{$storehash})) {
 9959:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 9960:                 }
 9961:                 $namevalue=~s/\&$//;
 9962:                 unless ($namespace eq 'courserequests') {
 9963:                     $datakey = &escape($datakey);
 9964:                 }
 9965:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 9966:                                   $namevalue,$uhome);
 9967:             }
 9968:         } else {
 9969:             $result = 'error: data to store was not a hash reference'; 
 9970:         }
 9971:     } else {
 9972:         $result= 'error: invalid requestkey'; 
 9973:     }
 9974:     return $result;
 9975: }
 9976: 
 9977: # ---------------------------------------------------------- Assign Custom Role
 9978: 
 9979: sub assigncustomrole {
 9980:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 9981:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 9982:                        $end,$start,$deleteflag,$selfenroll,$context);
 9983: }
 9984: 
 9985: # ----------------------------------------------------------------- Revoke Role
 9986: 
 9987: sub revokerole {
 9988:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 9989:     my $now=time;
 9990:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 9991: }
 9992: 
 9993: # ---------------------------------------------------------- Revoke Custom Role
 9994: 
 9995: sub revokecustomrole {
 9996:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 9997:     my $now=time;
 9998:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 9999:            $deleteflag,$selfenroll,$context);
10000: }
10001: 
10002: # ------------------------------------------------------------ Disk usage
10003: sub diskusage {
10004:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10005:     $directorypath =~ s/\/$//;
10006:     my $listing=&reply('du2:'.&escape($directorypath).':'
10007:                        .&escape($getpropath).':'.&escape($uname).':'
10008:                        .&escape($udom),homeserver($uname,$udom));
10009:     if ($listing eq 'unknown_cmd') {
10010:         if ($getpropath) {
10011:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10012:         }
10013:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10014:     }
10015:     return $listing;
10016: }
10017: 
10018: sub is_locked {
10019:     my ($file_name, $domain, $user, $which) = @_;
10020:     my @check;
10021:     my $is_locked;
10022:     push (@check,$file_name);
10023:     my %locked = &get('file_permissions',\@check,
10024: 		      $env{'user.domain'},$env{'user.name'});
10025:     my ($tmp)=keys(%locked);
10026:     if ($tmp=~/^error:/) { undef(%locked); }
10027:     
10028:     if (ref($locked{$file_name}) eq 'ARRAY') {
10029:         $is_locked = 'false';
10030:         foreach my $entry (@{$locked{$file_name}}) {
10031:            if (ref($entry) eq 'ARRAY') {
10032:                $is_locked = 'true';
10033:                if (ref($which) eq 'ARRAY') {
10034:                    push(@{$which},$entry);
10035:                } else {
10036:                    last;
10037:                }
10038:            }
10039:        }
10040:     } else {
10041:         $is_locked = 'false';
10042:     }
10043:     return $is_locked;
10044: }
10045: 
10046: sub declutter_portfile {
10047:     my ($file) = @_;
10048:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10049:     return $file;
10050: }
10051: 
10052: # ------------------------------------------------------------- Mark as Read Only
10053: 
10054: sub mark_as_readonly {
10055:     my ($domain,$user,$files,$what) = @_;
10056:     my %current_permissions = &dump('file_permissions',$domain,$user);
10057:     my ($tmp)=keys(%current_permissions);
10058:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10059:     foreach my $file (@{$files}) {
10060: 	$file = &declutter_portfile($file);
10061:         push(@{$current_permissions{$file}},$what);
10062:     }
10063:     &put('file_permissions',\%current_permissions,$domain,$user);
10064:     return;
10065: }
10066: 
10067: # ------------------------------------------------------------Save Selected Files
10068: 
10069: sub save_selected_files {
10070:     my ($user, $path, @files) = @_;
10071:     my $filename = $user."savedfiles";
10072:     my @other_files = &files_not_in_path($user, $path);
10073:     open (OUT, '>'.$tmpdir.$filename);
10074:     foreach my $file (@files) {
10075:         print (OUT $env{'form.currentpath'}.$file."\n");
10076:     }
10077:     foreach my $file (@other_files) {
10078:         print (OUT $file."\n");
10079:     }
10080:     close (OUT);
10081:     return 'ok';
10082: }
10083: 
10084: sub clear_selected_files {
10085:     my ($user) = @_;
10086:     my $filename = $user."savedfiles";
10087:     open (OUT, '>'.LONCAPA::tempdir().$filename);
10088:     print (OUT undef);
10089:     close (OUT);
10090:     return ("ok");    
10091: }
10092: 
10093: sub files_in_path {
10094:     my ($user, $path) = @_;
10095:     my $filename = $user."savedfiles";
10096:     my %return_files;
10097:     open (IN, '<'.LONCAPA::tempdir().$filename);
10098:     while (my $line_in = <IN>) {
10099:         chomp ($line_in);
10100:         my @paths_and_file = split (m!/!, $line_in);
10101:         my $file_part = pop (@paths_and_file);
10102:         my $path_part = join ('/', @paths_and_file);
10103:         $path_part.='/';
10104:         my $path_and_file = $path_part.$file_part;
10105:         if ($path_part eq $path) {
10106:             $return_files{$file_part}= 'selected';
10107:         }
10108:     }
10109:     close (IN);
10110:     return (\%return_files);
10111: }
10112: 
10113: # called in portfolio select mode, to show files selected NOT in current directory
10114: sub files_not_in_path {
10115:     my ($user, $path) = @_;
10116:     my $filename = $user."savedfiles";
10117:     my @return_files;
10118:     my $path_part;
10119:     open(IN, '<'.LONCAPA::.$filename);
10120:     while (my $line = <IN>) {
10121:         #ok, I know it's clunky, but I want it to work
10122:         my @paths_and_file = split(m|/|, $line);
10123:         my $file_part = pop(@paths_and_file);
10124:         chomp($file_part);
10125:         my $path_part = join('/', @paths_and_file);
10126:         $path_part .= '/';
10127:         my $path_and_file = $path_part.$file_part;
10128:         if ($path_part ne $path) {
10129:             push(@return_files, ($path_and_file));
10130:         }
10131:     }
10132:     close(OUT);
10133:     return (@return_files);
10134: }
10135: 
10136: #------------------------------Submitted/Handedback Portfolio Files Versioning
10137:  
10138: sub portfiles_versioning {
10139:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10140:     my $portfolio_root = '/userfiles/portfolio';
10141:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10142:     foreach my $file (@{$portfiles}) {
10143:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10144:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10145:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10146:         my $getpropath = 1;
10147:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10148:                                              $stu_name,$getpropath);
10149:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10150:         my $new_answer = 
10151:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10152:         if ($new_answer ne 'problem getting file') {
10153:             push(@{$versioned_portfiles}, $directory.$new_answer);
10154:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10155:                               [$symb,$env{'request.course.id'},'graded']);
10156:         }
10157:     }
10158: }
10159: 
10160: sub get_next_version {
10161:     my ($answer_name, $answer_ext, $dir_list) = @_;
10162:     my $version;
10163:     if (ref($dir_list) eq 'ARRAY') {
10164:         foreach my $row (@{$dir_list}) {
10165:             my ($file) = split(/\&/,$row,2);
10166:             my ($file_name,$file_version,$file_ext) =
10167:                 &file_name_version_ext($file);
10168:             if (($file_name eq $answer_name) &&
10169:                 ($file_ext eq $answer_ext)) {
10170:                      # gets here if filename and extension match,
10171:                      # regardless of version
10172:                 if ($file_version ne '') {
10173:                     # a versioned file is found  so save it for later
10174:                     if ($file_version > $version) {
10175:                         $version = $file_version;
10176:                     }
10177:                 }
10178:             }
10179:         }
10180:     }
10181:     $version ++;
10182:     return($version);
10183: }
10184: 
10185: sub version_selected_portfile {
10186:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10187:     my ($answer_name,$answer_ver,$answer_ext) =
10188:         &file_name_version_ext($file_name);
10189:     my $new_answer;
10190:     $env{'form.copy'} =
10191:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10192:     if($env{'form.copy'} eq '-1') {
10193:         $new_answer = 'problem getting file';
10194:     } else {
10195:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10196:         my $copy_result = 
10197:             &finishuserfileupload($stu_name,$domain,'copy',
10198:                                   '/portfolio'.$directory.$new_answer);
10199:     }
10200:     undef($env{'form.copy'});
10201:     return ($new_answer);
10202: }
10203: 
10204: sub file_name_version_ext {
10205:     my ($file)=@_;
10206:     my @file_parts = split(/\./, $file);
10207:     my ($name,$version,$ext);
10208:     if (@file_parts > 1) {
10209:         $ext=pop(@file_parts);
10210:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10211:             $version=pop(@file_parts);
10212:         }
10213:         $name=join('.',@file_parts);
10214:     } else {
10215:         $name=join('.',@file_parts);
10216:     }
10217:     return($name,$version,$ext);
10218: }
10219: 
10220: #----------------------------------------------Get portfolio file permissions
10221: 
10222: sub get_portfile_permissions {
10223:     my ($domain,$user) = @_;
10224:     my %current_permissions = &dump('file_permissions',$domain,$user);
10225:     my ($tmp)=keys(%current_permissions);
10226:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10227:     return \%current_permissions;
10228: }
10229: 
10230: #---------------------------------------------Get portfolio file access controls
10231: 
10232: sub get_access_controls {
10233:     my ($current_permissions,$group,$file) = @_;
10234:     my %access;
10235:     my $real_file = $file;
10236:     $file =~ s/\.meta$//;
10237:     if (defined($file)) {
10238:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10239:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10240:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10241:             }
10242:         }
10243:     } else {
10244:         foreach my $key (keys(%{$current_permissions})) {
10245:             if ($key =~ /\0accesscontrol$/) {
10246:                 if (defined($group)) {
10247:                     if ($key !~ m-^\Q$group\E/-) {
10248:                         next;
10249:                     }
10250:                 }
10251:                 my ($fullpath) = split(/\0/,$key);
10252:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10253:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10254:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10255:                     }
10256:                 }
10257:             }
10258:         }
10259:     }
10260:     return %access;
10261: }
10262: 
10263: sub modify_access_controls {
10264:     my ($file_name,$changes,$domain,$user)=@_;
10265:     my ($outcome,$deloutcome);
10266:     my %store_permissions;
10267:     my %new_values;
10268:     my %new_control;
10269:     my %translation;
10270:     my @deletions = ();
10271:     my $now = time;
10272:     if (exists($$changes{'activate'})) {
10273:         if (ref($$changes{'activate'}) eq 'HASH') {
10274:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10275:             my $numnew = scalar(@newitems);
10276:             for (my $i=0; $i<$numnew; $i++) {
10277:                 my $newkey = $newitems[$i];
10278:                 my $newid = &Apache::loncommon::get_cgi_id();
10279:                 if ($newkey =~ /^\d+:/) { 
10280:                     $newkey =~ s/^(\d+)/$newid/;
10281:                     $translation{$1} = $newid;
10282:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10283:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10284:                     $translation{$1} = $newid;
10285:                 }
10286:                 $new_values{$file_name."\0".$newkey} = 
10287:                                           $$changes{'activate'}{$newitems[$i]};
10288:                 $new_control{$newkey} = $now;
10289:             }
10290:         }
10291:     }
10292:     my %todelete;
10293:     my %changed_items;
10294:     foreach my $action ('delete','update') {
10295:         if (exists($$changes{$action})) {
10296:             if (ref($$changes{$action}) eq 'HASH') {
10297:                 foreach my $key (keys(%{$$changes{$action}})) {
10298:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10299:                     if ($action eq 'delete') { 
10300:                         $todelete{$itemnum} = 1;
10301:                     } else {
10302:                         $changed_items{$itemnum} = $key;
10303:                     }
10304:                 }
10305:             }
10306:         }
10307:     }
10308:     # get lock on access controls for file.
10309:     my $lockhash = {
10310:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10311:                                                        ':'.$env{'user.domain'},
10312:                    }; 
10313:     my $tries = 0;
10314:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10315:    
10316:     while (($gotlock ne 'ok') && $tries < 10) {
10317:         $tries ++;
10318:         sleep(0.1);
10319:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10320:     }
10321:     if ($gotlock eq 'ok') {
10322:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10323:         my ($tmp)=keys(%curr_permissions);
10324:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10325:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10326:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10327:             if (ref($curr_controls) eq 'HASH') {
10328:                 foreach my $control_item (keys(%{$curr_controls})) {
10329:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10330:                     if (defined($todelete{$itemnum})) {
10331:                         push(@deletions,$file_name."\0".$control_item);
10332:                     } else {
10333:                         if (defined($changed_items{$itemnum})) {
10334:                             $new_control{$changed_items{$itemnum}} = $now;
10335:                             push(@deletions,$file_name."\0".$control_item);
10336:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10337:                         } else {
10338:                             $new_control{$control_item} = $$curr_controls{$control_item};
10339:                         }
10340:                     }
10341:                 }
10342:             }
10343:         }
10344:         my ($group);
10345:         if (&is_course($domain,$user)) {
10346:             ($group,my $file) = split(/\//,$file_name,2);
10347:         }
10348:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10349:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10350:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10351:         #  remove lock
10352:         my @del_lock = ($file_name."\0".'locked_access_records');
10353:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10354:         my $sqlresult =
10355:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10356:                                     $group);
10357:     } else {
10358:         $outcome = "error: could not obtain lockfile\n";  
10359:     }
10360:     return ($outcome,$deloutcome,\%new_values,\%translation);
10361: }
10362: 
10363: sub make_public_indefinitely {
10364:     my (@requrl) = @_;
10365:     return &automated_portfile_access('public',\@requrl);
10366: }
10367: 
10368: sub automated_portfile_access {
10369:     my ($accesstype,$addsref,$delsref,$info) = @_;
10370:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10371:         return 'invalid';
10372:     }
10373:     my %urls;
10374:     if (ref($addsref) eq 'ARRAY') {
10375:         foreach my $requrl (@{$addsref}) {
10376:             if (&is_portfolio_url($requrl)) {
10377:                 unless (exists($urls{$requrl})) {
10378:                     $urls{$requrl} = 'add';
10379:                 }
10380:             }
10381:         }
10382:     }
10383:     if (ref($delsref) eq 'ARRAY') {
10384:         foreach my $requrl (@{$delsref}) { 
10385:             if (&is_portfolio_url($requrl)) {
10386:                 unless (exists($urls{$requrl})) {
10387:                     $urls{$requrl} = 'delete'; 
10388:                 }
10389:             }
10390:         }
10391:     }
10392:     unless (keys(%urls)) {
10393:         return 'invalid';
10394:     }
10395:     my $ip;
10396:     if ($accesstype eq 'ip') {
10397:         if (ref($info) eq 'HASH') {
10398:             if ($info->{'ip'} ne '') {
10399:                 $ip = $info->{'ip'};
10400:             }
10401:         }
10402:         if ($ip eq '') {
10403:             return 'invalid';
10404:         }
10405:     }
10406:     my $errors;
10407:     my $now = time;
10408:     my %current_perms;
10409:     foreach my $requrl (sort(keys(%urls))) {
10410:         my $action;
10411:         if ($urls{$requrl} eq 'add') {
10412:             $action = 'activate';
10413:         } else {
10414:             $action = 'none';
10415:         }
10416:         my $aclnum = 0;
10417:         my (undef,$udom,$unum,$file_name,$group) =
10418:             &parse_portfolio_url($requrl);
10419:         unless (exists($current_perms{$unum.':'.$udom})) {
10420:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10421:         }
10422:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10423:                                                    $group,$file_name);
10424:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10425:             my ($num,$scope,$end,$start) = 
10426:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10427:             if ($scope eq $accesstype) {
10428:                 if (($start <= $now) && ($end == 0)) {
10429:                     if ($accesstype eq 'ip') {
10430:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10431:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10432:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10433:                                     if ($urls{$requrl} eq 'add') {
10434:                                         $action = 'none';
10435:                                         last;
10436:                                     } else {
10437:                                         $action = 'delete';
10438:                                         $aclnum = $num;
10439:                                         last;
10440:                                     }
10441:                                 }
10442:                             }
10443:                         }
10444:                     } elsif ($accesstype eq 'public') {
10445:                         if ($urls{$requrl} eq 'add') {
10446:                             $action = 'none';
10447:                             last;
10448:                         } else {
10449:                             $action = 'delete';
10450:                             $aclnum = $num;
10451:                             last;
10452:                         }
10453:                     }
10454:                 } elsif ($accesstype eq 'public') {
10455:                     $action = 'update';
10456:                     $aclnum = $num;
10457:                     last;
10458:                 }
10459:             }
10460:         }
10461:         if ($action eq 'none') {
10462:             next;
10463:         } else {
10464:             my %changes;
10465:             my $newend = 0;
10466:             my $newstart = $now;
10467:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10468:             $changes{$action}{$newkey} = {
10469:                 type => $accesstype,
10470:                 time => {
10471:                     start => $newstart,
10472:                     end   => $newend,
10473:                 },
10474:             };
10475:             if ($accesstype eq 'ip') {
10476:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10477:             }
10478:             my ($outcome,$deloutcome,$new_values,$translation) =
10479:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10480:             unless ($outcome eq 'ok') {
10481:                 $errors .= $outcome.' ';
10482:             }
10483:         }
10484:     }
10485:     if ($errors) {
10486:         $errors =~ s/\s$//;
10487:         return $errors;
10488:     } else {
10489:         return 'ok';
10490:     }
10491: }
10492: 
10493: #------------------------------------------------------Get Marked as Read Only
10494: 
10495: sub get_marked_as_readonly {
10496:     my ($domain,$user,$what,$group) = @_;
10497:     my $current_permissions = &get_portfile_permissions($domain,$user);
10498:     my @readonly_files;
10499:     my $cmp1=$what;
10500:     if (ref($what)) { $cmp1=join('',@{$what}) };
10501:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10502:         if (defined($group)) {
10503:             if ($file_name !~ m-^\Q$group\E/-) {
10504:                 next;
10505:             }
10506:         }
10507:         if (ref($value) eq "ARRAY"){
10508:             foreach my $stored_what (@{$value}) {
10509:                 my $cmp2=$stored_what;
10510:                 if (ref($stored_what) eq 'ARRAY') {
10511:                     $cmp2=join('',@{$stored_what});
10512:                 }
10513:                 if ($cmp1 eq $cmp2) {
10514:                     push(@readonly_files, $file_name);
10515:                     last;
10516:                 } elsif (!defined($what)) {
10517:                     push(@readonly_files, $file_name);
10518:                     last;
10519:                 }
10520:             }
10521:         }
10522:     }
10523:     return @readonly_files;
10524: }
10525: #-----------------------------------------------------------Get Marked as Read Only Hash
10526: 
10527: sub get_marked_as_readonly_hash {
10528:     my ($current_permissions,$group,$what) = @_;
10529:     my %readonly_files;
10530:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10531:         if (defined($group)) {
10532:             if ($file_name !~ m-^\Q$group\E/-) {
10533:                 next;
10534:             }
10535:         }
10536:         if (ref($value) eq "ARRAY"){
10537:             foreach my $stored_what (@{$value}) {
10538:                 if (ref($stored_what) eq 'ARRAY') {
10539:                     foreach my $lock_descriptor(@{$stored_what}) {
10540:                         if ($lock_descriptor eq 'graded') {
10541:                             $readonly_files{$file_name} = 'graded';
10542:                         } elsif ($lock_descriptor eq 'handback') {
10543:                             $readonly_files{$file_name} = 'handback';
10544:                         } else {
10545:                             if (!exists($readonly_files{$file_name})) {
10546:                                 $readonly_files{$file_name} = 'locked';
10547:                             }
10548:                         }
10549:                     }
10550:                 } 
10551:             }
10552:         } 
10553:     }
10554:     return %readonly_files;
10555: }
10556: # ------------------------------------------------------------ Unmark as Read Only
10557: 
10558: sub unmark_as_readonly {
10559:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10560:     # for portfolio submissions, $what contains [$symb,$crsid] 
10561:     my ($domain,$user,$what,$file_name,$group) = @_;
10562:     $file_name = &declutter_portfile($file_name);
10563:     my $symb_crs = $what;
10564:     if (ref($what)) { $symb_crs=join('',@$what); }
10565:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10566:     my ($tmp)=keys(%current_permissions);
10567:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10568:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10569:     foreach my $file (@readonly_files) {
10570: 	my $clean_file = &declutter_portfile($file);
10571: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10572: 	my $current_locks = $current_permissions{$file};
10573:         my @new_locks;
10574:         my @del_keys;
10575:         if (ref($current_locks) eq "ARRAY"){
10576:             foreach my $locker (@{$current_locks}) {
10577:                 my $compare=$locker;
10578:                 if (ref($locker) eq 'ARRAY') {
10579:                     $compare=join('',@{$locker});
10580:                     if ($compare ne $symb_crs) {
10581:                         push(@new_locks, $locker);
10582:                     }
10583:                 }
10584:             }
10585:             if (scalar(@new_locks) > 0) {
10586:                 $current_permissions{$file} = \@new_locks;
10587:             } else {
10588:                 push(@del_keys, $file);
10589:                 &del('file_permissions',\@del_keys, $domain, $user);
10590:                 delete($current_permissions{$file});
10591:             }
10592:         }
10593:     }
10594:     &put('file_permissions',\%current_permissions,$domain,$user);
10595:     return;
10596: }
10597: 
10598: # ------------------------------------------------------------ Directory lister
10599: 
10600: sub dirlist {
10601:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10602:     $uri=~s/^\///;
10603:     $uri=~s/\/$//;
10604:     my ($udom, $uname);
10605:     if ($getuserdir) {
10606:         $udom = $userdomain;
10607:         $uname = $username;
10608:     } else {
10609:         (undef,$udom,$uname)=split(/\//,$uri);
10610:         if(defined($userdomain)) {
10611:             $udom = $userdomain;
10612:         }
10613:         if(defined($username)) {
10614:             $uname = $username;
10615:         }
10616:     }
10617:     my ($dirRoot,$listing,@listing_results);
10618: 
10619:     $dirRoot = $perlvar{'lonDocRoot'};
10620:     if (defined($getpropath)) {
10621:         $dirRoot = &propath($udom,$uname);
10622:         $dirRoot =~ s/\/$//;
10623:     } elsif (defined($getuserdir)) {
10624:         my $subdir=$uname.'__';
10625:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10626:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10627:                    ."/$udom/$subdir/$uname";
10628:     } elsif (defined($alternateRoot)) {
10629:         $dirRoot = $alternateRoot;
10630:     }
10631: 
10632:     if($udom) {
10633:         if($uname) {
10634:             my $uhome = &homeserver($uname,$udom);
10635:             if ($uhome eq 'no_host') {
10636:                 return ([],'no_host');
10637:             }
10638:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10639:                               .$getuserdir.':'.&escape($dirRoot)
10640:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10641:             if ($listing eq 'unknown_cmd') {
10642:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10643:             } else {
10644:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10645:             }
10646:             if ($listing eq 'unknown_cmd') {
10647:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10648:                 @listing_results = split(/:/,$listing);
10649:             } else {
10650:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10651:             }
10652:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10653:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10654:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10655:                 return ([],$listing);
10656:             } else {
10657:                 return (\@listing_results);
10658:             }
10659:         } elsif(!$alternateRoot) {
10660:             my (%allusers,%listerror);
10661: 	    my %servers = &get_servers($udom,'library');
10662:  	    foreach my $tryserver (keys(%servers)) {
10663:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10664:                                   &escape($udom),$tryserver);
10665:                 if ($listing eq 'unknown_cmd') {
10666: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10667: 				      $udom, $tryserver);
10668:                 } else {
10669:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10670:                 }
10671: 		if ($listing eq 'unknown_cmd') {
10672: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10673: 				      $udom, $tryserver);
10674: 		    @listing_results = split(/:/,$listing);
10675: 		} else {
10676: 		    @listing_results =
10677: 			map { &unescape($_); } split(/:/,$listing);
10678: 		}
10679:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10680:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10681:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10682:                     $listerror{$tryserver} = $listing;
10683:                 } else {
10684: 		    foreach my $line (@listing_results) {
10685: 			my ($entry) = split(/&/,$line,2);
10686: 			$allusers{$entry} = 1;
10687: 		    }
10688: 		}
10689:             }
10690:             my @alluserslist=();
10691:             foreach my $user (sort(keys(%allusers))) {
10692:                 push(@alluserslist,$user.'&user');
10693:             }
10694: 
10695:             if (!%listerror) {
10696:                 # no errors
10697:                 return (\@alluserslist);
10698:             } elsif (scalar(keys(%servers)) == 1) {
10699:                 # one library server, one error 
10700:                 my ($key) = keys(%listerror);
10701:                 return (\@alluserslist, $listerror{$key});
10702:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10703:                 # con_lost indicates that we might miss data from at least one
10704:                 # library server
10705:                 return (\@alluserslist, 'con_lost');
10706:             } else {
10707:                 # multiple library servers and no con_lost -> data should be
10708:                 # complete. 
10709:                 return (\@alluserslist);
10710:             }
10711: 
10712:         } else {
10713:             return ([],'missing username');
10714:         }
10715:     } elsif(!defined($getpropath)) {
10716:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10717:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10718:         return (\@all_domains);
10719:     } else {
10720:         return ([],'missing domain');
10721:     }
10722: }
10723: 
10724: # --------------------------------------------- GetFileTimestamp
10725: # This function utilizes dirlist and returns the date stamp for
10726: # when it was last modified.  It will also return an error of -1
10727: # if an error occurs
10728: 
10729: sub GetFileTimestamp {
10730:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10731:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10732:     $studentName   = &LONCAPA::clean_username($studentName);
10733:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10734:                                     undef,$getuserdir);
10735:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10736:         return -1;
10737:     }
10738:     if (ref($fileref) eq 'ARRAY') {
10739:         my @stats = split('&',$fileref->[0]);
10740:         # @stats contains first the filename, then the stat output
10741:         return $stats[10]; # so this is 10 instead of 9.
10742:     } else {
10743:         return -1;
10744:     }
10745: }
10746: 
10747: sub stat_file {
10748:     my ($uri) = @_;
10749:     $uri = &clutter_with_no_wrapper($uri);
10750: 
10751:     my ($udom,$uname,$file);
10752:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10753: 	($udom,$uname,$file) =
10754: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10755: 	$file = 'userfiles/'.$file;
10756:     }
10757:     if ($uri =~ m-^/res/-) {
10758: 	($udom,$uname) = 
10759: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10760: 	$file = $uri;
10761:     }
10762: 
10763:     if (!$udom || !$uname || !$file) {
10764: 	# unable to handle the uri
10765: 	return ();
10766:     }
10767:     my $getpropath;
10768:     if ($file =~ /^userfiles\//) {
10769:         $getpropath = 1;
10770:     }
10771:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10772:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10773:         return ();
10774:     } else {
10775:         if (ref($listref) eq 'ARRAY') {
10776:             my @stats = split('&',$listref->[0]);
10777: 	    shift(@stats); #filename is first
10778: 	    return @stats;
10779:         }
10780:     }
10781:     return ();
10782: }
10783: 
10784: # --------------------------------------------------------- recursedirs
10785: # Recursive function to traverse either a specific user's Authoring Space
10786: # or corresponding Published Resource Space, and populate the hash ref:
10787: # $dirhashref with URLs of all directories, and if $filehashref hash
10788: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10789: # or .rights files in resource space, and .meta, .save, .log, and .bak
10790: # files in Authoring Space.
10791: #
10792: # Inputs:
10793: #
10794: # $is_home - true if current server is home server for user's space
10795: # $context - either: priv, or res respectively for Authoring or Resource Space.
10796: # $docroot - Document root (i.e., /home/httpd/html
10797: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10798: # $relpath - Current path (relative to top level).
10799: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10800: # $filehashref - reference to hash to populate with URLs of files (Optional)
10801: #
10802: # Returns: nothing
10803: #
10804: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10805: #
10806: # Currently used by interface/londocs.pm to create linked select boxes for
10807: # directory and filename to import a Course "Author" resource into a course, and
10808: # also to create linked select boxes for Authoring Space and Directory to choose
10809: # save location for creation of a new "standard" problem from the Course Editor.
10810: #
10811: 
10812: sub recursedirs {
10813:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10814:     return unless (ref($dirhashref) eq 'HASH');
10815:     my $currpath = $docroot.$toppath;
10816:     if ($relpath) {
10817:         $currpath .= "/$relpath";
10818:     }
10819:     my $savefile;
10820:     if (ref($filehashref)) {
10821:         $savefile = 1;
10822:     }
10823:     if ($is_home) {
10824:         if (opendir(my $dirh,$currpath)) {
10825:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10826:                 next if ($item eq '');
10827:                 if (-d "$currpath/$item") {
10828:                     my $newpath;
10829:                     if ($relpath) {
10830:                         $newpath = "$relpath/$item";
10831:                     } else {
10832:                         $newpath = $item;
10833:                     }
10834:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10835:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10836:                 } elsif ($savefile) {
10837:                     if ($context eq 'priv') {
10838:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10839:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10840:                         }
10841:                     } else {
10842:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10843:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10844:                         }
10845:                     }
10846:                 }
10847:             }
10848:             closedir($dirh);
10849:         }
10850:     } else {
10851:         my ($dirlistref,$listerror) =
10852:             &dirlist($toppath.$relpath);
10853:         my @dir_lines;
10854:         my $dirptr=16384;
10855:         if (ref($dirlistref) eq 'ARRAY') {
10856:             foreach my $dir_line (sort
10857:                               {
10858:                                   my ($afile)=split('&',$a,2);
10859:                                   my ($bfile)=split('&',$b,2);
10860:                                   return (lc($afile) cmp lc($bfile));
10861:                               } (@{$dirlistref})) {
10862:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10863:                     split(/\&/,$dir_line,16);
10864:                 $item =~ s/\s+$//;
10865:                 next if (($item =~ /^\.\.?$/) || ($obs));
10866:                 if ($dirptr&$testdir) {
10867:                     my $newpath;
10868:                     if ($relpath) {
10869:                         $newpath = "$relpath/$item";
10870:                     } else {
10871:                         $relpath = '/';
10872:                         $newpath = $item;
10873:                     }
10874:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10875:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10876:                 } elsif ($savefile) {
10877:                     if ($context eq 'priv') {
10878:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10879:                             $filehashref->{$relpath}{$item} = 1;
10880:                         }
10881:                     } else {
10882:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10883:                             $filehashref->{$relpath}{$item} = 1;
10884:                         }
10885:                     }
10886:                 }
10887:             }
10888:         }
10889:     }
10890:     return;
10891: }
10892: 
10893: # -------------------------------------------------------- Value of a Condition
10894: 
10895: # gets the value of a specific preevaluated condition
10896: #    stored in the string  $env{user.state.<cid>}
10897: # or looks up a condition reference in the bighash and if if hasn't
10898: # already been evaluated recurses into docondval to get the value of
10899: # the condition, then memoizing it to 
10900: #   $env{user.state.<cid>.<condition>}
10901: sub directcondval {
10902:     my $number=shift;
10903:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
10904: 	&Apache::lonuserstate::evalstate();
10905:     }
10906:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10907: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10908:     } elsif ($number =~ /^_/) {
10909: 	my $sub_condition;
10910: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10911: 		&GDBM_READER(),0640)) {
10912: 	    $sub_condition=$bighash{'conditions'.$number};
10913: 	    untie(%bighash);
10914: 	}
10915: 	my $value = &docondval($sub_condition);
10916: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
10917: 	return $value;
10918:     }
10919:     if ($env{'user.state.'.$env{'request.course.id'}}) {
10920:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
10921:     } else {
10922:        return 2;
10923:     }
10924: }
10925: 
10926: # get the collection of conditions for this resource
10927: sub condval {
10928:     my $condidx=shift;
10929:     my $allpathcond='';
10930:     foreach my $cond (split(/\|/,$condidx)) {
10931: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10932: 	    $allpathcond.=
10933: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10934: 	}
10935:     }
10936:     $allpathcond=~s/\|$//;
10937:     return &docondval($allpathcond);
10938: }
10939: 
10940: #evaluates an expression of conditions
10941: sub docondval {
10942:     my ($allpathcond) = @_;
10943:     my $result=0;
10944:     if ($env{'request.course.id'}
10945: 	&& defined($allpathcond)) {
10946: 	my $operand='|';
10947: 	my @stack;
10948: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10949: 	    if ($chunk eq '(') {
10950: 		push @stack,($operand,$result);
10951: 	    } elsif ($chunk eq ')') {
10952: 		my $before=pop @stack;
10953: 		if (pop @stack eq '&') {
10954: 		    $result=$result>$before?$before:$result;
10955: 		} else {
10956: 		    $result=$result>$before?$result:$before;
10957: 		}
10958: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
10959: 		$operand=$chunk;
10960: 	    } else {
10961: 		my $new=directcondval($chunk);
10962: 		if ($operand eq '&') {
10963: 		    $result=$result>$new?$new:$result;
10964: 		} else {
10965: 		    $result=$result>$new?$result:$new;
10966: 		}
10967: 	    }
10968: 	}
10969:     }
10970:     return $result;
10971: }
10972: 
10973: # ---------------------------------------------------- Devalidate courseresdata
10974: 
10975: sub devalidatecourseresdata {
10976:     my ($coursenum,$coursedomain)=@_;
10977:     my $hashid=$coursenum.':'.$coursedomain;
10978:     &devalidate_cache_new('courseres',$hashid);
10979: }
10980: 
10981: 
10982: # --------------------------------------------------- Course Resourcedata Query
10983: #
10984: #  Parameters:
10985: #      $coursenum    - Number of the course.
10986: #      $coursedomain - Domain at which the course was created.
10987: #  Returns:
10988: #     A hash of the course parameters along (I think) with timestamps
10989: #     and version info.
10990: 
10991: sub get_courseresdata {
10992:     my ($coursenum,$coursedomain)=@_;
10993:     my $coursehom=&homeserver($coursenum,$coursedomain);
10994:     my $hashid=$coursenum.':'.$coursedomain;
10995:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
10996:     my %dumpreply;
10997:     unless (defined($cached)) {
10998: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
10999: 	$result=\%dumpreply;
11000: 	my ($tmp) = keys(%dumpreply);
11001: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11002: 	    &do_cache_new('courseres',$hashid,$result,600);
11003: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11004: 	    return $tmp;
11005: 	} elsif ($tmp =~ /^(error)/) {
11006: 	    $result=undef;
11007: 	    &do_cache_new('courseres',$hashid,$result,600);
11008: 	}
11009:     }
11010:     return $result;
11011: }
11012: 
11013: sub devalidateuserresdata {
11014:     my ($uname,$udom)=@_;
11015:     my $hashid="$udom:$uname";
11016:     &devalidate_cache_new('userres',$hashid);
11017: }
11018: 
11019: sub get_userresdata {
11020:     my ($uname,$udom)=@_;
11021:     #most student don\'t have any data set, check if there is some data
11022:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11023: 
11024:     my $hashid="$udom:$uname";
11025:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11026:     if (!defined($cached)) {
11027: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11028: 	$result=\%resourcedata;
11029: 	&do_cache_new('userres',$hashid,$result,600);
11030:     }
11031:     my ($tmp)=keys(%$result);
11032:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11033: 	return $result;
11034:     }
11035:     #error 2 occurs when the .db doesn't exist
11036:     if ($tmp!~/error: 2 /) {
11037:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11038: 	    &logthis("<font color=\"blue\">WARNING:".
11039: 		     " Trying to get resource data for ".
11040: 		     $uname." at ".$udom.": ".
11041: 		     $tmp."</font>");
11042:         }
11043:     } elsif ($tmp=~/error: 2 /) {
11044: 	#&EXT_cache_set($udom,$uname);
11045: 	&do_cache_new('userres',$hashid,undef,600);
11046: 	undef($tmp); # not really an error so don't send it back
11047:     }
11048:     return $tmp;
11049: }
11050: #----------------------------------------------- resdata - return resource data
11051: #  Purpose:
11052: #    Return resource data for either users or for a course.
11053: #  Parameters:
11054: #     $name      - Course/user name.
11055: #     $domain    - Name of the domain the user/course is registered on.
11056: #     $type      - Type of thing $name is (must be 'course' or 'user')
11057: #     $mapp      - decluttered URL of enclosing map  
11058: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11059: #     $recurseup - Ref to array of map URLs, starting with map containing
11060: #                  $mapp up through hierarchy of nested maps to top level map.  
11061: #     $courseid  - CourseID (first part of param identifier).
11062: #     $modifier  - Middle part of param identifier.
11063: #     $what      - Last part of param identifier.
11064: #     @which     - Array of names of resources desired.
11065: #  Returns:
11066: #     The value of the first reasource in @which that is found in the
11067: #     resource hash.
11068: #  Exceptional Conditions:
11069: #     If the $type passed in is not valid (not the string 'course' or 
11070: #     'user', an undefined  reference is returned.
11071: #     If none of the resources are found, an undef is returned
11072: sub resdata {
11073:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11074:         $modifier,$what,@which)=@_;
11075:     my $result;
11076:     if ($type eq 'course') {
11077: 	$result=&get_courseresdata($name,$domain);
11078:     } elsif ($type eq 'user') {
11079: 	$result=&get_userresdata($name,$domain);
11080:     }
11081:     if (!ref($result)) { return $result; }    
11082:     foreach my $item (@which) {
11083:         if ($item->[1] eq 'course') {
11084:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11085:                 unless ($$recursed) {
11086:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11087:                     $$recursed = 1;
11088:                 }
11089:                 foreach my $item (@${recurseup}) {
11090:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11091:                     last if (defined($result->{$norecursechk}));
11092:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11093:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11094:                 }
11095:             }
11096:         }
11097:         if (defined($result->{$item->[0]})) {
11098: 	    return [$result->{$item->[0]},$item->[1]];
11099: 	}
11100:     }
11101:     return undef;
11102: }
11103: 
11104: sub get_domain_ltitools {
11105:     my ($cdom) = @_;
11106:     my %ltitools;
11107:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
11108:     if (defined($cached)) {
11109:         if (ref($result) eq 'HASH') {
11110:             %ltitools = %{$result};
11111:         }
11112:     } else {
11113:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
11114:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
11115:             %ltitools = %{$domconfig{'ltitools'}};
11116:             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
11117:             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
11118:                 foreach my $id (keys(%ltitools)) {
11119:                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
11120:                         foreach my $item ('key','secret') {
11121:                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
11122:                         }
11123:                     }
11124:                 }
11125:             }
11126:         }
11127:         my $cachetime = 24*60*60;
11128:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
11129:     }
11130:     return %ltitools;
11131: }
11132: 
11133: sub get_numsuppfiles {
11134:     my ($cnum,$cdom,$ignorecache)=@_;
11135:     my $hashid=$cnum.':'.$cdom;
11136:     my ($suppcount,$cached);
11137:     unless ($ignorecache) {
11138:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11139:     }
11140:     unless (defined($cached)) {
11141:         my $chome=&homeserver($cnum,$cdom);
11142:         unless ($chome eq 'no_host') {
11143:             ($suppcount,my $errors) = (0,0);
11144:             my $suppmap = 'supplemental.sequence';
11145:             ($suppcount,$errors) = 
11146:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11147:         }
11148:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11149:     }
11150:     return $suppcount;
11151: }
11152: 
11153: #
11154: # EXT resource caching routines
11155: #
11156: 
11157: {
11158: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11159: #
11160: # The course for which we cache
11161: my $cachedmapkey='';
11162: # The cached recursive maps for this course
11163: my %cachedmaps=();
11164: # When this was last done
11165: my $cachedmaptime='';
11166: 
11167: sub clear_EXT_cache_status {
11168:     &delenv('cache.EXT.');
11169: }
11170: 
11171: sub EXT_cache_status {
11172:     my ($target_domain,$target_user) = @_;
11173:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11174:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11175:         # We know already the user has no data
11176:         return 1;
11177:     } else {
11178:         return 0;
11179:     }
11180: }
11181: 
11182: sub EXT_cache_set {
11183:     my ($target_domain,$target_user) = @_;
11184:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11185:     #&appenv({$cachename => time});
11186: }
11187: 
11188: # --------------------------------------------------------- Value of a Variable
11189: sub EXT {
11190: 
11191:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11192:     unless ($varname) { return ''; }
11193:     #get real user name/domain, courseid and symb
11194:     my $courseid;
11195:     my $publicuser;
11196:     if ($symbparm) {
11197: 	$symbparm=&get_symb_from_alias($symbparm);
11198:     }
11199:     if (!($uname && $udom)) {
11200:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11201:       if (!$symbparm) {	$symbparm=$cursymb; }
11202:     } else {
11203: 	$courseid=$env{'request.course.id'};
11204:     }
11205:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11206:     my $rest;
11207:     if (defined($therest[0])) {
11208:        $rest=join('.',@therest);
11209:     } else {
11210:        $rest='';
11211:     }
11212: 
11213:     my $qualifierrest=$qualifier;
11214:     if ($rest) { $qualifierrest.='.'.$rest; }
11215:     my $spacequalifierrest=$space;
11216:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11217:     if ($realm eq 'user') {
11218: # --------------------------------------------------------------- user.resource
11219: 	if ($space eq 'resource') {
11220: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11221: 		  || defined($Apache::lonhomework::parsing_a_task))
11222: 		 &&
11223: 		 ($symbparm eq &symbread()) ) {	
11224: 		# if we are in the middle of processing the resource the
11225: 		# get the value we are planning on committing
11226:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11227:                     return $Apache::lonhomework::results{$qualifierrest};
11228:                 } else {
11229:                     return $Apache::lonhomework::history{$qualifierrest};
11230:                 }
11231: 	    } else {
11232: 		my %restored;
11233: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11234: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11235: 		} else {
11236: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11237: 		}
11238: 		return $restored{$qualifierrest};
11239: 	    }
11240: # ----------------------------------------------------------------- user.access
11241:         } elsif ($space eq 'access') {
11242: 	    # FIXME - not supporting calls for a specific user
11243:             return &allowed($qualifier,$rest);
11244: # ------------------------------------------ user.preferences, user.environment
11245:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11246: 	    if (($uname eq $env{'user.name'}) &&
11247: 		($udom eq $env{'user.domain'})) {
11248: 		return $env{join('.',('environment',$qualifierrest))};
11249: 	    } else {
11250: 		my %returnhash;
11251: 		if (!$publicuser) {
11252: 		    %returnhash=&userenvironment($udom,$uname,
11253: 						 $qualifierrest);
11254: 		}
11255: 		return $returnhash{$qualifierrest};
11256: 	    }
11257: # ----------------------------------------------------------------- user.course
11258:         } elsif ($space eq 'course') {
11259: 	    # FIXME - not supporting calls for a specific user
11260:             return $env{join('.',('request.course',$qualifier))};
11261: # ------------------------------------------------------------------- user.role
11262:         } elsif ($space eq 'role') {
11263: 	    # FIXME - not supporting calls for a specific user
11264:             my ($role,$where)=split(/\./,$env{'request.role'});
11265:             if ($qualifier eq 'value') {
11266: 		return $role;
11267:             } elsif ($qualifier eq 'extent') {
11268:                 return $where;
11269:             }
11270: # ----------------------------------------------------------------- user.domain
11271:         } elsif ($space eq 'domain') {
11272:             return $udom;
11273: # ------------------------------------------------------------------- user.name
11274:         } elsif ($space eq 'name') {
11275:             return $uname;
11276: # ---------------------------------------------------- Any other user namespace
11277:         } else {
11278: 	    my %reply;
11279: 	    if (!$publicuser) {
11280: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11281: 	    }
11282: 	    return $reply{$qualifierrest};
11283:         }
11284:     } elsif ($realm eq 'query') {
11285: # ---------------------------------------------- pull stuff out of query string
11286:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11287: 						[$spacequalifierrest]);
11288: 	return $env{'form.'.$spacequalifierrest}; 
11289:    } elsif ($realm eq 'request') {
11290: # ------------------------------------------------------------- request.browser
11291:         if ($space eq 'browser') {
11292:             return $env{'browser.'.$qualifier};
11293: # ------------------------------------------------------------ request.filename
11294:         } else {
11295:             return $env{'request.'.$spacequalifierrest};
11296:         }
11297:     } elsif ($realm eq 'course') {
11298: # ---------------------------------------------------------- course.description
11299:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11300:     } elsif ($realm eq 'resource') {
11301: 
11302: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11303: 	    if (!$symbparm) { $symbparm=&symbread(); }
11304: 	}
11305: 
11306:         if ($qualifier eq '') {
11307: 	    if ($space eq 'title') {
11308: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11309: 	        return &gettitle($symbparm);
11310: 	    }
11311: 	
11312: 	    if ($space eq 'map') {
11313: 	        my ($map) = &decode_symb($symbparm);
11314: 	        return &symbread($map);
11315: 	    }
11316:             if ($space eq 'maptitle') {
11317:                 my ($map) = &decode_symb($symbparm);
11318:                 return &gettitle($map);
11319:             }
11320: 	    if ($space eq 'filename') {
11321: 	        if ($symbparm) {
11322: 		    return &clutter((&decode_symb($symbparm))[2]);
11323: 	        }
11324: 	        return &hreflocation('',$env{'request.filename'});
11325: 	    }
11326: 
11327:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11328:                 if ($space eq 'visibleparts') {
11329:                     my $navmap = Apache::lonnavmaps::navmap->new();
11330:                     my $item;
11331:                     if (ref($navmap)) {
11332:                         my $res = $navmap->getBySymb($symbparm);
11333:                         my $parts = $res->parts();
11334:                         if (ref($parts) eq 'ARRAY') {
11335:                             $item = join(',',@{$parts});
11336:                         }
11337:                         undef($navmap);
11338:                     }
11339:                     return $item;
11340:                 }
11341:             }
11342:         }
11343: 
11344: 	my ($section, $group, @groups, @recurseup, $recursed);
11345: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11346:         if (($courseid eq '') && ($cid)) {
11347:             $courseid = $cid;
11348:         }
11349: 	if (($symbparm && $courseid) && 
11350: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11351: 
11352: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11353: 
11354: # ----------------------------------------------------- Cascading lookup scheme
11355: 	    my $symbp=$symbparm;
11356: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11357: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11358:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11359: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11360: 	    if (($env{'user.name'} eq $uname) &&
11361: 		($env{'user.domain'} eq $udom)) {
11362: 		$section=$env{'request.course.sec'};
11363:                 @groups = split(/:/,$env{'request.course.groups'});  
11364:                 @groups=&sort_course_groups($courseid,@groups); 
11365: 	    } else {
11366: 		if (! defined($usection)) {
11367: 		    $section=&getsection($udom,$uname,$courseid);
11368: 		} else {
11369: 		    $section = $usection;
11370: 		}
11371:                 @groups = &get_users_groups($udom,$uname,$courseid);
11372: 	    }
11373: 
11374: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11375: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11376:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11377: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11378: 
11379: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11380: 	    my $courselevelr=$courseid.'.'.$symbparm;
11381:             $courseleveli=$courseid.'.'.$recurseparm;
11382: 	    $courselevelm=$courseid.'.'.$mapparm;
11383: 
11384: # ----------------------------------------------------------- first, check user
11385: 
11386: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11387:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11388: 				       ([$courselevelr,'resource'],
11389: 					[$courselevelm,'map'     ],
11390:                                         [$courseleveli,'map'     ],
11391: 					[$courselevel, 'course'  ]));
11392: 	    if (defined($userreply)) { return &get_reply($userreply); }
11393: 
11394: # ------------------------------------------------ second, check some of course
11395:             my $coursereply;
11396:             if (@groups > 0) {
11397:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11398:                                        $recurseparm,$mapparm,$spacequalifierrest,
11399:                                        $mapp,\$recursed,\@recurseup);
11400:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11401:             }
11402: 
11403: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11404: 				  $env{'course.'.$courseid.'.domain'},
11405: 				  'course',$mapp,\$recursed,\@recurseup,
11406:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11407: 				  ([$seclevelr,   'resource'],
11408: 				   [$seclevelm,   'map'     ],
11409:                                    [$secleveli,   'map'     ],
11410: 				   [$seclevel,    'course'  ],
11411: 				   [$courselevelr,'resource']));
11412: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11413: 
11414: # ------------------------------------------------------ third, check map parms
11415: 	    my %parmhash=();
11416: 	    my $thisparm='';
11417: 	    if (tie(%parmhash,'GDBM_File',
11418: 		    $env{'request.course.fn'}.'_parms.db',
11419: 		    &GDBM_READER(),0640)) {
11420: 		$thisparm=$parmhash{$symbparm};
11421: 		untie(%parmhash);
11422: 	    }
11423: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11424: 	}
11425: # ------------------------------------------ fourth, look in resource metadata
11426:  
11427:         my $what = $spacequalifierrest;
11428: 	$what=~s/\./\_/;
11429: 	my $filename;
11430: 	if (!$symbparm) { $symbparm=&symbread(); }
11431: 	if ($symbparm) {
11432: 	    $filename=(&decode_symb($symbparm))[2];
11433: 	} else {
11434: 	    $filename=$env{'request.filename'};
11435: 	}
11436: 	my $metadata=&metadata($filename,$what);
11437: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11438: 	$metadata=&metadata($filename,'parameter_'.$what);
11439: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11440: 
11441: # ----------------------------------------------- fifth, look in rest of course
11442: 	if ($symbparm && defined($courseid) && 
11443: 	    $courseid eq $env{'request.course.id'}) {
11444: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11445: 				     $env{'course.'.$courseid.'.domain'},
11446: 				     'course',$mapp,\$recursed,\@recurseup,
11447:                                      $courseid,'.',$spacequalifierrest,
11448: 				     ([$courselevelm,'map'   ],
11449:                                       [$courseleveli,'map'   ],
11450: 				      [$courselevel, 'course']));
11451: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11452: 	}
11453: # ------------------------------------------------------------------ Cascade up
11454: 	unless ($space eq '0') {
11455: 	    my @parts=split(/_/,$space);
11456: 	    my $id=pop(@parts);
11457: 	    my $part=join('_',@parts);
11458: 	    if ($part eq '') { $part='0'; }
11459: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11460: 				 $symbparm,$udom,$uname,$section,1);
11461: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11462: 	}
11463: 	if ($recurse) { return undef; }
11464: 	my $pack_def=&packages_tab_default($filename,$varname);
11465: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11466: # ---------------------------------------------------- Any other user namespace
11467:     } elsif ($realm eq 'environment') {
11468: # ----------------------------------------------------------------- environment
11469: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11470: 	    return $env{'environment.'.$spacequalifierrest};
11471: 	} else {
11472: 	    if ($uname eq 'anonymous' && $udom eq '') {
11473: 		return '';
11474: 	    }
11475: 	    my %returnhash=&userenvironment($udom,$uname,
11476: 					    $spacequalifierrest);
11477: 	    return $returnhash{$spacequalifierrest};
11478: 	}
11479:     } elsif ($realm eq 'system') {
11480: # ----------------------------------------------------------------- system.time
11481: 	if ($space eq 'time') {
11482: 	    return time;
11483:         }
11484:     } elsif ($realm eq 'server') {
11485: # ----------------------------------------------------------------- system.time
11486: 	if ($space eq 'name') {
11487: 	    return $ENV{'SERVER_NAME'};
11488:         }
11489:     }
11490:     return '';
11491: }
11492: 
11493: sub get_reply {
11494:     my ($reply_value) = @_;
11495:     if (ref($reply_value) eq 'ARRAY') {
11496:         if (wantarray) {
11497: 	    return @$reply_value;
11498:         }
11499:         return $reply_value->[0];
11500:     } else {
11501:         return $reply_value;
11502:     }
11503: }
11504: 
11505: sub check_group_parms {
11506:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11507:         $recursed,$recurseupref) = @_;
11508:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11509:                   [$what,'course']);
11510:     my $coursereply;
11511:     foreach my $group (@{$groups}) {
11512:         my @groupitems = ();
11513:         foreach my $level (@levels) {
11514:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11515:              push(@groupitems,[$item,$level->[1]]);
11516:         }
11517:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11518:                                    $env{'course.'.$courseid.'.domain'},
11519:                                    'course',$mapp,$recursed,$recurseupref,
11520:                                    $courseid,'.['.$group.'].',$what,
11521:                                    @groupitems);
11522:         last if (defined($coursereply));
11523:     }
11524:     return $coursereply;
11525: }
11526: 
11527: sub get_map_hierarchy {
11528:     my ($mapname,$courseid) = @_;
11529:     my @recurseup = ();
11530:     if ($mapname) {
11531:         if (($cachedmapkey eq $courseid) &&
11532:             (abs($cachedmaptime-time)<5)) {
11533:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11534:                 return @{$cachedmaps{$mapname}};
11535:             }
11536:         }
11537:         my $navmap = Apache::lonnavmaps::navmap->new();
11538:         if (ref($navmap)) {
11539:             @recurseup = $navmap->recurseup_maps($mapname);
11540:             undef($navmap);
11541:             $cachedmaps{$mapname} = \@recurseup;
11542:             $cachedmaptime=time;
11543:             $cachedmapkey=$courseid;
11544:         }
11545:     }
11546:     return @recurseup;
11547: }
11548: 
11549: }
11550: 
11551: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11552:     my ($courseid,@groups) = @_;
11553:     @groups = sort(@groups);
11554:     return @groups;
11555: }
11556: 
11557: sub packages_tab_default {
11558:     my ($uri,$varname)=@_;
11559:     my (undef,$part,$name)=split(/\./,$varname);
11560: 
11561:     my (@extension,@specifics,$do_default);
11562:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11563: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11564: 	if ($pack_type eq 'default') {
11565: 	    $do_default=1;
11566: 	} elsif ($pack_type eq 'extension') {
11567: 	    push(@extension,[$package,$pack_type,$pack_part]);
11568: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11569: 	    # only look at packages defaults for packages that this id is
11570: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11571: 	}
11572:     }
11573:     # first look for a package that matches the requested part id
11574:     foreach my $package (@specifics) {
11575: 	my (undef,$pack_type,$pack_part)=@{$package};
11576: 	next if ($pack_part ne $part);
11577: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11578: 	    return $packagetab{"$pack_type&$name&default"};
11579: 	}
11580:     }
11581:     # look for any possible matching non extension_ package
11582:     foreach my $package (@specifics) {
11583: 	my (undef,$pack_type,$pack_part)=@{$package};
11584: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11585: 	    return $packagetab{"$pack_type&$name&default"};
11586: 	}
11587: 	if ($pack_type eq 'part') { $pack_part='0'; }
11588: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11589: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11590: 	}
11591:     }
11592:     # look for any posible extension_ match
11593:     foreach my $package (@extension) {
11594: 	my ($package,$pack_type)=@{$package};
11595: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11596: 	    return $packagetab{"$pack_type&$name&default"};
11597: 	}
11598: 	if (defined($packagetab{$package."&$name&default"})) {
11599: 	    return $packagetab{$package."&$name&default"};
11600: 	}
11601:     }
11602:     # look for a global default setting
11603:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11604: 	return $packagetab{"default&$name&default"};
11605:     }
11606:     return undef;
11607: }
11608: 
11609: sub add_prefix_and_part {
11610:     my ($prefix,$part)=@_;
11611:     my $keyroot;
11612:     if (defined($prefix) && $prefix !~ /^__/) {
11613: 	# prefix that has a part already
11614: 	$keyroot=$prefix;
11615:     } elsif (defined($prefix)) {
11616: 	# prefix that is missing a part
11617: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11618:     } else {
11619: 	# no prefix at all
11620: 	if (defined($part)) { $keyroot='_'.$part; }
11621:     }
11622:     return $keyroot;
11623: }
11624: 
11625: # ---------------------------------------------------------------- Get metadata
11626: 
11627: my %metaentry;
11628: my %importedpartids;
11629: sub metadata {
11630:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11631:     $uri=&declutter($uri);
11632:     # if it is a non metadata possible uri return quickly
11633:     if (($uri eq '') || 
11634: 	(($uri =~ m|^/*adm/|) && 
11635: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11636:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11637: 	return undef;
11638:     }
11639:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11640: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11641: 	return undef;
11642:     }
11643:     my $filename=$uri;
11644:     $uri=~s/\.meta$//;
11645: #
11646: # Is the metadata already cached?
11647: # Look at timestamp of caching
11648: # Everything is cached by the main uri, libraries are never directly cached
11649: #
11650:     if (!defined($liburi)) {
11651: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11652: 	if (defined($cached)) { return $result->{':'.$what}; }
11653:     }
11654:     {
11655: # Imported parts would go here
11656:         my %importedids=();
11657:         my @origfileimportpartids=();
11658:         my $importedparts=0;
11659: #
11660: # Is this a recursive call for a library?
11661: #
11662: #	if (! exists($metacache{$uri})) {
11663: #	    $metacache{$uri}={};
11664: #	}
11665: 	my $cachetime = 60*60;
11666:         if ($liburi) {
11667: 	    $liburi=&declutter($liburi);
11668:             $filename=$liburi;
11669:         } else {
11670: 	    &devalidate_cache_new('meta',$uri);
11671: 	    undef(%metaentry);
11672: 	}
11673:         my %metathesekeys=();
11674:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11675: 	my $metastring;
11676: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11677: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11678: 	    $metastring = 
11679: 		&Apache::lonnet::ssi_body($which,
11680: 					  ('grade_target' => 'meta'));
11681: 	    $cachetime = 1; # only want this cached in the child not long term
11682: 	} elsif (($uri !~ m -^(editupload)/-) && 
11683:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11684: 	    my $file=&filelocation('',&clutter($filename));
11685: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11686: 	    $metastring=&getfile($file);
11687: 	}
11688:         my $parser=HTML::LCParser->new(\$metastring);
11689:         my $token;
11690:         undef %metathesekeys;
11691:         while ($token=$parser->get_token) {
11692: 	    if ($token->[0] eq 'S') {
11693: 		if (defined($token->[2]->{'package'})) {
11694: #
11695: # This is a package - get package info
11696: #
11697: 		    my $package=$token->[2]->{'package'};
11698: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11699: 		    if (defined($token->[2]->{'id'})) { 
11700: 			$keyroot.='_'.$token->[2]->{'id'}; 
11701: 		    }
11702: 		    if ($metaentry{':packages'}) {
11703: 			$metaentry{':packages'}.=','.$package.$keyroot;
11704: 		    } else {
11705: 			$metaentry{':packages'}=$package.$keyroot;
11706: 		    }
11707: 		    foreach my $pack_entry (keys(%packagetab)) {
11708: 			my $part=$keyroot;
11709: 			$part=~s/^\_//;
11710: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11711: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11712: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11713: 			    # ignore package.tab specified default values
11714:                             # here &package_tab_default() will fetch those
11715: 			    if ($subp eq 'default') { next; }
11716: 			    my $value=$packagetab{$pack_entry};
11717: 			    my $unikey;
11718: 			    if ($pack =~ /_0$/) {
11719: 				$unikey='parameter_0_'.$name;
11720: 				$part=0;
11721: 			    } else {
11722: 				$unikey='parameter'.$keyroot.'_'.$name;
11723: 			    }
11724: 			    if ($subp eq 'display') {
11725: 				$value.=' [Part: '.$part.']';
11726: 			    }
11727: 			    $metaentry{':'.$unikey.'.part'}=$part;
11728: 			    $metathesekeys{$unikey}=1;
11729: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11730: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11731: 			    }
11732: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11733: 				$metaentry{':'.$unikey}=
11734: 				    $metaentry{':'.$unikey.'.default'};
11735: 			    }
11736: 			}
11737: 		    }
11738: 		} else {
11739: #
11740: # This is not a package - some other kind of start tag
11741: #
11742: 		    my $entry=$token->[1];
11743: 		    my $unikey='';
11744: 
11745: 		    if ($entry eq 'import') {
11746: #
11747: # Importing a library here
11748: #
11749:                         my $location=$parser->get_text('/import');
11750:                         my $dir=$filename;
11751:                         $dir=~s|[^/]*$||;
11752:                         $location=&filelocation($dir,$location);
11753:                        
11754:                         my $importmode=$token->[2]->{'importmode'};
11755:                         if ($importmode eq 'problem') {
11756: # Import as problem/response
11757:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11758:                         } elsif ($importmode eq 'part') {
11759: # Import as part(s)
11760:                            $importedparts=1;
11761: # We need to get the original file and the imported file to get the part order correct
11762: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11763: # Load and inspect original file
11764:                            if ($#origfileimportpartids<0) {
11765:                               undef(%importedpartids);
11766:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11767:                               my $origfile=&getfile($origfilelocation);
11768:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11769:                            }
11770: 
11771: # Load and inspect imported file
11772:                            my $impfile=&getfile($location);
11773:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11774:                            if ($#impfilepartids>=0) {
11775: # This problem had parts
11776:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11777:                            } else {
11778: # Importing by turning a single problem into a problem part
11779: # It gets the import-tags ID as part-ID
11780:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11781:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11782:                            }
11783:                         } else {
11784: # Normal import
11785:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11786:                            if (defined($token->[2]->{'id'})) {
11787:                               $unikey.='_'.$token->[2]->{'id'};
11788:                            }
11789:                         }
11790: 
11791: 			if ($depthcount<20) {
11792: 			    my $metadata = 
11793: 				&metadata($uri,'keys', $location,$unikey,
11794: 					  $depthcount+1);
11795: 			    foreach my $meta (split(',',$metadata)) {
11796: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
11797: 				$metathesekeys{$meta}=1;
11798: 			    }
11799: 			
11800:                         }
11801: 		    } else {
11802: #
11803: # Not importing, some other kind of non-package, non-library start tag
11804: # 
11805:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11806:                         if (defined($token->[2]->{'id'})) {
11807:                             $unikey.='_'.$token->[2]->{'id'};
11808:                         }
11809: 			if (defined($token->[2]->{'name'})) { 
11810: 			    $unikey.='_'.$token->[2]->{'name'}; 
11811: 			}
11812: 			$metathesekeys{$unikey}=1;
11813: 			foreach my $param (@{$token->[3]}) {
11814: 			    $metaentry{':'.$unikey.'.'.$param} =
11815: 				$token->[2]->{$param};
11816: 			}
11817: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
11818: 			my $default=$metaentry{':'.$unikey.'.default'};
11819: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11820: 		 # only ws inside the tag, and not in default, so use default
11821: 		 # as value
11822: 			    $metaentry{':'.$unikey}=$default;
11823: 			} elsif ( $internaltext =~ /\S/ ) {
11824: 		  # something interesting inside the tag
11825: 			    $metaentry{':'.$unikey}=$internaltext;
11826: 			} else {
11827: 		  # no interesting values, don't set a default
11828: 			}
11829: # end of not-a-package not-a-library import
11830: 		    }
11831: # end of not-a-package start tag
11832: 		}
11833: # the next is the end of "start tag"
11834: 	    }
11835: 	}
11836: 	my ($extension) = ($uri =~ /\.(\w+)$/);
11837: 	$extension = lc($extension);
11838: 	if ($extension eq 'htm') { $extension='html'; }
11839: 
11840: 	foreach my $key (keys(%packagetab)) {
11841: 	    #no specific packages #how's our extension
11842: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
11843: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
11844: 					 \%metathesekeys);
11845: 	}
11846: 
11847: 	if (!exists($metaentry{':packages'})
11848: 	    || $packagetab{"import_defaults&extension_$extension"}) {
11849: 	    foreach my $key (keys(%packagetab)) {
11850: 		#no specific packages well let's get default then
11851: 		if ($key!~/^default&/) { next; }
11852: 		&metadata_create_package_def($uri,$key,'default',
11853: 					     \%metathesekeys);
11854: 	    }
11855: 	}
11856: # are there custom rights to evaluate
11857: 	if ($metaentry{':copyright'} eq 'custom') {
11858: 
11859:     #
11860:     # Importing a rights file here
11861:     #
11862: 	    unless ($depthcount) {
11863: 		my $location=$metaentry{':customdistributionfile'};
11864: 		my $dir=$filename;
11865: 		$dir=~s|[^/]*$||;
11866: 		$location=&filelocation($dir,$location);
11867: 		my $rights_metadata =
11868: 		    &metadata($uri,'keys',$location,'_rights',
11869: 			      $depthcount+1);
11870: 		foreach my $rights (split(',',$rights_metadata)) {
11871: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11872: 		    $metathesekeys{$rights}=1;
11873: 		}
11874: 	    }
11875: 	}
11876: 	# uniqifiy package listing
11877: 	my %seen;
11878: 	my @uniq_packages =
11879: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11880: 	$metaentry{':packages'} = join(',',@uniq_packages);
11881: 
11882:         if ($importedparts) {
11883: # We had imported parts and need to rebuild partorder
11884:            $metaentry{':partorder'}='';
11885:            $metathesekeys{'partorder'}=1;
11886:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11887:                if ($origfileimportpartids[$index] eq 'part') {
11888: # original part, part of the problem
11889:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11890:                } else {
11891: # we have imported parts at this position
11892:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11893:                }
11894:            }
11895:            $metaentry{':partorder'}=~s/^\,//;
11896:         }
11897: 
11898: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
11899: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
11900: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
11901: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
11902: # this is the end of "was not already recently cached
11903:     }
11904:     return $metaentry{':'.$what};
11905: }
11906: 
11907: sub metadata_create_package_def {
11908:     my ($uri,$key,$package,$metathesekeys)=@_;
11909:     my ($pack,$name,$subp)=split(/\&/,$key);
11910:     if ($subp eq 'default') { next; }
11911:     
11912:     if (defined($metaentry{':packages'})) {
11913: 	$metaentry{':packages'}.=','.$package;
11914:     } else {
11915: 	$metaentry{':packages'}=$package;
11916:     }
11917:     my $value=$packagetab{$key};
11918:     my $unikey;
11919:     $unikey='parameter_0_'.$name;
11920:     $metaentry{':'.$unikey.'.part'}=0;
11921:     $$metathesekeys{$unikey}=1;
11922:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11923: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
11924:     }
11925:     if (defined($metaentry{':'.$unikey.'.default'})) {
11926: 	$metaentry{':'.$unikey}=
11927: 	    $metaentry{':'.$unikey.'.default'};
11928:     }
11929: }
11930: 
11931: sub metadata_generate_part0 {
11932:     my ($metadata,$metacache,$uri) = @_;
11933:     my %allnames;
11934:     foreach my $metakey (keys(%$metadata)) {
11935: 	if ($metakey=~/^parameter\_(.*)/) {
11936: 	  my $part=$$metacache{':'.$metakey.'.part'};
11937: 	  my $name=$$metacache{':'.$metakey.'.name'};
11938: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
11939: 	    $allnames{$name}=$part;
11940: 	  }
11941: 	}
11942:     }
11943:     foreach my $name (keys(%allnames)) {
11944:       $$metadata{"parameter_0_$name"}=1;
11945:       my $key=":parameter_0_$name";
11946:       $$metacache{"$key.part"}='0';
11947:       $$metacache{"$key.name"}=$name;
11948:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
11949: 					   $allnames{$name}.'_'.$name.
11950: 					   '.type'};
11951:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
11952: 			     '.display'};
11953:       my $expr='[Part: '.$allnames{$name}.']';
11954:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
11955:       $$metacache{"$key.display"}=$olddis;
11956:     }
11957: }
11958: 
11959: # ------------------------------------------------------ Devalidate title cache
11960: 
11961: sub devalidate_title_cache {
11962:     my ($url)=@_;
11963:     if (!$env{'request.course.id'}) { return; }
11964:     my $symb=&symbread($url);
11965:     if (!$symb) { return; }
11966:     my $key=$env{'request.course.id'}."\0".$symb;
11967:     &devalidate_cache_new('title',$key);
11968: }
11969: 
11970: # ------------------------------------------------- Get the title of a course
11971: 
11972: sub current_course_title {
11973:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11974: }
11975: # ------------------------------------------------- Get the title of a resource
11976: 
11977: sub gettitle {
11978:     my $urlsymb=shift;
11979:     my $symb=&symbread($urlsymb);
11980:     if ($symb) {
11981: 	my $key=$env{'request.course.id'}."\0".$symb;
11982: 	my ($result,$cached)=&is_cached_new('title',$key);
11983: 	if (defined($cached)) { 
11984: 	    return $result;
11985: 	}
11986: 	my ($map,$resid,$url)=&decode_symb($symb);
11987: 	my $title='';
11988: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11989: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11990: 	} else {
11991: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11992: 		    &GDBM_READER(),0640)) {
11993: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
11994: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
11995: 		untie(%bighash);
11996: 	    }
11997: 	}
11998: 	$title=~s/\&colon\;/\:/gs;
11999: 	if ($title) {
12000: # Remember both $symb and $title for dynamic metadata
12001:             $accesshash{$symb.'___crstitle'}=$title;
12002:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12003: # Cache this title and then return it
12004: 	    return &do_cache_new('title',$key,$title,600);
12005: 	}
12006: 	$urlsymb=$url;
12007:     }
12008:     my $title=&metadata($urlsymb,'title');
12009:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12010:     return $title;
12011: }
12012: 
12013: sub get_slot {
12014:     my ($which,$cnum,$cdom)=@_;
12015:     if (!$cnum || !$cdom) {
12016: 	(undef,my $courseid)=&whichuser();
12017: 	$cdom=$env{'course.'.$courseid.'.domain'};
12018: 	$cnum=$env{'course.'.$courseid.'.num'};
12019:     }
12020:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12021:     my %slotinfo;
12022:     if (exists($remembered{$key})) {
12023: 	$slotinfo{$which} = $remembered{$key};
12024:     } else {
12025: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12026: 	&Apache::lonhomework::showhash(%slotinfo);
12027: 	my ($tmp)=keys(%slotinfo);
12028: 	if ($tmp=~/^error:/) { return (); }
12029: 	$remembered{$key} = $slotinfo{$which};
12030:     }
12031:     if (ref($slotinfo{$which}) eq 'HASH') {
12032: 	return %{$slotinfo{$which}};
12033:     }
12034:     return $slotinfo{$which};
12035: }
12036: 
12037: sub get_reservable_slots {
12038:     my ($cnum,$cdom,$uname,$udom) = @_;
12039:     my $now = time;
12040:     my $reservable_info;
12041:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12042:     if (exists($remembered{$key})) {
12043:         $reservable_info = $remembered{$key};
12044:     } else {
12045:         my %resv;
12046:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12047:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12048:         $reservable_info = \%resv;
12049:         $remembered{$key} = $reservable_info;
12050:     }
12051:     return $reservable_info;
12052: }
12053: 
12054: sub get_course_slots {
12055:     my ($cnum,$cdom) = @_;
12056:     my $hashid=$cnum.':'.$cdom;
12057:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12058:     if (defined($cached)) {
12059:         if (ref($result) eq 'HASH') {
12060:             return %{$result};
12061:         }
12062:     } else {
12063:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12064:         my ($tmp) = keys(%slots);
12065:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12066:             &do_cache_new('allslots',$hashid,\%slots,600);
12067:             return %slots;
12068:         }
12069:     }
12070:     return;
12071: }
12072: 
12073: sub devalidate_slots_cache {
12074:     my ($cnum,$cdom)=@_;
12075:     my $hashid=$cnum.':'.$cdom;
12076:     &devalidate_cache_new('allslots',$hashid);
12077: }
12078: 
12079: sub get_coursechange {
12080:     my ($cdom,$cnum) = @_;
12081:     if ($cdom eq '' || $cnum eq '') {
12082:         return unless ($env{'request.course.id'});
12083:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12084:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12085:     }
12086:     my $hashid=$cdom.'_'.$cnum;
12087:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12088:     if ((defined($cached)) && ($change ne '')) {
12089:         return $change;
12090:     } else {
12091:         my %crshash;
12092:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12093:         if ($crshash{'internal.contentchange'} eq '') {
12094:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12095:             if ($change eq '') {
12096:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12097:                 $change = $crshash{'internal.created'};
12098:             }
12099:         } else {
12100:             $change = $crshash{'internal.contentchange'};
12101:         }
12102:         my $cachetime = 600;
12103:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12104:     }
12105:     return $change;
12106: }
12107: 
12108: sub devalidate_coursechange_cache {
12109:     my ($cnum,$cdom)=@_;
12110:     my $hashid=$cnum.':'.$cdom;
12111:     &devalidate_cache_new('crschange',$hashid);
12112: }
12113: 
12114: # ------------------------------------------------- Update symbolic store links
12115: 
12116: sub symblist {
12117:     my ($mapname,%newhash)=@_;
12118:     $mapname=&deversion(&declutter($mapname));
12119:     my %hash;
12120:     if (($env{'request.course.fn'}) && (%newhash)) {
12121:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12122:                       &GDBM_WRCREAT(),0640)) {
12123: 	    foreach my $url (keys(%newhash)) {
12124: 		next if ($url eq 'last_known'
12125: 			 && $env{'form.no_update_last_known'});
12126: 		$hash{declutter($url)}=&encode_symb($mapname,
12127: 						    $newhash{$url}->[1],
12128: 						    $newhash{$url}->[0]);
12129:             }
12130:             if (untie(%hash)) {
12131: 		return 'ok';
12132:             }
12133:         }
12134:     }
12135:     return 'error';
12136: }
12137: 
12138: # --------------------------------------------------------------- Verify a symb
12139: 
12140: sub symbverify {
12141:     my ($symb,$thisurl,$encstate)=@_;
12142:     my $thisfn=$thisurl;
12143:     $thisfn=&declutter($thisfn);
12144: # direct jump to resource in page or to a sequence - will construct own symbs
12145:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12146: # check URL part
12147:     my ($map,$resid,$url)=&decode_symb($symb);
12148: 
12149:     unless ($url eq $thisfn) { return 0; }
12150: 
12151:     $symb=&symbclean($symb);
12152:     $thisurl=&deversion($thisurl);
12153:     $thisfn=&deversion($thisfn);
12154: 
12155:     my %bighash;
12156:     my $okay=0;
12157: 
12158:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12159:                             &GDBM_READER(),0640)) {
12160:         my $noclutter;
12161:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12162:             $thisurl =~ s/\?.+$//;
12163:             if ($map =~ m{^uploaded/.+\.page$}) {
12164:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12165:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12166:                 $noclutter = 1;
12167:             }
12168:         }
12169:         my $ids;
12170:         if ($noclutter) {
12171:             $ids=$bighash{'ids_'.$thisurl};
12172:         } else {
12173:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12174:         }
12175:         unless ($ids) {
12176:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12177:             $ids=$bighash{$idkey};
12178:         }
12179:         if ($ids) {
12180: # ------------------------------------------------------------------- Has ID(s)
12181:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12182:                 $symb =~ s/\?.+$//;
12183:             }
12184: 	    foreach my $id (split(/\,/,$ids)) {
12185: 	       my ($mapid,$resid)=split(/\./,$id);
12186:                if (
12187:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12188:    eq $symb) {
12189:                    if (ref($encstate)) {
12190:                        $$encstate = $bighash{'encrypted_'.$id};
12191:                    }
12192: 		   if (($env{'request.role.adv'}) ||
12193: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12194:                        ($thisurl eq '/adm/navmaps')) {
12195: 		       $okay=1;
12196:                        last;
12197: 		   }
12198: 	       }
12199: 	   }
12200:         }
12201: 	untie(%bighash);
12202:     }
12203:     return $okay;
12204: }
12205: 
12206: # --------------------------------------------------------------- Clean-up symb
12207: 
12208: sub symbclean {
12209:     my $symb=shift;
12210:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12211: # remove version from map
12212:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12213: 
12214: # remove version from URL
12215:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12216: 
12217: # remove wrapper
12218: 
12219:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12220:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12221:     return $symb;
12222: }
12223: 
12224: # ---------------------------------------------- Split symb to find map and url
12225: 
12226: sub encode_symb {
12227:     my ($map,$resid,$url)=@_;
12228:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12229: }
12230: 
12231: sub decode_symb {
12232:     my $symb=shift;
12233:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12234:     my ($map,$resid,$url)=split(/___/,$symb);
12235:     return (&fixversion($map),$resid,&fixversion($url));
12236: }
12237: 
12238: sub fixversion {
12239:     my $fn=shift;
12240:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12241:     my %bighash;
12242:     my $uri=&clutter($fn);
12243:     my $key=$env{'request.course.id'}.'_'.$uri;
12244: # is this cached?
12245:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12246:     if (defined($cached)) { return $result; }
12247: # unfortunately not cached, or expired
12248:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12249: 	    &GDBM_READER(),0640)) {
12250:  	if ($bighash{'version_'.$uri}) {
12251:  	    my $version=$bighash{'version_'.$uri};
12252:  	    unless (($version eq 'mostrecent') || 
12253: 		    ($version==&getversion($uri))) {
12254:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12255:  	    }
12256:  	}
12257:  	untie %bighash;
12258:     }
12259:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12260: }
12261: 
12262: sub deversion {
12263:     my $url=shift;
12264:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12265:     return $url;
12266: }
12267: 
12268: # ------------------------------------------------------ Return symb list entry
12269: 
12270: sub symbread {
12271:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12272:     my $cache_str='request.symbread.cached.'.$thisfn;
12273:     if (defined($env{$cache_str})) {
12274:         if ($ignorecachednull) {
12275:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12276:         } else {
12277:             return $env{$cache_str};
12278:         }
12279:     }
12280: # no filename provided? try from environment
12281:     unless ($thisfn) {
12282:         if ($env{'request.symb'}) {
12283: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12284: 	}
12285: 	$thisfn=$env{'request.filename'};
12286:     }
12287:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12288: # is that filename actually a symb? Verify, clean, and return
12289:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12290: 	if (&symbverify($thisfn,$1)) {
12291: 	    return $env{$cache_str}=&symbclean($thisfn);
12292: 	}
12293:     }
12294:     $thisfn=declutter($thisfn);
12295:     my %hash;
12296:     my %bighash;
12297:     my $syval='';
12298:     if (($env{'request.course.fn'}) && ($thisfn)) {
12299:         my $targetfn = $thisfn;
12300:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12301:             $targetfn = 'adm/wrapper/'.$thisfn;
12302:         }
12303: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12304: 	    $targetfn=$1;
12305: 	}
12306:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12307:                       &GDBM_READER(),0640)) {
12308: 	    $syval=$hash{$targetfn};
12309:             untie(%hash);
12310:         }
12311: # ---------------------------------------------------------- There was an entry
12312:         if ($syval) {
12313: 	    #unless ($syval=~/\_\d+$/) {
12314: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12315: 		    #&appenv({'request.ambiguous' => $thisfn});
12316: 		    #return $env{$cache_str}='';
12317: 		#}    
12318: 		#$syval.=$1;
12319: 	    #}
12320:         } else {
12321: # ------------------------------------------------------- Was not in symb table
12322:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12323:                             &GDBM_READER(),0640)) {
12324: # ---------------------------------------------- Get ID(s) for current resource
12325:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12326:               unless ($ids) { 
12327:                  $ids=$bighash{'ids_/'.$thisfn};
12328:               }
12329:               unless ($ids) {
12330: # alias?
12331: 		  $ids=$bighash{'mapalias_'.$thisfn};
12332:               }
12333:               if ($ids) {
12334: # ------------------------------------------------------------------- Has ID(s)
12335:                  my @possibilities=split(/\,/,$ids);
12336:                  if ($#possibilities==0) {
12337: # ----------------------------------------------- There is only one possibility
12338: 		     my ($mapid,$resid)=split(/\./,$ids);
12339: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12340: 						    $resid,$thisfn);
12341:                      if (ref($possibles) eq 'HASH') {
12342:                          $possibles->{$syval} = 1;    
12343:                      }
12344:                      if ($checkforblock) {
12345:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12346:                          if (@blockers) {
12347:                              $syval = '';
12348:                              return;
12349:                          }
12350:                      }
12351:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12352: # ------------------------------------------ There is more than one possibility
12353:                      my $realpossible=0;
12354:                      foreach my $id (@possibilities) {
12355: 			 my $file=$bighash{'src_'.$id};
12356:                          my $canaccess;
12357:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12358:                              $canaccess = 1;
12359:                          } else { 
12360:                              $canaccess = &allowed('bre',$file);
12361:                          }
12362:                          if ($canaccess) {
12363:          		     my ($mapid,$resid)=split(/\./,$id);
12364:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12365:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12366: 						             $resid,$thisfn);
12367:                                  if (ref($possibles) eq 'HASH') {
12368:                                      $possibles->{$syval} = 1;
12369:                                  }
12370:                                  if ($checkforblock) {
12371:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12372:                                      unless (@blockers > 0) {
12373:                                          $syval = $poss_syval;
12374:                                          $realpossible++;
12375:                                      }
12376:                                  } else {
12377:                                      $syval = $poss_syval;
12378:                                      $realpossible++;
12379:                                  }
12380:                              }
12381: 			 }
12382:                      }
12383: 		     if ($realpossible!=1) { $syval=''; }
12384:                  } else {
12385:                      $syval='';
12386:                  }
12387: 	      }
12388:               untie(%bighash);
12389:            }
12390:         }
12391:         if ($syval) {
12392: 	    return $env{$cache_str}=$syval;
12393:         }
12394:     }
12395:     &appenv({'request.ambiguous' => $thisfn});
12396:     return $env{$cache_str}='';
12397: }
12398: 
12399: # ---------------------------------------------------------- Return random seed
12400: 
12401: sub numval {
12402:     my $txt=shift;
12403:     $txt=~tr/A-J/0-9/;
12404:     $txt=~tr/a-j/0-9/;
12405:     $txt=~tr/K-T/0-9/;
12406:     $txt=~tr/k-t/0-9/;
12407:     $txt=~tr/U-Z/0-5/;
12408:     $txt=~tr/u-z/0-5/;
12409:     $txt=~s/\D//g;
12410:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12411:     return int($txt);
12412: }
12413: 
12414: sub numval2 {
12415:     my $txt=shift;
12416:     $txt=~tr/A-J/0-9/;
12417:     $txt=~tr/a-j/0-9/;
12418:     $txt=~tr/K-T/0-9/;
12419:     $txt=~tr/k-t/0-9/;
12420:     $txt=~tr/U-Z/0-5/;
12421:     $txt=~tr/u-z/0-5/;
12422:     $txt=~s/\D//g;
12423:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12424:     my $total;
12425:     foreach my $val (@txts) { $total+=$val; }
12426:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12427:     return int($total);
12428: }
12429: 
12430: sub numval3 {
12431:     use integer;
12432:     my $txt=shift;
12433:     $txt=~tr/A-J/0-9/;
12434:     $txt=~tr/a-j/0-9/;
12435:     $txt=~tr/K-T/0-9/;
12436:     $txt=~tr/k-t/0-9/;
12437:     $txt=~tr/U-Z/0-5/;
12438:     $txt=~tr/u-z/0-5/;
12439:     $txt=~s/\D//g;
12440:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12441:     my $total;
12442:     foreach my $val (@txts) { $total+=$val; }
12443:     if ($_64bit) { $total=(($total<<32)>>32); }
12444:     return $total;
12445: }
12446: 
12447: sub digest {
12448:     my ($data)=@_;
12449:     my $digest=&Digest::MD5::md5($data);
12450:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12451:     my ($e,$f);
12452:     {
12453:         use integer;
12454:         $e=($a+$b);
12455:         $f=($c+$d);
12456:         if ($_64bit) {
12457:             $e=(($e<<32)>>32);
12458:             $f=(($f<<32)>>32);
12459:         }
12460:     }
12461:     if (wantarray) {
12462: 	return ($e,$f);
12463:     } else {
12464: 	my $g;
12465: 	{
12466: 	    use integer;
12467: 	    $g=($e+$f);
12468: 	    if ($_64bit) {
12469: 		$g=(($g<<32)>>32);
12470: 	    }
12471: 	}
12472: 	return $g;
12473:     }
12474: }
12475: 
12476: sub latest_rnd_algorithm_id {
12477:     return '64bit5';
12478: }
12479: 
12480: sub get_rand_alg {
12481:     my ($courseid)=@_;
12482:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12483:     if ($courseid) {
12484: 	return $env{"course.$courseid.rndseed"};
12485:     }
12486:     return &latest_rnd_algorithm_id();
12487: }
12488: 
12489: sub validCODE {
12490:     my ($CODE)=@_;
12491:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12492:     return 0;
12493: }
12494: 
12495: sub getCODE {
12496:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12497:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12498: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12499: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12500: 	return $Apache::lonhomework::history{'resource.CODE'};
12501:     }
12502:     return undef;
12503: }
12504: #
12505: #  Determines the random seed for a specific context:
12506: #
12507: # parameters:
12508: #   symb      - in course context the symb for the seed.
12509: #   course_id - The course id of the form domain_coursenum.
12510: #   domain    - Domain for the user.
12511: #   course    - Course for the user.
12512: #   cenv      - environment of the course.
12513: #
12514: # NOTE:
12515: #   All parameters are picked out of the environment if missing
12516: #   or not defined.
12517: #   If a symb cannot be determined the current time is used instead.
12518: #
12519: #  For a given well defined symb, courside, domain, username,
12520: #  and course environment, the seed is reproducible.
12521: #
12522: sub rndseed {
12523:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12524:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12525:     if (!defined($symb)) {
12526: 	unless ($symb=$wsymb) { return time; }
12527:     }
12528:     if (!defined $courseid) { 
12529: 	$courseid=$wcourseid; 
12530:     }
12531:     if (!defined $domain) { $domain=$wdomain; }
12532:     if (!defined $username) { $username=$wusername }
12533: 
12534:     my $which;
12535:     if (defined($cenv->{'rndseed'})) {
12536: 	$which = $cenv->{'rndseed'};
12537:     } else {
12538: 	$which =&get_rand_alg($courseid);
12539:     }
12540:     if (defined(&getCODE())) {
12541: 
12542: 	if ($which eq '64bit5') {
12543: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12544: 	} elsif ($which eq '64bit4') {
12545: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12546: 	} else {
12547: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12548: 	}
12549:     } elsif ($which eq '64bit5') {
12550: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12551:     } elsif ($which eq '64bit4') {
12552: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12553:     } elsif ($which eq '64bit3') {
12554: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12555:     } elsif ($which eq '64bit2') {
12556: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12557:     } elsif ($which eq '64bit') {
12558: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12559:     }
12560:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12561: }
12562: 
12563: sub rndseed_32bit {
12564:     my ($symb,$courseid,$domain,$username)=@_;
12565:     {
12566: 	use integer;
12567: 	my $symbchck=unpack("%32C*",$symb) << 27;
12568: 	my $symbseed=numval($symb) << 22;
12569: 	my $namechck=unpack("%32C*",$username) << 17;
12570: 	my $nameseed=numval($username) << 12;
12571: 	my $domainseed=unpack("%32C*",$domain) << 7;
12572: 	my $courseseed=unpack("%32C*",$courseid);
12573: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12574: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12575: 	#&logthis("rndseed :$num:$symb");
12576: 	if ($_64bit) { $num=(($num<<32)>>32); }
12577: 	return $num;
12578:     }
12579: }
12580: 
12581: sub rndseed_64bit {
12582:     my ($symb,$courseid,$domain,$username)=@_;
12583:     {
12584: 	use integer;
12585: 	my $symbchck=unpack("%32S*",$symb) << 21;
12586: 	my $symbseed=numval($symb) << 10;
12587: 	my $namechck=unpack("%32S*",$username);
12588: 	
12589: 	my $nameseed=numval($username) << 21;
12590: 	my $domainseed=unpack("%32S*",$domain) << 10;
12591: 	my $courseseed=unpack("%32S*",$courseid);
12592: 	
12593: 	my $num1=$symbchck+$symbseed+$namechck;
12594: 	my $num2=$nameseed+$domainseed+$courseseed;
12595: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12596: 	#&logthis("rndseed :$num:$symb");
12597: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12598: 	return "$num1,$num2";
12599:     }
12600: }
12601: 
12602: sub rndseed_64bit2 {
12603:     my ($symb,$courseid,$domain,$username)=@_;
12604:     {
12605: 	use integer;
12606: 	# strings need to be an even # of cahracters long, it it is odd the
12607:         # last characters gets thrown away
12608: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12609: 	my $symbseed=numval($symb) << 10;
12610: 	my $namechck=unpack("%32S*",$username.' ');
12611: 	
12612: 	my $nameseed=numval($username) << 21;
12613: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12614: 	my $courseseed=unpack("%32S*",$courseid.' ');
12615: 	
12616: 	my $num1=$symbchck+$symbseed+$namechck;
12617: 	my $num2=$nameseed+$domainseed+$courseseed;
12618: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12619: 	#&logthis("rndseed :$num:$symb");
12620: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12621: 	return "$num1,$num2";
12622:     }
12623: }
12624: 
12625: sub rndseed_64bit3 {
12626:     my ($symb,$courseid,$domain,$username)=@_;
12627:     {
12628: 	use integer;
12629: 	# strings need to be an even # of cahracters long, it it is odd the
12630:         # last characters gets thrown away
12631: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12632: 	my $symbseed=numval2($symb) << 10;
12633: 	my $namechck=unpack("%32S*",$username.' ');
12634: 	
12635: 	my $nameseed=numval2($username) << 21;
12636: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12637: 	my $courseseed=unpack("%32S*",$courseid.' ');
12638: 	
12639: 	my $num1=$symbchck+$symbseed+$namechck;
12640: 	my $num2=$nameseed+$domainseed+$courseseed;
12641: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12642: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12643: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12644: 	
12645: 	return "$num1:$num2";
12646:     }
12647: }
12648: 
12649: sub rndseed_64bit4 {
12650:     my ($symb,$courseid,$domain,$username)=@_;
12651:     {
12652: 	use integer;
12653: 	# strings need to be an even # of cahracters long, it it is odd the
12654:         # last characters gets thrown away
12655: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12656: 	my $symbseed=numval3($symb) << 10;
12657: 	my $namechck=unpack("%32S*",$username.' ');
12658: 	
12659: 	my $nameseed=numval3($username) << 21;
12660: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12661: 	my $courseseed=unpack("%32S*",$courseid.' ');
12662: 	
12663: 	my $num1=$symbchck+$symbseed+$namechck;
12664: 	my $num2=$nameseed+$domainseed+$courseseed;
12665: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12666: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12667: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12668: 	
12669: 	return "$num1:$num2";
12670:     }
12671: }
12672: 
12673: sub rndseed_64bit5 {
12674:     my ($symb,$courseid,$domain,$username)=@_;
12675:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12676:     return "$num1:$num2";
12677: }
12678: 
12679: sub rndseed_CODE_64bit {
12680:     my ($symb,$courseid,$domain,$username)=@_;
12681:     {
12682: 	use integer;
12683: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12684: 	my $symbseed=numval2($symb);
12685: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12686: 	my $CODEseed=numval(&getCODE());
12687: 	my $courseseed=unpack("%32S*",$courseid.' ');
12688: 	my $num1=$symbseed+$CODEchck;
12689: 	my $num2=$CODEseed+$courseseed+$symbchck;
12690: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12691: 	#&logthis("rndseed :$num1:$num2:$symb");
12692: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12693: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12694: 	return "$num1:$num2";
12695:     }
12696: }
12697: 
12698: sub rndseed_CODE_64bit4 {
12699:     my ($symb,$courseid,$domain,$username)=@_;
12700:     {
12701: 	use integer;
12702: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12703: 	my $symbseed=numval3($symb);
12704: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12705: 	my $CODEseed=numval3(&getCODE());
12706: 	my $courseseed=unpack("%32S*",$courseid.' ');
12707: 	my $num1=$symbseed+$CODEchck;
12708: 	my $num2=$CODEseed+$courseseed+$symbchck;
12709: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12710: 	#&logthis("rndseed :$num1:$num2:$symb");
12711: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12712: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12713: 	return "$num1:$num2";
12714:     }
12715: }
12716: 
12717: sub rndseed_CODE_64bit5 {
12718:     my ($symb,$courseid,$domain,$username)=@_;
12719:     my $code = &getCODE();
12720:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
12721:     return "$num1:$num2";
12722: }
12723: 
12724: sub setup_random_from_rndseed {
12725:     my ($rndseed)=@_;
12726:     if ($rndseed =~/([,:])/) {
12727:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12728:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12729:             &Math::Random::random_set_seed_from_phrase($rndseed);
12730:         } else {
12731:             &Math::Random::random_set_seed($num1,$num2);
12732:         }
12733:     } else {
12734: 	&Math::Random::random_set_seed_from_phrase($rndseed);
12735:     }
12736: }
12737: 
12738: sub latest_receipt_algorithm_id {
12739:     return 'receipt3';
12740: }
12741: 
12742: sub recunique {
12743:     my $fucourseid=shift;
12744:     my $unique;
12745:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12746: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12747: 	$unique=$env{"course.$fucourseid.internal.encseed"};
12748:     } else {
12749: 	$unique=$perlvar{'lonReceipt'};
12750:     }
12751:     return unpack("%32C*",$unique);
12752: }
12753: 
12754: sub recprefix {
12755:     my $fucourseid=shift;
12756:     my $prefix;
12757:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12758: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12759: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
12760:     } else {
12761: 	$prefix=$perlvar{'lonHostID'};
12762:     }
12763:     return unpack("%32C*",$prefix);
12764: }
12765: 
12766: sub ireceipt {
12767:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
12768: 
12769:     my $return =&recprefix($fucourseid).'-';
12770: 
12771:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12772: 	$env{'request.state'} eq 'construct') {
12773: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12774: 	return $return;
12775:     }
12776: 
12777:     my $cuname=unpack("%32C*",$funame);
12778:     my $cudom=unpack("%32C*",$fudom);
12779:     my $cucourseid=unpack("%32C*",$fucourseid);
12780:     my $cusymb=unpack("%32C*",$fusymb);
12781:     my $cunique=&recunique($fucourseid);
12782:     my $cpart=unpack("%32S*",$part);
12783:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12784: 
12785: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
12786: 			       
12787: 	$return.= ($cunique%$cuname+
12788: 		   $cunique%$cudom+
12789: 		   $cusymb%$cuname+
12790: 		   $cusymb%$cudom+
12791: 		   $cucourseid%$cuname+
12792: 		   $cucourseid%$cudom+
12793: 		   $cpart%$cuname+
12794: 		   $cpart%$cudom);
12795:     } else {
12796: 	$return.= ($cunique%$cuname+
12797: 		   $cunique%$cudom+
12798: 		   $cusymb%$cuname+
12799: 		   $cusymb%$cudom+
12800: 		   $cucourseid%$cuname+
12801: 		   $cucourseid%$cudom);
12802:     }
12803:     return $return;
12804: }
12805: 
12806: sub receipt {
12807:     my ($part)=@_;
12808:     my ($symb,$courseid,$domain,$name) = &whichuser();
12809:     return &ireceipt($name,$domain,$courseid,$symb,$part);
12810: }
12811: 
12812: sub whichuser {
12813:     my ($passedsymb)=@_;
12814:     my ($symb,$courseid,$domain,$name,$publicuser);
12815:     if (defined($env{'form.grade_symb'})) {
12816: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12817: 	my $allowed=&allowed('vgr',$tmp_courseid);
12818: 	if (!$allowed &&
12819: 	    exists($env{'request.course.sec'}) &&
12820: 	    $env{'request.course.sec'} !~ /^\s*$/) {
12821: 	    $allowed=&allowed('vgr',$tmp_courseid.
12822: 			      '/'.$env{'request.course.sec'});
12823: 	}
12824: 	if ($allowed) {
12825: 	    ($symb)=&get_env_multiple('form.grade_symb');
12826: 	    $courseid=$tmp_courseid;
12827: 	    ($domain)=&get_env_multiple('form.grade_domain');
12828: 	    ($name)=&get_env_multiple('form.grade_username');
12829: 	    return ($symb,$courseid,$domain,$name,$publicuser);
12830: 	}
12831:     }
12832:     if (!$passedsymb) {
12833: 	$symb=&symbread();
12834:     } else {
12835: 	$symb=$passedsymb;
12836:     }
12837:     $courseid=$env{'request.course.id'};
12838:     $domain=$env{'user.domain'};
12839:     $name=$env{'user.name'};
12840:     if ($name eq 'public' && $domain eq 'public') {
12841: 	if (!defined($env{'form.username'})) {
12842: 	    $env{'form.username'}.=time.rand(10000000);
12843: 	}
12844: 	$name.=$env{'form.username'};
12845:     }
12846:     return ($symb,$courseid,$domain,$name,$publicuser);
12847: 
12848: }
12849: 
12850: # ------------------------------------------------------------ Serves up a file
12851: # returns either the contents of the file or 
12852: # -1 if the file doesn't exist
12853: #
12854: # if the target is a file that was uploaded via DOCS, 
12855: # a check will be made to see if a current copy exists on the local server,
12856: # if it does this will be served, otherwise a copy will be retrieved from
12857: # the home server for the course and stored in /home/httpd/html/userfiles on
12858: # the local server.   
12859: 
12860: sub getfile {
12861:     my ($file) = @_;
12862:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
12863:     &repcopy($file);
12864:     return &readfile($file);
12865: }
12866: 
12867: sub repcopy_userfile {
12868:     my ($file)=@_;
12869:     my $londocroot = $perlvar{'lonDocRoot'};
12870:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
12871:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
12872:     my ($cdom,$cnum,$filename) = 
12873: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
12874:     my $uri="/uploaded/$cdom/$cnum/$filename";
12875:     if (-e "$file") {
12876: # we already have a local copy, check it out
12877: 	my @fileinfo = stat($file);
12878: 	my $rtncode;
12879: 	my $info;
12880: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
12881: 	if ($lwpresp ne 'ok') {
12882: # there is no such file anymore, even though we had a local copy
12883: 	    if ($rtncode eq '404') {
12884: 		unlink($file);
12885: 	    }
12886: 	    return -1;
12887: 	}
12888: 	if ($info < $fileinfo[9]) {
12889: # nice, the file we have is up-to-date, just say okay
12890: 	    return 'ok';
12891: 	} else {
12892: # the file is outdated, get rid of it
12893: 	    unlink($file);
12894: 	}
12895:     }
12896: # one way or the other, at this point, we don't have the file
12897: # construct the correct path for the file
12898:     my @parts = ($cdom,$cnum); 
12899:     if ($filename =~ m|^(.+)/[^/]+$|) {
12900: 	push @parts, split(/\//,$1);
12901:     }
12902:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12903:     foreach my $part (@parts) {
12904: 	$path .= '/'.$part;
12905: 	if (!-e $path) {
12906: 	    mkdir($path,0770);
12907: 	}
12908:     }
12909: # now the path exists for sure
12910: # get a user agent
12911:     my $transferfile=$file.'.in.transfer';
12912: # FIXME: this should flock
12913:     if (-e $transferfile) { return 'ok'; }
12914:     my $request;
12915:     $uri=~s/^\///;
12916:     my $homeserver = &homeserver($cnum,$cdom);
12917:     my $protocol = $protocol{$homeserver};
12918:     $protocol = 'http' if ($protocol ne 'https');
12919:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
12920:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
12921: # did it work?
12922:     if ($response->is_error()) {
12923: 	unlink($transferfile);
12924: 	&logthis("Userfile repcopy failed for $uri");
12925: 	return -1;
12926:     }
12927: # worked, rename the transfer file
12928:     rename($transferfile,$file);
12929:     return 'ok';
12930: }
12931: 
12932: sub tokenwrapper {
12933:     my $uri=shift;
12934:     $uri=~s|^https?\://([^/]+)||;
12935:     $uri=~s|^/||;
12936:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
12937:     my $token=$1;
12938:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
12939:     if ($udom && $uname && $file) {
12940: 	$file=~s|(\?\.*)*$||;
12941:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
12942:         my $homeserver = &homeserver($uname,$udom);
12943:         my $protocol = $protocol{$homeserver};
12944:         $protocol = 'http' if ($protocol ne 'https');
12945:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
12946:                (($uri=~/\?/)?'&':'?').'token='.$token.
12947:                                '&tokenissued='.$perlvar{'lonHostID'};
12948:     } else {
12949:         return '/adm/notfound.html';
12950:     }
12951: }
12952: 
12953: # call with reqtype HEAD: get last modification time
12954: # call with reqtype GET: get the file contents
12955: # Do not call this with reqtype GET for large files! It loads everything into memory
12956: #
12957: sub getuploaded {
12958:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12959:     $uri=~s/^\///;
12960:     my $homeserver = &homeserver($cnum,$cdom);
12961:     my $protocol = $protocol{$homeserver};
12962:     $protocol = 'http' if ($protocol ne 'https');
12963:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
12964:     my $request=new HTTP::Request($reqtype,$uri);
12965:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
12966:     $$rtncode = $response->code;
12967:     if (! $response->is_success()) {
12968: 	return 'failed';
12969:     }      
12970:     if ($reqtype eq 'HEAD') {
12971: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
12972:     } elsif ($reqtype eq 'GET') {
12973: 	$$info = $response->content;
12974:     }
12975:     return 'ok';
12976: }
12977: 
12978: sub readfile {
12979:     my $file = shift;
12980:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
12981:     my $fh;
12982:     open($fh,"<$file");
12983:     my $a='';
12984:     while (my $line = <$fh>) { $a .= $line; }
12985:     return $a;
12986: }
12987: 
12988: sub filelocation {
12989:     my ($dir,$file) = @_;
12990:     my $location;
12991:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
12992: 
12993:     if ($file =~ m-^/adm/-) {
12994: 	$file=~s-^/adm/wrapper/-/-;
12995: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
12996:     }
12997: 
12998:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
12999:         $location = $file;
13000:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13001:         my ($udom,$uname,$filename)=
13002:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13003:         my $home=&homeserver($uname,$udom);
13004:         my $is_me=0;
13005:         my @ids=&current_machine_ids();
13006:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13007:         if ($is_me) {
13008:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13009:         } else {
13010:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13011:   	      $udom.'/'.$uname.'/'.$filename;
13012:         }
13013:     } elsif ($file =~ m-^/adm/-) {
13014: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13015:     } else {
13016:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13017:         $file=~s:^/(res|priv)/:/:;
13018:         my $space=$1;
13019:         if ( !( $file =~ m:^/:) ) {
13020:             $location = $dir. '/'.$file;
13021:         } else {
13022:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13023:         }
13024:     }
13025:     $location=~s://+:/:g; # remove duplicate /
13026:     while ($location=~m{/\.\./}) {
13027: 	if ($location =~ m{/[^/]+/\.\./}) {
13028: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13029: 	} else {
13030: 	    $location=~ s{/\.\./}{/}g;
13031: 	}
13032:     } #remove dir/..
13033:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13034:     return $location;
13035: }
13036: 
13037: sub hreflocation {
13038:     my ($dir,$file)=@_;
13039:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13040: 	$file=filelocation($dir,$file);
13041:     } elsif ($file=~m-^/adm/-) {
13042: 	$file=~s-^/adm/wrapper/-/-;
13043: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13044:     }
13045:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13046: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13047:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13048: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13049: 	        {/uploaded/$1/$2/}x;
13050:     }
13051:     if ($file=~ m{^/userfiles/}) {
13052: 	$file =~ s{^/userfiles/}{/uploaded/};
13053:     }
13054:     return $file;
13055: }
13056: 
13057: 
13058: 
13059: 
13060: 
13061: sub current_machine_domains {
13062:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13063: }
13064: 
13065: sub machine_domains {
13066:     my ($hostname) = @_;
13067:     my @domains;
13068:     my %hostname = &all_hostnames();
13069:     while( my($id, $name) = each(%hostname)) {
13070: #	&logthis("-$id-$name-$hostname-");
13071: 	if ($hostname eq $name) {
13072: 	    push(@domains,&host_domain($id));
13073: 	}
13074:     }
13075:     return @domains;
13076: }
13077: 
13078: sub current_machine_ids {
13079:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13080: }
13081: 
13082: sub machine_ids {
13083:     my ($hostname) = @_;
13084:     $hostname ||= &hostname($perlvar{'lonHostID'});
13085:     my @ids;
13086:     my %name_to_host = &all_names();
13087:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13088: 	return @{ $name_to_host{$hostname} };
13089:     }
13090:     return;
13091: }
13092: 
13093: sub additional_machine_domains {
13094:     my @domains;
13095:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
13096:     while( my $line = <$fh>) {
13097:         $line =~ s/\s//g;
13098:         push(@domains,$line);
13099:     }
13100:     return @domains;
13101: }
13102: 
13103: sub default_login_domain {
13104:     my $domain = $perlvar{'lonDefDomain'};
13105:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13106:     foreach my $posdom (&current_machine_domains(),
13107:                         &additional_machine_domains()) {
13108:         if (lc($posdom) eq lc($testdomain)) {
13109:             $domain=$posdom;
13110:             last;
13111:         }
13112:     }
13113:     return $domain;
13114: }
13115: 
13116: # ------------------------------------------------------------- Declutters URLs
13117: 
13118: sub declutter {
13119:     my $thisfn=shift;
13120:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13121:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13122:         $thisfn=~s{^/home/httpd/html}{};
13123:     }
13124:     $thisfn=~s/^\///;
13125:     $thisfn=~s|^adm/wrapper/||;
13126:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13127:     $thisfn=~s/^res\///;
13128:     $thisfn=~s/^priv\///;
13129:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13130:         $thisfn=~s/\?.+$//;
13131:     }
13132:     return $thisfn;
13133: }
13134: 
13135: # ------------------------------------------------------------- Clutter up URLs
13136: 
13137: sub clutter {
13138:     my $thisfn='/'.&declutter(shift);
13139:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13140: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13141:        $thisfn='/res'.$thisfn; 
13142:     }
13143:     if ($thisfn !~m|^/adm|) {
13144: 	if ($thisfn =~ m|^/ext/|) {
13145: 	    $thisfn='/adm/wrapper'.$thisfn;
13146: 	} else {
13147: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13148: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13149: 	    if ($embstyle eq 'ssi'
13150: 		|| ($embstyle eq 'hdn')
13151: 		|| ($embstyle eq 'rat')
13152: 		|| ($embstyle eq 'prv')
13153: 		|| ($embstyle eq 'ign')) {
13154: 		#do nothing with these
13155: 	    } elsif (($embstyle eq 'img') 
13156: 		|| ($embstyle eq 'emb')
13157: 		|| ($embstyle eq 'wrp')) {
13158: 		$thisfn='/adm/wrapper'.$thisfn;
13159: 	    } elsif ($embstyle eq 'unk'
13160: 		     && $thisfn!~/\.(sequence|page)$/) {
13161: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13162: 	    } else {
13163: #		&logthis("Got a blank emb style");
13164: 	    }
13165: 	}
13166:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13167:         $thisfn='/adm/wrapper'.$thisfn;
13168:     }
13169:     return $thisfn;
13170: }
13171: 
13172: sub clutter_with_no_wrapper {
13173:     my $uri = &clutter(shift);
13174:     if ($uri =~ m-^/adm/-) {
13175: 	$uri =~ s-^/adm/wrapper/-/-;
13176: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13177:     }
13178:     return $uri;
13179: }
13180: 
13181: sub freeze_escape {
13182:     my ($value)=@_;
13183:     if (ref($value)) {
13184: 	$value=&nfreeze($value);
13185: 	return '__FROZEN__'.&escape($value);
13186:     }
13187:     return &escape($value);
13188: }
13189: 
13190: 
13191: sub thaw_unescape {
13192:     my ($value)=@_;
13193:     if ($value =~ /^__FROZEN__/) {
13194: 	substr($value,0,10,undef);
13195: 	$value=&unescape($value);
13196: 	return &thaw($value);
13197:     }
13198:     return &unescape($value);
13199: }
13200: 
13201: sub correct_line_ends {
13202:     my ($result)=@_;
13203:     $$result =~s/\r\n/\n/mg;
13204:     $$result =~s/\r/\n/mg;
13205: }
13206: # ================================================================ Main Program
13207: 
13208: sub goodbye {
13209:    &logthis("Starting Shut down");
13210: #not converted to using infrastruture and probably shouldn't be
13211:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13212: #converted
13213: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13214:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13215: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13216: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13217: #1.1 only
13218: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13219: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13220: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13221: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13222:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13223:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13224:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13225:    &flushcourselogs();
13226:    &logthis("Shutting down");
13227: }
13228: 
13229: sub get_dns {
13230:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13231:     if (!$ignore_cache) {
13232: 	my ($content,$cached)=
13233: 	    &Apache::lonnet::is_cached_new('dns',$url);
13234: 	if ($cached) {
13235: 	    &$func($content,$hashref);
13236: 	    return;
13237: 	}
13238:     }
13239: 
13240:     my %alldns;
13241:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13242:     foreach my $dns (<$config>) {
13243: 	next if ($dns !~ /^\^(\S*)/x);
13244:         my $line = $1;
13245:         my ($host,$protocol) = split(/:/,$line);
13246:         if ($protocol ne 'https') {
13247:             $protocol = 'http';
13248:         }
13249: 	$alldns{$host} = $protocol;
13250:     }
13251:     while (%alldns) {
13252: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13253: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13254:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13255:         delete($alldns{$dns});
13256: 	next if ($response->is_error());
13257: 	my @content = split("\n",$response->content);
13258: 	unless ($nocache) {
13259: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
13260: 	}
13261: 	&$func(\@content,$hashref);
13262: 	return;
13263:     }
13264:     close($config);
13265:     my $which = (split('/',$url))[3];
13266:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13267:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
13268:     my @content = <$config>;
13269:     &$func(\@content,$hashref);
13270:     return;
13271: }
13272: 
13273: # ------------------------------------------------------Get DNS checksums file
13274: sub parse_dns_checksums_tab {
13275:     my ($lines,$hashref) = @_;
13276:     my $lonhost = $perlvar{'lonHostID'};
13277:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13278:     my $loncaparev = &get_server_loncaparev($machine_dom);
13279:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13280:     my $webconfdir = '/etc/httpd/conf';
13281:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13282:         $webconfdir = '/etc/apache2';
13283:     } elsif ($distro =~ /^sles(\d+)$/) {
13284:         if ($1 >= 10) {
13285:             $webconfdir = '/etc/apache2';
13286:         }
13287:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13288:         if ($1 >= 10.0) {
13289:             $webconfdir = '/etc/apache2';
13290:         }
13291:     }
13292:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13293:     my (%chksum,%revnum);
13294:     if (ref($lines) eq 'ARRAY') {
13295:         chomp(@{$lines});
13296:         my $version = shift(@{$lines});
13297:         if ($version eq $release) {  
13298:             foreach my $line (@{$lines}) {
13299:                 my ($file,$version,$shasum) = split(/,/,$line);
13300:                 if ($file =~ m{^/etc/httpd/conf}) {
13301:                     if ($webconfdir eq '/etc/apache2') {
13302:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13303:                     }
13304:                 }
13305:                 $chksum{$file} = $shasum;
13306:                 $revnum{$file} = $version;
13307:             }
13308:             if (ref($hashref) eq 'HASH') {
13309:                 %{$hashref} = (
13310:                                 sums     => \%chksum,
13311:                                 versions => \%revnum,
13312:                               );
13313:             }
13314:         }
13315:     }
13316:     return;
13317: }
13318: 
13319: sub fetch_dns_checksums {
13320:     my %checksums;
13321:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13322:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13323:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13324:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13325:              \%checksums);
13326:     return \%checksums;
13327: }
13328: 
13329: # ------------------------------------------------------------ Read domain file
13330: {
13331:     my $loaded;
13332:     my %domain;
13333: 
13334:     sub parse_domain_tab {
13335: 	my ($lines) = @_;
13336: 	foreach my $line (@$lines) {
13337: 	    next if ($line =~ /^(\#|\s*$ )/x);
13338: 
13339: 	    chomp($line);
13340: 	    my ($name,@elements) = split(/:/,$line,9);
13341: 	    my %this_domain;
13342: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13343: 			       'lang_def', 'city', 'longi', 'lati',
13344: 			       'primary') {
13345: 		$this_domain{$field} = shift(@elements);
13346: 	    }
13347: 	    $domain{$name} = \%this_domain;
13348: 	}
13349:     }
13350: 
13351:     sub reset_domain_info {
13352: 	undef($loaded);
13353: 	undef(%domain);
13354:     }
13355: 
13356:     sub load_domain_tab {
13357: 	my ($ignore_cache,$nocache) = @_;
13358: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13359: 	my $fh;
13360: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
13361: 	    my @lines = <$fh>;
13362: 	    &parse_domain_tab(\@lines);
13363: 	}
13364: 	close($fh);
13365: 	$loaded = 1;
13366:     }
13367: 
13368:     sub domain {
13369: 	&load_domain_tab() if (!$loaded);
13370: 
13371: 	my ($name,$what) = @_;
13372: 	return if ( !exists($domain{$name}) );
13373: 
13374: 	if (!$what) {
13375: 	    return $domain{$name}{'description'};
13376: 	}
13377: 	return $domain{$name}{$what};
13378:     }
13379: 
13380:     sub domain_info {
13381:         &load_domain_tab() if (!$loaded);
13382:         return %domain;
13383:     }
13384: 
13385: }
13386: 
13387: 
13388: # ------------------------------------------------------------- Read hosts file
13389: {
13390:     my %hostname;
13391:     my %hostdom;
13392:     my %libserv;
13393:     my $loaded;
13394:     my %name_to_host;
13395:     my %internetdom;
13396:     my %LC_dns_serv;
13397: 
13398:     sub parse_hosts_tab {
13399: 	my ($file) = @_;
13400: 	foreach my $configline (@$file) {
13401: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13402:             chomp($configline);
13403: 	    if ($configline =~ /^\^/) {
13404:                 if ($configline =~ /^\^([\w.\-]+)/) {
13405:                     $LC_dns_serv{$1} = 1;
13406:                 }
13407:                 next;
13408:             }
13409: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13410: 	    $name=~s/\s//g;
13411: 	    if ($id && $domain && $role && $name) {
13412: 		$hostname{$id}=$name;
13413: 		push(@{$name_to_host{$name}}, $id);
13414: 		$hostdom{$id}=$domain;
13415: 		if ($role eq 'library') { $libserv{$id}=$name; }
13416:                 if (defined($protocol)) {
13417:                     if ($protocol eq 'https') {
13418:                         $protocol{$id} = $protocol;
13419:                     } else {
13420:                         $protocol{$id} = 'http'; 
13421:                     }
13422:                 } else {
13423:                     $protocol{$id} = 'http';
13424:                 }
13425:                 if (defined($intdom)) {
13426:                     $internetdom{$id} = $intdom;
13427:                 }
13428: 	    }
13429: 	}
13430:     }
13431:     
13432:     sub reset_hosts_info {
13433: 	&purge_remembered();
13434: 	&reset_domain_info();
13435: 	&reset_hosts_ip_info();
13436:         undef(%internetdom);
13437: 	undef(%name_to_host);
13438: 	undef(%hostname);
13439: 	undef(%hostdom);
13440: 	undef(%libserv);
13441: 	undef($loaded);
13442:     }
13443: 
13444:     sub load_hosts_tab {
13445: 	my ($ignore_cache,$nocache) = @_;
13446: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13447: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13448: 	my @config = <$config>;
13449: 	&parse_hosts_tab(\@config);
13450: 	close($config);
13451: 	$loaded=1;
13452:     }
13453: 
13454:     sub hostname {
13455: 	&load_hosts_tab() if (!$loaded);
13456: 
13457: 	my ($lonid) = @_;
13458: 	return $hostname{$lonid};
13459:     }
13460: 
13461:     sub all_hostnames {
13462: 	&load_hosts_tab() if (!$loaded);
13463: 
13464: 	return %hostname;
13465:     }
13466: 
13467:     sub all_names {
13468:         my ($ignore_cache,$nocache) = @_;
13469: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13470: 
13471: 	return %name_to_host;
13472:     }
13473: 
13474:     sub all_host_domain {
13475:         &load_hosts_tab() if (!$loaded);
13476:         return %hostdom;
13477:     }
13478: 
13479:     sub all_host_intdom {
13480:         &load_hosts_tab() if (!$loaded);
13481:         return %internetdom;
13482:     }
13483: 
13484:     sub is_library {
13485: 	&load_hosts_tab() if (!$loaded);
13486: 
13487: 	return exists($libserv{$_[0]});
13488:     }
13489: 
13490:     sub all_library {
13491: 	&load_hosts_tab() if (!$loaded);
13492: 
13493: 	return %libserv;
13494:     }
13495: 
13496:     sub unique_library {
13497: 	#2x reverse removes all hostnames that appear more than once
13498:         my %unique = reverse &all_library();
13499:         return reverse %unique;
13500:     }
13501: 
13502:     sub get_servers {
13503: 	&load_hosts_tab() if (!$loaded);
13504: 
13505: 	my ($domain,$type) = @_;
13506: 	my %possible_hosts = ($type eq 'library') ? %libserv
13507: 	                                          : %hostname;
13508: 	my %result;
13509: 	if (ref($domain) eq 'ARRAY') {
13510: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13511: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13512: 		    $result{$host} = $hostname;
13513: 		}
13514: 	    }
13515: 	} else {
13516: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13517: 		if ($hostdom{$host} eq $domain) {
13518: 		    $result{$host} = $hostname;
13519: 		}
13520: 	    }
13521: 	}
13522: 	return %result;
13523:     }
13524: 
13525:     sub get_unique_servers {
13526:         my %unique = reverse &get_servers(@_);
13527: 	return reverse %unique;
13528:     }
13529: 
13530:     sub host_domain {
13531: 	&load_hosts_tab() if (!$loaded);
13532: 
13533: 	my ($lonid) = @_;
13534: 	return $hostdom{$lonid};
13535:     }
13536: 
13537:     sub all_domains {
13538: 	&load_hosts_tab() if (!$loaded);
13539: 
13540: 	my %seen;
13541: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13542: 	return @uniq;
13543:     }
13544: 
13545:     sub internet_dom {
13546:         &load_hosts_tab() if (!$loaded);
13547: 
13548:         my ($lonid) = @_;
13549:         return $internetdom{$lonid};
13550:     }
13551: 
13552:     sub is_LC_dns {
13553:         &load_hosts_tab() if (!$loaded);
13554: 
13555:         my ($hostname) = @_;
13556:         return exists($LC_dns_serv{$hostname});
13557:     }
13558: 
13559: }
13560: 
13561: { 
13562:     my %iphost;
13563:     my %name_to_ip;
13564:     my %lonid_to_ip;
13565: 
13566:     sub get_hosts_from_ip {
13567: 	my ($ip) = @_;
13568: 	my %iphosts = &get_iphost();
13569: 	if (ref($iphosts{$ip})) {
13570: 	    return @{$iphosts{$ip}};
13571: 	}
13572: 	return;
13573:     }
13574:     
13575:     sub reset_hosts_ip_info {
13576: 	undef(%iphost);
13577: 	undef(%name_to_ip);
13578: 	undef(%lonid_to_ip);
13579:     }
13580: 
13581:     sub get_host_ip {
13582: 	my ($lonid) = @_;
13583: 	if (exists($lonid_to_ip{$lonid})) {
13584: 	    return $lonid_to_ip{$lonid};
13585: 	}
13586: 	my $name=&hostname($lonid);
13587:    	my $ip = gethostbyname($name);
13588: 	return if (!$ip || length($ip) ne 4);
13589: 	$ip=inet_ntoa($ip);
13590: 	$name_to_ip{$name}   = $ip;
13591: 	$lonid_to_ip{$lonid} = $ip;
13592: 	return $ip;
13593:     }
13594:     
13595:     sub get_iphost {
13596: 	my ($ignore_cache,$nocache) = @_;
13597: 
13598: 	if (!$ignore_cache) {
13599: 	    if (%iphost) {
13600: 		return %iphost;
13601: 	    }
13602: 	    my ($ip_info,$cached)=
13603: 		&Apache::lonnet::is_cached_new('iphost','iphost');
13604: 	    if ($cached) {
13605: 		%iphost      = %{$ip_info->[0]};
13606: 		%name_to_ip  = %{$ip_info->[1]};
13607: 		%lonid_to_ip = %{$ip_info->[2]};
13608: 		return %iphost;
13609: 	    }
13610: 	}
13611: 
13612: 	# get yesterday's info for fallback
13613: 	my %old_name_to_ip;
13614: 	my ($ip_info,$cached)=
13615: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
13616: 	if ($cached) {
13617: 	    %old_name_to_ip = %{$ip_info->[1]};
13618: 	}
13619: 
13620: 	my %name_to_host = &all_names($ignore_cache,$nocache);
13621: 	foreach my $name (keys(%name_to_host)) {
13622: 	    my $ip;
13623: 	    if (!exists($name_to_ip{$name})) {
13624: 		$ip = gethostbyname($name);
13625: 		if (!$ip || length($ip) ne 4) {
13626: 		    if (defined($old_name_to_ip{$name})) {
13627: 			$ip = $old_name_to_ip{$name};
13628: 			&logthis("Can't find $name defaulting to old $ip");
13629: 		    } else {
13630: 			&logthis("Name $name no IP found");
13631: 			next;
13632: 		    }
13633: 		} else {
13634: 		    $ip=inet_ntoa($ip);
13635: 		}
13636: 		$name_to_ip{$name} = $ip;
13637: 	    } else {
13638: 		$ip = $name_to_ip{$name};
13639: 	    }
13640: 	    foreach my $id (@{ $name_to_host{$name} }) {
13641: 		$lonid_to_ip{$id} = $ip;
13642: 	    }
13643: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
13644: 	}
13645:         unless ($nocache) {
13646: 	    &do_cache_new('iphost','iphost',
13647: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
13648: 		          48*60*60);
13649:         }
13650: 
13651: 	return %iphost;
13652:     }
13653: 
13654:     #
13655:     #  Given a DNS returns the loncapa host name for that DNS 
13656:     # 
13657:     sub host_from_dns {
13658:         my ($dns) = @_;
13659:         my @hosts;
13660:         my $ip;
13661: 
13662:         if (exists($name_to_ip{$dns})) {
13663:             $ip = $name_to_ip{$dns};
13664:         }
13665:         if (!$ip) {
13666:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13667:             if (length($ip) == 4) { 
13668: 	        $ip   = &IO::Socket::inet_ntoa($ip);
13669:             }
13670:         }
13671:         if ($ip) {
13672: 	    @hosts = get_hosts_from_ip($ip);
13673: 	    return $hosts[0];
13674:         }
13675:         return undef;
13676:     }
13677: 
13678:     sub get_internet_names {
13679:         my ($lonid) = @_;
13680:         return if ($lonid eq '');
13681:         my ($idnref,$cached)=
13682:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
13683:         if ($cached) {
13684:             return $idnref;
13685:         }
13686:         my $ip = &get_host_ip($lonid);
13687:         my @hosts = &get_hosts_from_ip($ip);
13688:         my %iphost = &get_iphost();
13689:         my (@idns,%seen);
13690:         foreach my $id (@hosts) {
13691:             my $dom = &host_domain($id);
13692:             my $prim_id = &domain($dom,'primary');
13693:             my $prim_ip = &get_host_ip($prim_id);
13694:             next if ($seen{$prim_ip});
13695:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13696:                 foreach my $id (@{$iphost{$prim_ip}}) {
13697:                     my $intdom = &internet_dom($id);
13698:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
13699:                         push(@idns,$intdom);
13700:                     }
13701:                 }
13702:             }
13703:             $seen{$prim_ip} = 1;
13704:         }
13705:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
13706:     }
13707: 
13708: }
13709: 
13710: sub all_loncaparevs {
13711:     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);
13712: }
13713: 
13714: # ---------------------------------------------------------- Read loncaparev table
13715: {
13716:     sub load_loncaparevs { 
13717:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13718:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13719:                 while (my $configline=<$config>) {
13720:                     chomp($configline);
13721:                     my ($hostid,$loncaparev)=split(/:/,$configline);
13722:                     $loncaparevs{$hostid}=$loncaparev;
13723:                 }
13724:                 close($config);
13725:             }
13726:         }
13727:     }
13728: }
13729: 
13730: # ---------------------------------------------------------- Read serverhostID table
13731: {
13732:     sub load_serverhomeIDs {
13733:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13734:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13735:                 while (my $configline=<$config>) {
13736:                     chomp($configline);
13737:                     my ($name,$id)=split(/:/,$configline);
13738:                     $serverhomeIDs{$name}=$id;
13739:                 }
13740:                 close($config);
13741:             }
13742:         }
13743:     }
13744: }
13745: 
13746: 
13747: BEGIN {
13748: 
13749: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13750:     unless ($readit) {
13751: {
13752:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13753:     %perlvar = (%perlvar,%{$configvars});
13754: }
13755: 
13756: 
13757: # ------------------------------------------------------ Read spare server file
13758: {
13759:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
13760: 
13761:     while (my $configline=<$config>) {
13762:        chomp($configline);
13763:        if ($configline) {
13764: 	   my ($host,$type) = split(':',$configline,2);
13765: 	   if (!defined($type) || $type eq '') { $type = 'default' };
13766: 	   push(@{ $spareid{$type} }, $host);
13767:        }
13768:     }
13769:     close($config);
13770: }
13771: # ------------------------------------------------------------ Read permissions
13772: {
13773:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
13774: 
13775:     while (my $configline=<$config>) {
13776: 	chomp($configline);
13777: 	if ($configline) {
13778: 	    my ($role,$perm)=split(/ /,$configline);
13779: 	    if ($perm ne '') { $pr{$role}=$perm; }
13780: 	}
13781:     }
13782:     close($config);
13783: }
13784: 
13785: # -------------------------------------------- Read plain texts for permissions
13786: {
13787:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
13788: 
13789:     while (my $configline=<$config>) {
13790: 	chomp($configline);
13791: 	if ($configline) {
13792: 	    my ($short,@plain)=split(/:/,$configline);
13793:             %{$prp{$short}} = ();
13794: 	    if (@plain > 0) {
13795:                 $prp{$short}{'std'} = $plain[0];
13796:                 for (my $i=1; $i<@plain; $i++) {
13797:                     $prp{$short}{'alt'.$i} = $plain[$i];  
13798:                 }
13799:             }
13800: 	}
13801:     }
13802:     close($config);
13803: }
13804: 
13805: # ---------------------------------------------------------- Read package table
13806: {
13807:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
13808: 
13809:     while (my $configline=<$config>) {
13810: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
13811: 	chomp($configline);
13812: 	my ($short,$plain)=split(/:/,$configline);
13813: 	my ($pack,$name)=split(/\&/,$short);
13814: 	if ($plain ne '') {
13815: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
13816: 	    $packagetab{$short}=$plain; 
13817: 	}
13818:     }
13819:     close($config);
13820: }
13821: 
13822: # ---------------------------------------------------------- Read loncaparev table
13823: 
13824: &load_loncaparevs();
13825: 
13826: # ---------------------------------------------------------- Read serverhostID table
13827: 
13828: &load_serverhomeIDs();
13829: 
13830: # ---------------------------------------------------------- Read releaseslist XML
13831: {
13832:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13833:     if (-e $file) {
13834:         my $parser = HTML::LCParser->new($file);
13835:         while (my $token = $parser->get_token()) {
13836:             if ($token->[0] eq 'S') {
13837:                 my $item = $token->[1];
13838:                 my $name = $token->[2]{'name'};
13839:                 my $value = $token->[2]{'value'};
13840:                 my $valuematch = $token->[2]{'valuematch'};
13841:                 my $namematch = $token->[2]{'namematch'};
13842:                 if ($item eq 'parameter') {
13843:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13844:                         my $release = $parser->get_text();
13845:                         $release =~ s/(^\s*|\s*$ )//gx;
13846:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13847:                     }
13848:                 } elsif ($item ne '' && $name ne '') {
13849:                     my $release = $parser->get_text();
13850:                     $release =~ s/(^\s*|\s*$ )//gx;
13851:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
13852:                 }
13853:             }
13854:         }
13855:     }
13856: }
13857: 
13858: # ---------------------------------------------------------- Read managers table
13859: {
13860:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13861:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13862:             while (my $configline=<$config>) {
13863:                 chomp($configline);
13864:                 next if ($configline =~ /^\#/);
13865:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13866:                     $managerstab{$configline} = 1;
13867:                 }
13868:             }
13869:             close($config);
13870:         }
13871:     }
13872: }
13873: 
13874: # ------------- set up temporary directory
13875: {
13876:     $tmpdir = LONCAPA::tempdir();
13877: 
13878: }
13879: 
13880: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
13881: 				'compress_threshold'=> 20_000,
13882:  			        });
13883: 
13884: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
13885: $dumpcount=0;
13886: $locknum=0;
13887: 
13888: &logtouch();
13889: &logthis('<font color="yellow">INFO: Read configuration</font>');
13890: $readit=1;
13891:     {
13892: 	use integer;
13893: 	my $test=(2**32)+1;
13894: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
13895: 	&logthis(" Detected 64bit platform ($_64bit)");
13896:     }
13897: }
13898: }
13899: 
13900: 1;
13901: __END__
13902: 
13903: =pod
13904: 
13905: =head1 NAME
13906: 
13907: Apache::lonnet - Subroutines to ask questions about things in the network.
13908: 
13909: =head1 SYNOPSIS
13910: 
13911: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
13912: 
13913:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13914: 
13915: Common parameters:
13916: 
13917: =over 4
13918: 
13919: =item *
13920: 
13921: $uname : an internal username (if $cname expecting a course Id specifically)
13922: 
13923: =item *
13924: 
13925: $udom : a domain (if $cdom expecting a course's domain specifically)
13926: 
13927: =item *
13928: 
13929: $symb : a resource instance identifier
13930: 
13931: =item *
13932: 
13933: $namespace : the name of a .db file that contains the data needed or
13934: being set.
13935: 
13936: =back
13937: 
13938: =head1 OVERVIEW
13939: 
13940: lonnet provides subroutines which interact with the
13941: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13942: about classes, users, and resources.
13943: 
13944: For many of these objects you can also use this to store data about
13945: them or modify them in various ways.
13946: 
13947: =head2 Symbs
13948: 
13949: To identify a specific instance of a resource, LON-CAPA uses symbols
13950: or "symbs"X<symb>. These identifiers are built from the URL of the
13951: map, the resource number of the resource in the map, and the URL of
13952: the resource itself. The latter is somewhat redundant, but might help
13953: if maps change.
13954: 
13955: An example is
13956: 
13957:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13958: 
13959: The respective map entry is
13960: 
13961:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
13962:   title="Problem 2">
13963:  </resource>
13964: 
13965: Symbs are used by the random number generator, as well as to store and
13966: restore data specific to a certain instance of for example a problem.
13967: 
13968: =head2 Storing And Retrieving Data
13969: 
13970: X<store()>X<cstore()>X<restore()>Three of the most important functions
13971: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13972: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13973: is is the non-critical message twin of cstore. These functions are for
13974: handlers to store a perl hash to a user's permanent data space in an
13975: easy manner, and to retrieve it again on another call. It is expected
13976: that a handler would use this once at the beginning to retrieve data,
13977: and then again once at the end to send only the new data back.
13978: 
13979: The data is stored in the user's data directory on the user's
13980: homeserver under the ID of the course.
13981: 
13982: The hash that is returned by restore will have all of the previous
13983: value for all of the elements of the hash.
13984: 
13985: Example:
13986: 
13987:  #creating a hash
13988:  my %hash;
13989:  $hash{'foo'}='bar';
13990: 
13991:  #storing it
13992:  &Apache::lonnet::cstore(\%hash);
13993: 
13994:  #changing a value
13995:  $hash{'foo'}='notbar';
13996: 
13997:  #adding a new value
13998:  $hash{'bar'}='foo';
13999:  &Apache::lonnet::cstore(\%hash);
14000: 
14001:  #retrieving the hash
14002:  my %history=&Apache::lonnet::restore();
14003: 
14004:  #print the hash
14005:  foreach my $key (sort(keys(%history))) {
14006:    print("\%history{$key} = $history{$key}");
14007:  }
14008: 
14009: Will print out:
14010: 
14011:  %history{1:foo} = bar
14012:  %history{1:keys} = foo:timestamp
14013:  %history{1:timestamp} = 990455579
14014:  %history{2:bar} = foo
14015:  %history{2:foo} = notbar
14016:  %history{2:keys} = foo:bar:timestamp
14017:  %history{2:timestamp} = 990455580
14018:  %history{bar} = foo
14019:  %history{foo} = notbar
14020:  %history{timestamp} = 990455580
14021:  %history{version} = 2
14022: 
14023: Note that the special hash entries C<keys>, C<version> and
14024: C<timestamp> were added to the hash. C<version> will be equal to the
14025: total number of versions of the data that have been stored. The
14026: C<timestamp> attribute will be the UNIX time the hash was
14027: stored. C<keys> is available in every historical section to list which
14028: keys were added or changed at a specific historical revision of a
14029: hash.
14030: 
14031: B<Warning>: do not store the hash that restore returns directly. This
14032: will cause a mess since it will restore the historical keys as if the
14033: were new keys. I.E. 1:foo will become 1:1:foo etc.
14034: 
14035: Calling convention:
14036: 
14037:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14038:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14039: 
14040: For more detailed information, see lonnet specific documentation.
14041: 
14042: =head1 RETURN MESSAGES
14043: 
14044: =over 4
14045: 
14046: =item * B<con_lost>: unable to contact remote host
14047: 
14048: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14049: when the connection is brought back up
14050: 
14051: =item * B<con_failed>: unable to contact remote host and unable to save message
14052: for later delivery
14053: 
14054: =item * B<error:>: an error a occurred, a description of the error follows the :
14055: 
14056: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14057: that was requested
14058: 
14059: =back
14060: 
14061: =head1 PUBLIC SUBROUTINES
14062: 
14063: =head2 Session Environment Functions
14064: 
14065: =over 4
14066: 
14067: =item * 
14068: X<appenv()>
14069: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14070: the user envirnoment file, and will be restored for each access this
14071: user makes during this session, also modifies the %env for the current
14072: process. Optional rolesarrayref - if defined contains a reference to an array
14073: of roles which are exempt from the restriction on modifying user.role entries 
14074: in the user's environment.db and in %env.    
14075: 
14076: =item *
14077: X<delenv()>
14078: B<delenv($delthis,$regexp)>: removes all items from the session
14079: environment file that begin with $delthis. If the 
14080: optional second arg - $regexp - is true, $delthis is treated as a 
14081: regular expression, otherwise \Q$delthis\E is used. 
14082: The values are also deleted from the current processes %env.
14083: 
14084: =item * get_env_multiple($name) 
14085: 
14086: gets $name from the %env hash, it seemlessly handles the cases where multiple
14087: values may be defined and end up as an array ref.
14088: 
14089: returns an array of values
14090: 
14091: =back
14092: 
14093: =head2 User Information
14094: 
14095: =over 4
14096: 
14097: =item *
14098: X<queryauthenticate()>
14099: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14100: authentication scheme
14101: 
14102: =item *
14103: X<authenticate()>
14104: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14105: authenticate user from domain's lib servers (first use the current
14106: one). C<$upass> should be the users password.
14107: $checkdefauth is optional (value is 1 if a check should be made to
14108:    authenticate user using default authentication method, and allow
14109:    account creation if username does not have account in the domain).
14110: $clientcancheckhost is optional (value is 1 if checking whether the
14111:    server can host will occur on the client side in lonauth.pm).   
14112: 
14113: =item *
14114: X<homeserver()>
14115: B<homeserver($uname,$udom)>: find the server which has
14116: the user's directory and files (there must be only one), this caches
14117: the answer, and also caches if there is a borken connection.
14118: 
14119: =item *
14120: X<idget()>
14121: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14122: a list of student/employee IDs or clicker IDs
14123: (student/employee IDs are a unique resource in a domain, there must be 
14124: only 1 ID per username, and only 1 username per ID in a specific domain).
14125: clickerIDs are not necessarily unique, as students might share clickers.
14126: (returns hash: id=>name,id=>name)
14127: 
14128: =item *
14129: X<idrget()>
14130: B<idrget($udom,@unames)>: find the IDs behind a list of
14131: usernames (returns hash: name=>id,name=>id)
14132: 
14133: =item *
14134: X<idput()>
14135: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14136: names and associated student/employee IDs or clicker IDs.
14137: 
14138: =item *
14139: X<iddel()>
14140: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14141: student/employee ID or clicker ID username look-ups from domain.
14142: The homeserver ($uhome) and namespace ($namespace) are optional.
14143: If no $uhome is provided, it will be determined usig &homeserver()
14144: for each user.  If no $namespace is provided, the default is ids.
14145: 
14146: =item *
14147: X<updateclickers()>
14148: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14149: clicker ID-to-username look-ups in clickers.db on library server.
14150: Permitted actions are add or del (i.e., add or delete). The 
14151: clickers.db contains clickerID as keys (escaped), and each corresponding
14152: value is an escaped comma-separated list of usernames (for whom the
14153: library server is the homeserver), who registered that particular ID.
14154: If $critical is true, the update will be sent via &critical, otherwise
14155: &reply() will be used.
14156: 
14157: =item *
14158: X<rolesinit()>
14159: B<rolesinit($udom,$username)>: get user privileges.
14160: returns user role, first access and timer interval hashes
14161: 
14162: =item *
14163: X<privileged()>
14164: B<privileged($username,$domain)>: returns a true if user has a
14165: privileged and active role (i.e. su or dc), false otherwise.
14166: 
14167: =item *
14168: X<getsection()>
14169: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14170: course $cname, return section name/number or '' for "not in course"
14171: and '-1' for "no section"
14172: 
14173: =item *
14174: X<userenvironment()>
14175: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14176: passed in @what from the requested user's environment, returns a hash
14177: 
14178: =item * 
14179: X<userlog_query()>
14180: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14181: activity.log file. %filters defines filters applied when parsing the
14182: log file. These can be start or end timestamps, or the type of action
14183: - log to look for Login or Logout events, check for Checkin or
14184: Checkout, role for role selection. The response is in the form
14185: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14186: escaped strings of the action recorded in the activity.log file.
14187: 
14188: =back
14189: 
14190: =head2 User Roles
14191: 
14192: =over 4
14193: 
14194: =item *
14195: 
14196: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14197: returns codes for allowed actions.
14198: 
14199: The first argument is required, all others are optional.
14200: 
14201: $priv is the privilege being checked.
14202: $uri contains additional information about what is being checked for access (e.g.,
14203: URL, course ID etc.). 
14204: $symb is the unique resource instance identifier in a course; if needed,
14205: but not provided, it will be retrieved via a call to &symbread(). 
14206: $role is the role for which a priv is being checked (only used if priv is evb). 
14207: $clientip is the user's IP address (only used when checking for access to portfolio 
14208: files).
14209: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14210: prevents recursive calls to &allowed.
14211: 
14212:  F: full access
14213:  U,I,K: authentication modes (cxx only)
14214:  '': forbidden
14215:  1: user needs to choose course
14216:  2: browse allowed
14217:  A: passphrase authentication needed
14218:  B: access temporarily blocked because of a blocking event in a course.
14219: 
14220: =item *
14221: 
14222: constructaccess($url,$setpriv) : check for access to construction space URL
14223: 
14224: See if the owner domain and name in the URL match those in the
14225: expected environment.  If so, return three element list
14226: ($ownername,$ownerdomain,$ownerhome).
14227: 
14228: Otherwise return the null string.
14229: 
14230: If second argument 'setpriv' is true, it assigns the privileges,
14231: and returns the same three element list, unless the owner has
14232: blocked "ad hoc" Domain Coordinator access to the Author Space,
14233: in which case the null string is returned.
14234: 
14235: =item *
14236: 
14237: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14238: define a custom role rolename set privileges in format of lonTabs/roles.tab
14239: for system, domain, and course level. $uname and $udom are optional (current
14240: user's username and domain will be used when either of $uname or $udom are absent.
14241: 
14242: =item *
14243: 
14244: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14245: (rolesplain.tab); plain text explanation of a user role term.
14246: $type is Course (default) or Community.
14247: If $forcedefault evaluates to true, text returned will be default 
14248: text for $type. Otherwise, if this is a course, the text returned 
14249: will be a custom name for the role (if defined in the course's 
14250: environment).  If no custom name is defined the default is returned.
14251:    
14252: =item *
14253: 
14254: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14255: All arguments are optional. Returns a hash of a roles, either for
14256: co-author/assistant author roles for a user's Construction Space
14257: (default), or if $context is 'userroles', roles for the user himself,
14258: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14259: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14260: For each key, value is set to colon-separated start and end times for
14261: the role.  If no username and domain are specified, will default to
14262: current user/domain. Types, roles, and roledoms are references to arrays
14263: of role statuses (active, future or previous), roles 
14264: (e.g., cc,in, st etc.) and domains of the roles which can be used
14265: to restrict the list of roles reported. If no array ref is 
14266: provided for types, will default to return only active roles.
14267: 
14268: =item *
14269: 
14270: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14271: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14272: 
14273: Additional optional arguments are: $type (if role checking is to be restricted 
14274: to certain user status types -- previous (expired roles), active (currently
14275: available roles) or future (roles available in the future), and
14276: $hideprivileged -- if true will not report course roles for users who
14277: have active Domain Coordinator role in course's domain or in additional
14278: domains (specified in 'Domains to check for privileged users' in course
14279: environment -- set via:  Course Settings -> Classlists and staff listing).
14280: 
14281: =item *
14282: 
14283: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14284: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14285: $possdomains and $possroles are optional array refs -- to domains to check and
14286: roles to check.  If $possdomains is not specified, a dump will be done of the
14287: users' roles.db to check for a dc or su role in any domain. This can be
14288: time consuming if &privileged is called repeatedly (e.g., when displaying a
14289: classlist), so in such cases, supplying a $possdomains array is preferred, as
14290: this then allows &privileged_by_domain() to be used, which caches the identity
14291: of privileged users, eliminating the need for repeated calls to &dump().
14292: 
14293: =item *
14294: 
14295: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14296: where the outer hash keys are domains specified in the $possdomains array ref,
14297: next inner hash keys are privileged roles specified in the $roles array ref,
14298: and the innermost hash contains key = value pairs for username:domain = end:start
14299: for active or future "privileged" users with that role in that domain. To avoid
14300: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14301: innerhash are cached using priv_$role and $dom as the identifiers.
14302: 
14303: =back
14304: 
14305: =head2 User Modification
14306: 
14307: =over 4
14308: 
14309: =item *
14310: 
14311: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14312: user for the level given by URL.  Optional start and end dates (leave empty
14313: string or zero for "no date")
14314: 
14315: =item *
14316: 
14317: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14318: change a users, password, possible return values are: ok,
14319: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14320: refused
14321: 
14322: =item *
14323: 
14324: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14325: 
14326: =item *
14327: 
14328: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14329:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14330: 
14331: will update user information (firstname,middlename,lastname,generation,
14332: permanentemail), and if forceid is true, student/employee ID also.
14333: A user's institutional affiliation(s) can also be updated.
14334: User information fields will not be overwritten with empty entries 
14335: unless the field is included in the $candelete array reference.
14336: This array is included when a single user is modified via "Manage Users",
14337: or when Autoupdate.pl is run by cron in a domain.
14338: 
14339: =item *
14340: 
14341: modifystudent
14342: 
14343: modify a student's enrollment and identification information.
14344: The course id is resolved based on the current user's environment.  
14345: This means the invoking user must be a course coordinator or otherwise
14346: associated with a course.
14347: 
14348: This call is essentially a wrapper for lonnet::modifyuser and
14349: lonnet::modify_student_enrollment
14350: 
14351: Inputs: 
14352: 
14353: =over 4
14354: 
14355: =item B<$udom> Student's loncapa domain
14356: 
14357: =item B<$uname> Student's loncapa login name
14358: 
14359: =item B<$uid> Student/Employee ID
14360: 
14361: =item B<$umode> Student's authentication mode
14362: 
14363: =item B<$upass> Student's password
14364: 
14365: =item B<$first> Student's first name
14366: 
14367: =item B<$middle> Student's middle name
14368: 
14369: =item B<$last> Student's last name
14370: 
14371: =item B<$gene> Student's generation
14372: 
14373: =item B<$usec> Student's section in course
14374: 
14375: =item B<$end> Unix time of the roles expiration
14376: 
14377: =item B<$start> Unix time of the roles start date
14378: 
14379: =item B<$forceid> If defined, allow $uid to be changed
14380: 
14381: =item B<$desiredhome> server to use as home server for student
14382: 
14383: =item B<$email> Student's permanent e-mail address
14384: 
14385: =item B<$type> Type of enrollment (auto or manual)
14386: 
14387: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14388: 
14389: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14390: 
14391: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14392: 
14393: =item B<$context> role change context (shown in User Management Logs display in a course)
14394: 
14395: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14396: 
14397: =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.
14398: 
14399: =back
14400: 
14401: =item *
14402: 
14403: modify_student_enrollment
14404: 
14405: Change a student's enrollment status in a class.  The environment variable
14406: 'role.request.course' must be defined for this function to proceed.
14407: 
14408: Inputs:
14409: 
14410: =over 4
14411: 
14412: =item $udom, student's domain
14413: 
14414: =item $uname, student's name
14415: 
14416: =item $uid, student's user id
14417: 
14418: =item $first, student's first name
14419: 
14420: =item $middle
14421: 
14422: =item $last
14423: 
14424: =item $gene
14425: 
14426: =item $usec
14427: 
14428: =item $end
14429: 
14430: =item $start
14431: 
14432: =item $type
14433: 
14434: =item $locktype
14435: 
14436: =item $cid
14437: 
14438: =item $selfenroll
14439: 
14440: =item $context
14441: 
14442: =item $credits, number of credits student will earn from this class
14443: 
14444: =item $instsec, institutional course section code for student
14445: 
14446: =back
14447: 
14448: 
14449: =item *
14450: 
14451: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14452: custom role; give a custom role to a user for the level given by URL.  Specify
14453: name and domain of role author, and role name
14454: 
14455: =item *
14456: 
14457: revokerole($udom,$uname,$url,$role) : revoke a role for url
14458: 
14459: =item *
14460: 
14461: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14462: 
14463: =back
14464: 
14465: =head2 Course Infomation
14466: 
14467: =over 4
14468: 
14469: =item *
14470: 
14471: coursedescription($courseid,$options) : returns a hash of information about the
14472: specified course id, including all environment settings for the
14473: course, the description of the course will be in the hash under the
14474: key 'description'
14475: 
14476: $options is an optional parameter that if supplied is a hash reference that controls
14477: what how this function works.  It has the following key/values:
14478: 
14479: =over 4
14480: 
14481: =item freshen_cache
14482: 
14483: If defined, and the environment cache for the course is valid, it is 
14484: returned in the returned hash.
14485: 
14486: =item one_time
14487: 
14488: If defined, the last cache time is set to _now_
14489: 
14490: =item user
14491: 
14492: If defined, the supplied username is used instead of the current user.
14493: 
14494: 
14495: =back
14496: 
14497: =item *
14498: 
14499: resdata($name,$domain,$type,@which) : request for current parameter
14500: setting for a specific $type, where $type is either 'course' or 'user',
14501: @what should be a list of parameters to ask about. This routine caches
14502: answers for 10 minutes.
14503: 
14504: =item *
14505: 
14506: get_courseresdata($courseid, $domain) : dump the entire course resource
14507: data base, returning a hash that is keyed by the resource name and has
14508: values that are the resource value.  I believe that the timestamps and
14509: versions are also returned.
14510: 
14511: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14512: supplemental content area. This routine caches the number of files for 
14513: 10 minutes.
14514: 
14515: =back
14516: 
14517: =head2 Course Modification
14518: 
14519: =over 4
14520: 
14521: =item *
14522: 
14523: writecoursepref($courseid,%prefs) : write preferences (environment
14524: database) for a course
14525: 
14526: =item *
14527: 
14528: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14529: 
14530: =item *
14531: 
14532: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14533: 
14534: =item *
14535: 
14536: is_course($courseid), is_course($cdom, $cnum)
14537: 
14538: Accepts either a combined $courseid (in the form of domain_courseid) or the
14539: two component version $cdom, $cnum. It checks if the specified course exists.
14540: 
14541: Returns:
14542:     undef if the course doesn't exist, otherwise
14543:     in scalar context the combined courseid.
14544:     in list context the two components of the course identifier, domain and 
14545:     courseid.    
14546: 
14547: =back
14548: 
14549: =head2 Resource Subroutines
14550: 
14551: =over 4
14552: 
14553: =item *
14554: 
14555: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14556: 
14557: =item *
14558: 
14559: repcopy($filename) : subscribes to the requested file, and attempts to
14560: replicate from the owning library server, Might return
14561: 'unavailable', 'not_found', 'forbidden', 'ok', or
14562: 'bad_request', also attempts to grab the metadata for the
14563: resource. Expects the local filesystem pathname
14564: (/home/httpd/html/res/....)
14565: 
14566: =back
14567: 
14568: =head2 Resource Information
14569: 
14570: =over 4
14571: 
14572: =item *
14573: 
14574: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14575: and returns the value of a variety of different possible values,
14576: $varname should be a request string, and the other parameters can be
14577: used to specify who and what one is asking about. Ordinarily, $cid 
14578: does not need to be specified, as it is retrived from 
14579: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14580: within lonuserstate::loadmap() when initializing a course, before
14581: $env{'request.course.id'} has been set, so it needs to be provided
14582: in that one case.
14583: 
14584: Possible values for $varname are environment.lastname (or other item
14585: from the envirnment hash), user.name (or someother aspect about the
14586: user), resource.0.maxtries (or some other part and parameter of a
14587: resource)
14588: 
14589: =item *
14590: 
14591: directcondval($number) : get current value of a condition; reads from a state
14592: string
14593: 
14594: =item *
14595: 
14596: condval($condidx) : value of condition index based on state
14597: 
14598: =item *
14599: 
14600: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14601: resource's metadata, $what should be either a specific key, or either
14602: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14603: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14604: 
14605: this function automatically caches all requests
14606: 
14607: =item *
14608: 
14609: metadata_query($query,$custom,$customshow) : make a metadata query against the
14610: network of library servers; returns file handle of where SQL and regex results
14611: will be stored for query
14612: 
14613: =item *
14614: 
14615: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
14616: return symbolic list entry (all arguments optional). 
14617: 
14618: Args: filename is the filename (including path) for the file for which a symb 
14619: is required; donotrecurse, if true will prevent calls to allowed() being made 
14620: to check access status if more than one resource was found in the bighash 
14621: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
14622: a randompick); ignorecachednull, if true will prevent a symb of '' being 
14623: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14624: cause possible symbs to be checked to determine if they are subject to content
14625: blocking, if so they will not be included as possible symbs; possibles is a
14626: ref to a hash, which, as a side effect, will be populated with all possible 
14627: symbs (content blocking not tested).
14628:  
14629: returns the data handle
14630: 
14631: =item *
14632: 
14633: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14634: and is a possible symb for the URL in $thisfn, and if is an encrypted
14635: resource that the user accessed using /enc/ returns a 1 on success, 0
14636: on failure, user must be in a course, as it assumes the existence of
14637: the course initial hash, and uses $env('request.course.id'}.  The third
14638: arg is an optional reference to a scalar.  If this arg is passed in the 
14639: call to symbverify, it will be set to 1 if the symb has been set to be 
14640: encrypted; otherwise it will be null.  
14641: 
14642: =item *
14643: 
14644: symbclean($symb) : removes versions numbers from a symb, returns the
14645: cleaned symb
14646: 
14647: =item *
14648: 
14649: is_on_map($uri) : checks if the $uri is somewhere on the current
14650: course map, user must be in a course for it to work.
14651: 
14652: =item *
14653: 
14654: numval($salt) : return random seed value (addend for rndseed)
14655: 
14656: =item *
14657: 
14658: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14659: a random seed, all arguments are optional, if they aren't sent it uses the
14660: environment to derive them. Note: if symb isn't sent and it can't get one
14661: from &symbread it will use the current time as its return value
14662: 
14663: =item *
14664: 
14665: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14666: unfakeable, receipt
14667: 
14668: =item *
14669: 
14670: receipt() : API to ireceipt working off of env values; given out to users
14671: 
14672: =item *
14673: 
14674: countacc($url) : count the number of accesses to a given URL
14675: 
14676: =item *
14677: 
14678: 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
14679: 
14680: =item *
14681: 
14682: 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)
14683: 
14684: =item *
14685: 
14686: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
14687: 
14688: =item *
14689: 
14690: devalidate($symb) : devalidate temporary spreadsheet calculations,
14691: forcing spreadsheet to reevaluate the resource scores next time.
14692: 
14693: =item * 
14694: 
14695: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14696: when viewing in course context.
14697: 
14698:  input: six args -- filename (decluttered), course number, course domain,
14699:                     url, symb (if registered) and group (if this is a 
14700:                     group item -- e.g., bulletin board, group page etc.).
14701: 
14702:  output: array of five scalars --
14703:          $cfile -- url for file editing if editable on current server
14704:          $home -- homeserver of resource (i.e., for author if published,
14705:                                           or course if uploaded.).
14706:          $switchserver --  1 if server switch will be needed.
14707:          $forceedit -- 1 if icon/link should be to go to edit mode 
14708:          $forceview -- 1 if icon/link should be to go to view mode
14709: 
14710: =item *
14711: 
14712: is_course_upload($file,$cnum,$cdom)
14713: 
14714: Used in course context to determine if current file was uploaded to 
14715: the course (i.e., would be found in /userfiles/docs on the course's 
14716: homeserver.
14717: 
14718:   input: 3 args -- filename (decluttered), course number and course domain.
14719:   output: boolean -- 1 if file was uploaded.
14720: 
14721: =back
14722: 
14723: =head2 Storing/Retreiving Data
14724: 
14725: =over 4
14726: 
14727: =item *
14728: 
14729: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14730: permanently for this url; hashref needs to be given and should be a \%hashname;
14731: the remaining args aren't required and if they aren't passed or are '' they will
14732: be derived from the env (with the exception of $laststore, which is an 
14733: optional arg used when a user's submission is stored in grading).
14734: $laststore is $version=$timestamp, where $version is the most recent version
14735: number retrieved for the corresponding $symb in the $namespace db file, and
14736: $timestamp is the timestamp for that transaction (UNIX time).
14737: $laststore is currently only passed when cstore() is called by 
14738: structuretags::finalize_storage().
14739: 
14740: =item *
14741: 
14742: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14743: but uses critical subroutine
14744: 
14745: =item *
14746: 
14747: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14748: all args are optional
14749: 
14750: =item *
14751: 
14752: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
14753: dumps the complete (or key matching regexp) namespace into a hash
14754: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14755: normally &store()ed into
14756: 
14757: $range should be either an integer '100' (give me the first 100
14758:                                            matching records)
14759:               or be  two integers sperated by a - with no spaces
14760:                  '30-50' (give me the 30th through the 50th matching
14761:                           records)
14762: 
14763: 
14764: =item *
14765: 
14766: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
14767: replaces a &store() version of data with a replacement set of data
14768: for a particular resource in a namespace passed in the $storehash hash 
14769: reference. If $tolog is true, the transaction is logged in the courselog
14770: with an action=PUTSTORE.
14771: 
14772: =item *
14773: 
14774: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14775: works very similar to store/cstore, but all data is stored in a
14776: temporary location and can be reset using tmpreset, $storehash should
14777: be a hash reference, returns nothing on success
14778: 
14779: =item *
14780: 
14781: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14782: similar to restore, but all data is stored in a temporary location and
14783: can be reset using tmpreset. Returns a hash of values on success,
14784: error string otherwise.
14785: 
14786: =item *
14787: 
14788: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14789: deltes all keys for $symb form the temporary storage hash.
14790: 
14791: =item *
14792: 
14793: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14794: reference filled in from namesp ($udom and $uname are optional)
14795: 
14796: =item *
14797: 
14798: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14799: namesp ($udom and $uname are optional)
14800: 
14801: =item *
14802: 
14803: dump($namespace,$udom,$uname,$regexp,$range) : 
14804: dumps the complete (or key matching regexp) namespace into a hash
14805: ($udom, $uname, $regexp, $range are optional)
14806: 
14807: $range should be either an integer '100' (give me the first 100
14808:                                            matching records)
14809:               or be  two integers sperated by a - with no spaces
14810:                  '30-50' (give me the 30th through the 50th matching
14811:                           records)
14812: =item *
14813: 
14814: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14815: $store can be a scalar, an array reference, or if the amount to be 
14816: incremented is > 1, a hash reference.
14817: 
14818: ($udom and $uname are optional)
14819: 
14820: =item *
14821: 
14822: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14823: ($udom and $uname are optional)
14824: 
14825: =item *
14826: 
14827: cput($namespace,$storehash,$udom,$uname) : critical put
14828: ($udom and $uname are optional)
14829: 
14830: =item *
14831: 
14832: newput($namespace,$storehash,$udom,$uname) :
14833: 
14834: Attempts to store the items in the $storehash, but only if they don't
14835: currently exist, if this succeeds you can be certain that you have 
14836: successfully created a new key value pair in the $namespace db.
14837: 
14838: 
14839: Args:
14840:  $namespace: name of database to store values to
14841:  $storehash: hashref to store to the db
14842:  $udom: (optional) domain of user containing the db
14843:  $uname: (optional) name of user caontaining the db
14844: 
14845: Returns:
14846:  'ok' -> succeeded in storing all keys of $storehash
14847:  'key_exists: <key>' -> failed to anything out of $storehash, as at
14848:                         least <key> already existed in the db (other
14849:                         requested keys may also already exist)
14850:  'error: <msg>' -> unable to tie the DB or other error occurred
14851:  'con_lost' -> unable to contact request server
14852:  'refused' -> action was not allowed by remote machine
14853: 
14854: 
14855: =item *
14856: 
14857: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14858: reference filled in from namesp (encrypts the return communication)
14859: ($udom and $uname are optional)
14860: 
14861: =item *
14862: 
14863: log($udom,$name,$home,$message) : write to permanent log for user; use
14864: critical subroutine
14865: 
14866: =item *
14867: 
14868: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14869: array reference filled in from namespace found in domain level on either
14870: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
14871: 
14872: =item *
14873: 
14874: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
14875: domain level either on specified domain server ($uhome) or primary domain 
14876: server ($udom and $uhome are optional)
14877: 
14878: =item * 
14879: 
14880: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
14881: for: authentication, language, quotas, timezone, date locale, and portal URL in
14882: the target domain.
14883: 
14884: May also include additional key => value pairs for the following groups:
14885: 
14886: =over
14887: 
14888: =item
14889: disk quotas (MB allocated by default to portfolios and authoring spaces).
14890: 
14891: =over
14892: 
14893: =item defaultquota, authorquota
14894: 
14895: =back
14896: 
14897: =item
14898: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14899: portfolio for users).
14900: 
14901: =over
14902: 
14903: =item
14904: aboutme, blog, webdav, portfolio
14905: 
14906: =back
14907: 
14908: =item
14909: requestcourses: ability to request courses, and how requests are processed.
14910: 
14911: =over
14912: 
14913: =item
14914: official, unofficial, community, textbook, placement
14915: 
14916: =back
14917: 
14918: =item
14919: inststatus: types of institutional affiliation, and order in which they are displayed.
14920: 
14921: =over
14922: 
14923: =item
14924: inststatustypes, inststatusorder, inststatusguest
14925: 
14926: =back
14927: 
14928: =item
14929: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14930: for course's uploaded content.
14931: 
14932: =over
14933: 
14934: =item
14935: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
14936: communityquota, textbookquota, placementquota
14937: 
14938: =back
14939: 
14940: =item
14941: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14942: on your servers.
14943: 
14944: =over
14945: 
14946: =item 
14947: remotesessions, hostedsessions
14948: 
14949: =back
14950: 
14951: =back
14952: 
14953: In cases where a domain coordinator has never used the "Set Domain Configuration"
14954: utility to create a configuration.db file on a domain's primary library server 
14955: only the following domain defaults: auth_def, auth_arg_def, lang_def
14956: -- corresponding values are authentication type (internal, krb4, krb5,
14957: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
14958: will be available. Values are retrieved from cache (if current), unless the
14959: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14960: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14961: 
14962: Typical usage:
14963: 
14964: %domdefaults = &get_domain_defaults($target_domain);
14965: 
14966: =back
14967: 
14968: =head2 Network Status Functions
14969: 
14970: =over 4
14971: 
14972: =item *
14973: 
14974: dirlist() : return directory list based on URI (first arg).
14975: 
14976: Inputs: 1 required, 5 optional.
14977: 
14978: =over
14979: 
14980: =item 
14981: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14982: 
14983: =item
14984: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
14985: 
14986: =item
14987: $username -  username of user/course to be listed. Extracted from $uri if absent. 
14988: 
14989: =item
14990: $getpropath - boolean: 1 if prepend path using &propath(). 
14991: 
14992: =item
14993: $getuserdir - boolean: 1 if prepend path for "userfiles".
14994: 
14995: =item 
14996: $alternateRoot - path to prepend in place of path from $uri.
14997: 
14998: =back
14999: 
15000: Returns: Array of up to two items.
15001: 
15002: =over
15003: 
15004: a reference to an array of files/subdirectories
15005: 
15006: =over
15007: 
15008: Each element in the array of files/subdirectories is a & separated list of
15009: item name and the result of running stat on the item.  If dirlist was requested
15010: for a file instead of a directory, the item name will be ''. For a directory 
15011: listing, if the item is a metadata file, the element will end &N&M 
15012: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15013: default copyright set (1).  
15014: 
15015: =back
15016: 
15017: a scalar containing error condition (if encountered).
15018: 
15019: =over
15020: 
15021: =item 
15022: no_host (no homeserver identified for $username:$domain).
15023: 
15024: =item 
15025: no_such_host (server contacted for listing not identified as valid host).
15026: 
15027: =item 
15028: con_lost (connection to remote server failed).
15029: 
15030: =item 
15031: refused (invalid $username:$domain received on lond side).
15032: 
15033: =item 
15034: no_such_dir (directory at specified path on lond side does not exist). 
15035: 
15036: =item 
15037: empty (directory at specified path on lond side is empty).
15038: 
15039: =over
15040: 
15041: This is currently not encountered because the &ls3, &ls2, 
15042: &ls (_handler) routines on the lond side do not filter out
15043: . and .. from a directory listing. 
15044: 
15045: =back
15046: 
15047: =back
15048: 
15049: =back
15050: 
15051: =item *
15052: 
15053: spareserver() : find server with least workload from spare.tab
15054: 
15055: 
15056: =item *
15057: 
15058: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15059: if there is no corresponding loncapa host.
15060: 
15061: =back
15062: 
15063: 
15064: =head2 Apache Request
15065: 
15066: =over 4
15067: 
15068: =item *
15069: 
15070: ssi($url,%hash) : server side include, does a complete request cycle on url to
15071: localhost, posts hash
15072: 
15073: =back
15074: 
15075: =head2 Data to String to Data
15076: 
15077: =over 4
15078: 
15079: =item *
15080: 
15081: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15082: and '&' separators, supports elements that are arrayrefs and hashrefs
15083: 
15084: =item *
15085: 
15086: hashref2str($hashref) : convert a hashref into a string complete with
15087: escaping and '=' and '&' separators, supports elements that are
15088: arrayrefs and hashrefs
15089: 
15090: =item *
15091: 
15092: arrayref2str($arrayref) : convert an arrayref into a string complete
15093: with escaping and '&' separators, supports elements that are arrayrefs
15094: and hashrefs
15095: 
15096: =item *
15097: 
15098: str2hash($string) : convert string to hash using unescaping and
15099: splitting on '=' and '&', supports elements that are arrayrefs and
15100: hashrefs
15101: 
15102: =item *
15103: 
15104: str2array($string) : convert string to hash using unescaping and
15105: splitting on '&', supports elements that are arrayrefs and hashrefs
15106: 
15107: =back
15108: 
15109: =head2 Logging Routines
15110: 
15111: 
15112: These routines allow one to make log messages in the lonnet.log and
15113: lonnet.perm logfiles.
15114: 
15115: =over 4
15116: 
15117: =item *
15118: 
15119: logtouch() : make sure the logfile, lonnet.log, exists
15120: 
15121: =item *
15122: 
15123: logthis() : append message to the normal lonnet.log file, it gets
15124: preiodically rolled over and deleted.
15125: 
15126: =item *
15127: 
15128: logperm() : append a permanent message to lonnet.perm.log, this log
15129: file never gets deleted by any automated portion of the system, only
15130: messages of critical importance should go in here.
15131: 
15132: 
15133: =back
15134: 
15135: =head2 General File Helper Routines
15136: 
15137: =over 4
15138: 
15139: =item *
15140: 
15141: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15142: (a) files in /uploaded
15143:   (i) If a local copy of the file exists - 
15144:       compares modification date of local copy with last-modified date for 
15145:       definitive version stored on home server for course. If local copy is 
15146:       stale, requests a new version from the home server and stores it. 
15147:       If the original has been removed from the home server, then local copy 
15148:       is unlinked.
15149:   (ii) If local copy does not exist -
15150:       requests the file from the home server and stores it. 
15151:   
15152:   If $caller is 'uploadrep':  
15153:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15154:     for request for files originally uploaded via DOCS. 
15155:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15156:   
15157:   Otherwise:
15158:      This indicates a call from the content generation phase of the request.
15159:      -  returns the entire contents of the file or -1.
15160:      
15161: (b) files in /res
15162:    - returns the entire contents of a file or -1; 
15163:    it properly subscribes to and replicates the file if neccessary.
15164: 
15165: 
15166: =item *
15167: 
15168: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15169:                   reference
15170: 
15171: returns either a stat() list of data about the file or an empty list
15172: if the file doesn't exist or couldn't find out about it (connection
15173: problems or user unknown)
15174: 
15175: =item *
15176: 
15177: filelocation($dir,$file) : returns file system location of a file
15178: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15179: directory that relative $file lookups are to looked in ($dir of /a/dir
15180: and a file of ../bob will become /a/bob)
15181: 
15182: =item *
15183: 
15184: hreflocation($dir,$file) : returns file system location or a URL; same as
15185: filelocation except for hrefs
15186: 
15187: =item *
15188: 
15189: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15190: also removes beginning /home/httpd/html unless /priv/ follows it.
15191: 
15192: =back
15193: 
15194: =head2 Usererfile file routines (/uploaded*)
15195: 
15196: =over 4
15197: 
15198: =item *
15199: 
15200: userfileupload(): main rotine for putting a file in a user or course's
15201:                   filespace, arguments are,
15202: 
15203:  formname - required - this is the name of the element in $env where the
15204:            filename, and the contents of the file to create/modifed exist
15205:            the filename is in $env{'form.'.$formname.'.filename'} and the
15206:            contents of the file is located in $env{'form.'.$formname}
15207:  context - if coursedoc, store the file in the course of the active role
15208:              of the current user; 
15209:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15210:            if 'canceloverwrite': delete file in tmp/overwrites directory
15211:  subdir - required - subdirectory to put the file in under ../userfiles/
15212:          if undefined, it will be placed in "unknown"
15213: 
15214:  (This routine calls clean_filename() to remove any dangerous
15215:  characters from the filename, and then calls finuserfileupload() to
15216:  complete the transaction)
15217: 
15218:  returns either the url of the uploaded file (/uploaded/....) if successful
15219:  and /adm/notfound.html if unsuccessful
15220: 
15221: =item *
15222: 
15223: clean_filename(): routine for cleaing a filename up for storage in
15224:                  userfile space, argument is:
15225: 
15226:  filename - proposed filename
15227: 
15228: returns: the new clean filename
15229: 
15230: =item *
15231: 
15232: finishuserfileupload(): routine that creates and sends the file to
15233: userspace, probably shouldn't be called directly
15234: 
15235:   docuname: username or courseid of destination for the file
15236:   docudom: domain of user/course of destination for the file
15237:   formname: same as for userfileupload()
15238:   fname: filename (including subdirectories) for the file
15239:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15240:   allfiles: reference to hash used to store objects found by parser
15241:   codebase: reference to hash used for codebases of java objects found by parser
15242:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15243:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15244:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15245:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15246:   context: if 'overwrite', will move the uploaded file from its temporary location to
15247:             userfiles to facilitate overwriting a previously uploaded file with same name.
15248:   mimetype: reference to scalar to accommodate mime type determined
15249:             from File::MMagic if $parser = parse.
15250: 
15251:  returns either the url of the uploaded file (/uploaded/....) if successful
15252:  and /adm/notfound.html if unsuccessful (or an error message if context 
15253:  was 'overwrite').
15254:  
15255: 
15256: =item *
15257: 
15258: renameuserfile(): renames an existing userfile to a new name
15259: 
15260:   Args:
15261:    docuname: username or courseid of destination for the file
15262:    docudom: domain of user/course of destination for the file
15263:    old: current file name (including any subdirs under userfiles)
15264:    new: desired file name (including any subdirs under userfiles)
15265: 
15266: =item *
15267: 
15268: mkdiruserfile(): creates a directory is a userfiles dir
15269: 
15270:   Args:
15271:    docuname: username or courseid of destination for the file
15272:    docudom: domain of user/course of destination for the file
15273:    dir: dir to create (including any subdirs under userfiles)
15274: 
15275: =item *
15276: 
15277: removeuserfile(): removes a file that exists in userfiles
15278: 
15279:   Args:
15280:    docuname: username or courseid of destination for the file
15281:    docudom: domain of user/course of destination for the file
15282:    fname: filname to delete (including any subdirs under userfiles)
15283: 
15284: =item *
15285: 
15286: removeuploadedurl(): convience function for removeuserfile()
15287: 
15288:   Args:
15289:    url:  a full /uploaded/... url to delete
15290: 
15291: =item * 
15292: 
15293: get_portfile_permissions():
15294:   Args:
15295:     domain: domain of user or course contain the portfolio files
15296:     user: name of user or num of course contain the portfolio files
15297:   Returns:
15298:     hashref of a dump of the proper file_permissions.db
15299:    
15300: 
15301: =item * 
15302: 
15303: get_access_controls():
15304: 
15305: Args:
15306:   current_permissions: the hash ref returned from get_portfile_permissions()
15307:   group: (optional) the group you want the files associated with
15308:   file: (optional) the file you want access info on
15309: 
15310: Returns:
15311:     a hash (keys are file names) of hashes containing
15312:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15313:         values are XML containing access control settings (see below) 
15314: 
15315: Internal notes:
15316: 
15317:  access controls are stored in file_permissions.db as key=value pairs.
15318:     key -> path to file/file_name\0uniqueID:scope_end_start
15319:         where scope -> public,guest,course,group,domains or users.
15320:               end -> UNIX time for end of access (0 -> no end date)
15321:               start -> UNIX time for start of access
15322: 
15323:     value -> XML description of access control
15324:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15325:             <start></start>
15326:             <end></end>
15327: 
15328:             <password></password>  for scope type = guest
15329: 
15330:             <domain></domain>     for scope type = course or group
15331:             <number></number>
15332:             <roles id="">
15333:              <role></role>
15334:              <access></access>
15335:              <section></section>
15336:              <group></group>
15337:             </roles>
15338: 
15339:             <dom></dom>         for scope type = domains
15340: 
15341:             <users>             for scope type = users
15342:              <user>
15343:               <uname></uname>
15344:               <udom></udom>
15345:              </user>
15346:             </users>
15347:            </scope> 
15348:               
15349:  Access data is also aggregated for each file in an additional key=value pair:
15350:  key -> path to file/file_name\0accesscontrol 
15351:  value -> reference to hash
15352:           hash contains key = value pairs
15353:           where key = uniqueID:scope_end_start
15354:                 value = UNIX time record was last updated
15355: 
15356:           Used to improve speed of look-ups of access controls for each file.  
15357:  
15358:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15359: 
15360: =item *
15361: 
15362: modify_access_controls():
15363: 
15364: Modifies access controls for a portfolio file
15365: Args
15366: 1. file name
15367: 2. reference to hash of required changes,
15368: 3. domain
15369: 4. username
15370:   where domain,username are the domain of the portfolio owner 
15371:   (either a user or a course) 
15372: 
15373: Returns:
15374: 1. result of additions or updates ('ok' or 'error', with error message). 
15375: 2. result of deletions ('ok' or 'error', with error message).
15376: 3. reference to hash of any new or updated access controls.
15377: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15378:    key = integer (inbound ID)
15379:    value = uniqueID
15380: 
15381: =item *
15382: 
15383: get_timebased_id():
15384: 
15385: Attempts to get a unique timestamp-based suffix for use with items added to a 
15386: course via the Course Editor (e.g., folders, composite pages, 
15387: group bulletin boards).
15388: 
15389: Args: (first three required; six others optional)
15390: 
15391: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15392:    docssequence, or name of group
15393: 
15394: 2. keyid (alphanumeric): name of temporary locking key in hash,
15395:    e.g., num, boardids
15396: 
15397: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15398:    file will be named nohist_namespace.db
15399: 
15400: 4. cdom: domain of course; default is current course domain from %env
15401: 
15402: 5. cnum: course number; default is current course number from %env
15403: 
15404: 6. idtype: set to concat if an additional digit is to be appended to the 
15405:    unix timestamp to form the suffix, if the plain timestamp is already
15406:    in use.  Default is to not do this, but simply increment the unix 
15407:    timestamp by 1 until a unique key is obtained.
15408: 
15409: 7. who: holder of locking key; defaults to user:domain for user.
15410: 
15411: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15412:    retrying); default is 3.
15413: 
15414: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15415: 
15416: Returns:
15417: 
15418: 1. suffix obtained (numeric)
15419: 
15420: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15421: 
15422: 3. error: contains (localized) error message if an error occurred.
15423: 
15424: 
15425: =back
15426: 
15427: =head2 HTTP Helper Routines
15428: 
15429: =over 4
15430: 
15431: =item *
15432: 
15433: escape() : unpack non-word characters into CGI-compatible hex codes
15434: 
15435: =item *
15436: 
15437: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15438: 
15439: =back
15440: 
15441: =head1 PRIVATE SUBROUTINES
15442: 
15443: =head2 Underlying communication routines (Shouldn't call)
15444: 
15445: =over 4
15446: 
15447: =item *
15448: 
15449: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15450: 
15451: =item *
15452: 
15453: reply() : uses subreply to send a message to remote machine, logs all failures
15454: 
15455: =item *
15456: 
15457: critical() : passes a critical message to another server; if cannot
15458: get through then place message in connection buffer directory and
15459: returns con_delayed, if incapable of saving message, returns
15460: con_failed
15461: 
15462: =item *
15463: 
15464: reconlonc() : tries to reconnect lonc client processes.
15465: 
15466: =back
15467: 
15468: =head2 Resource Access Logging
15469: 
15470: =over 4
15471: 
15472: =item *
15473: 
15474: flushcourselogs() : flush (save) buffer logs and access logs
15475: 
15476: =item *
15477: 
15478: courselog($what) : save message for course in hash
15479: 
15480: =item *
15481: 
15482: courseacclog($what) : save message for course using &courselog().  Perform
15483: special processing for specific resource types (problems, exams, quizzes, etc).
15484: 
15485: =item *
15486: 
15487: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15488: as a PerlChildExitHandler
15489: 
15490: =back
15491: 
15492: =head2 Other
15493: 
15494: =over 4
15495: 
15496: =item *
15497: 
15498: symblist($mapname,%newhash) : update symbolic storage links
15499: 
15500: =back
15501: 
15502: =cut
15503: 

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