File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1348: download - view: text, annotated - select for diffs
Tue Aug 8 15:33:13 2017 UTC (6 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Trust settings.
 - Use more versatile lonnet::will_trust() to determine if session-hosting
   server has catalalog access, according to domain's trust settings.
 - Eliminate lonnet::notcallable() -- no longer used.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1348 2017/08/08 15:33:13 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 trusted_domains {
 1602:     my ($cmdtype,$calldom) = @_;
 1603:     my (%trusted,%untrusted);
 1604:     if (&domain($calldom) eq '') {
 1605:         return (\%trusted,\%untrusted);
 1606:     }
 1607:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1608:         return (\%trusted,\%untrusted);
 1609:     }
 1610:     my $callprimary = &domain($calldom,'primary');
 1611:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1612:     if ($intcalldom eq '') {
 1613:         return (\%trusted,\%untrusted);
 1614:     }
 1615: 
 1616:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1617:     unless (defined($cached)) {
 1618:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1619:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1620:         $trustconfig = $domconfig{'trust'};
 1621:     }
 1622:     if (ref($trustconfig)) {
 1623:         my (%possexc,%possinc,@allexc,@allinc); 
 1624:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1625:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1626:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1627:             }
 1628:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1629:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1630:             }
 1631:         }
 1632:         if (keys(%possexc)) {
 1633:             if (keys(%possinc)) {
 1634:                 foreach my $key (sort(keys(%possexc))) {
 1635:                     next if ($key eq $intcalldom);
 1636:                     unless ($possinc{$key}) {
 1637:                         push(@allexc,$key);
 1638:                     }
 1639:                 }
 1640:             } else {
 1641:                 @allexc = sort(keys(%possexc));
 1642:             }
 1643:         }
 1644:         if (keys(%possinc)) {
 1645:             $possinc{$intcalldom} = 1;
 1646:             @allinc = sort(keys(%possinc));
 1647:         }
 1648:         if ((@allexc > 0) || (@allinc > 0)) {
 1649:             my %doms_by_intdom;
 1650:             my %allintdoms = &all_host_intdom();
 1651:             my %alldoms = &all_host_domain();
 1652:             foreach my $key (%allintdoms) {
 1653:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1654:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1655:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1656:                     }
 1657:                 } else {
 1658:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1659:                 }
 1660:             }
 1661:             foreach my $exc (@allexc) {
 1662:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1663:                     map { $untrusted{$_}; } @{$doms_by_intdom{$exc}};
 1664:                 }
 1665:             }
 1666:             foreach my $inc (@allinc) {
 1667:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1668:                     map { $trusted{$_}; } @{$doms_by_intdom{$inc}};
 1669:                 }
 1670:             }
 1671:         }
 1672:     }
 1673:     return(\%trusted,\%untrusted);
 1674: }
 1675: 
 1676: sub will_trust {
 1677:     my ($cmdtype,$domain,$possdom) = @_;
 1678:     return 1 if ($domain eq $possdom);
 1679:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1680:     my $willtrust; 
 1681:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1682:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1683:             $willtrust = 1;
 1684:         }
 1685:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1686:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1687:             $willtrust = 1;
 1688:         }
 1689:     } else {
 1690:         $willtrust = 1;
 1691:     }
 1692:     return $willtrust;
 1693: }
 1694: 
 1695: # ---------------------- Find the homebase for a user from domain's lib servers
 1696: 
 1697: my %homecache;
 1698: sub homeserver {
 1699:     my ($uname,$udom,$ignoreBadCache)=@_;
 1700:     my $index="$uname:$udom";
 1701: 
 1702:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1703: 
 1704:     my %servers = &get_servers($udom,'library');
 1705:     foreach my $tryserver (keys(%servers)) {
 1706:         next if ($ignoreBadCache ne 'true' && 
 1707: 		 exists($badServerCache{$tryserver}));
 1708: 
 1709: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1710: 	if ($answer eq 'found') {
 1711: 	    delete($badServerCache{$tryserver}); 
 1712: 	    return $homecache{$index}=$tryserver;
 1713: 	} elsif ($answer eq 'no_host') {
 1714: 	    $badServerCache{$tryserver}=1;
 1715: 	}
 1716:     }    
 1717:     return 'no_host';
 1718: }
 1719: 
 1720: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1721: 
 1722: sub idget {
 1723:     my ($udom,$idsref,$namespace)=@_;
 1724:     my %returnhash=();
 1725:     my @ids=(); 
 1726:     if (ref($idsref) eq 'ARRAY') {
 1727:         @ids = @{$idsref};
 1728:     } else {
 1729:         return %returnhash; 
 1730:     }
 1731:     if ($namespace eq '') {
 1732:         $namespace = 'ids';
 1733:     }
 1734:     
 1735:     my %servers = &get_servers($udom,'library');
 1736:     foreach my $tryserver (keys(%servers)) {
 1737: 	my $idlist=join('&', map { &escape($_); } @ids);
 1738: 	if ($namespace eq 'ids') {
 1739: 	    $idlist=~tr/A-Z/a-z/;
 1740: 	}
 1741: 	my $reply;
 1742: 	if ($namespace eq 'ids') {
 1743: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1744: 	} else {
 1745: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1746: 	}
 1747: 	my @answer=();
 1748: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1749: 	    @answer=split(/\&/,$reply);
 1750: 	}                    ;
 1751: 	my $i;
 1752: 	for ($i=0;$i<=$#ids;$i++) {
 1753: 	    if ($answer[$i]) {
 1754: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1755: 	    }
 1756: 	}
 1757:     }
 1758:     return %returnhash;
 1759: }
 1760: 
 1761: # ------------------------------------- Find the IDs behind a list of usernames
 1762: 
 1763: sub idrget {
 1764:     my ($udom,@unames)=@_;
 1765:     my %returnhash=();
 1766:     foreach my $uname (@unames) {
 1767:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1768:     }
 1769:     return %returnhash;
 1770: }
 1771: 
 1772: # Store away a list of names and associated student/employee IDs or clicker IDs
 1773: 
 1774: sub idput {
 1775:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1776:     my %servers=();
 1777:     my %ids=();
 1778:     my %byid = ();
 1779:     if (ref($idsref) eq 'HASH') {
 1780:         %ids=%{$idsref};
 1781:     }
 1782:     if ($namespace eq '') {
 1783:         $namespace = 'ids'; 
 1784:     }
 1785:     foreach my $uname (keys(%ids)) {
 1786: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1787:         if ($uhom eq '') {
 1788:             $uhom=&homeserver($uname,$udom);
 1789:         }
 1790:         if ($uhom ne 'no_host') {
 1791:             my $esc_unam=&escape($uname);
 1792:             if ($namespace eq 'ids') {
 1793:                 my $id=&escape($ids{$uname});
 1794:                 $id=~tr/A-Z/a-z/;
 1795:                 my $esc_unam=&escape($uname);
 1796:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1797:             } else {
 1798:                 my @currids = split(/,/,$ids{$uname});
 1799:                 foreach my $id (@currids) {
 1800:                     $byid{$uhom}{$id} .= $uname.',';
 1801:                 }
 1802:             }
 1803:         }
 1804:     }
 1805:     if ($namespace eq 'clickers') {
 1806:         foreach my $server (keys(%byid)) {
 1807:             if (ref($byid{$server}) eq 'HASH') {
 1808:                 foreach my $id (keys(%{$byid{$server}})) {
 1809:                     $byid{$server} =~ s/,$//;
 1810:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1811:                 }
 1812:             }
 1813:         }
 1814:     }
 1815:     foreach my $server (keys(%servers)) {
 1816:         $servers{$server} =~ s/\&$//;
 1817:         if ($namespace eq 'ids') {     
 1818:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1819:         } else {
 1820:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1821:         }
 1822:     }
 1823: }
 1824: 
 1825: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1826: 
 1827: sub iddel {
 1828:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1829:     my %result=();
 1830:     my %ids=();
 1831:     my %byid = ();
 1832:     if (ref($idshashref) eq 'HASH') {
 1833:         %ids=%{$idshashref};
 1834:     } else {
 1835:         return %result;
 1836:     }
 1837:     if ($namespace eq '') {
 1838:         $namespace = 'ids';
 1839:     }
 1840:     my %servers=();
 1841:     while (my ($id,$unamestr) = each(%ids)) {
 1842:         if ($namespace eq 'ids') {
 1843:             my $uhom = $uhome;
 1844:             if ($uhom eq '') { 
 1845:                 $uhom=&homeserver($unamestr,$udom);
 1846:             }
 1847:             if ($uhom ne 'no_host') {
 1848:                 $servers{$uhom}.='&'.&escape($id);
 1849:             }
 1850:          } else {
 1851:             my @curritems = split(/,/,$ids{$id});
 1852:             foreach my $uname (@curritems) {
 1853:                 my $uhom = $uhome;
 1854:                 if ($uhom eq '') {
 1855:                     $uhom=&homeserver($uname,$udom);
 1856:                 }
 1857:                 if ($uhom ne 'no_host') { 
 1858:                     $byid{$uhom}{$id} .= $uname.',';
 1859:                 }
 1860:             }
 1861:         }
 1862:     }
 1863:     if ($namespace eq 'clickers') {
 1864:         foreach my $server (keys(%byid)) {
 1865:             if (ref($byid{$server}) eq 'HASH') {
 1866:                 foreach my $id (keys(%{$byid{$server}})) {
 1867:                     $byid{$server}{$id} =~ s/,$//;
 1868:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 1869:                 }
 1870:             }
 1871:         }
 1872:     }
 1873:     foreach my $server (keys(%servers)) {
 1874:         $servers{$server} =~ s/\&$//;
 1875:         if ($namespace eq 'ids') {
 1876:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1877:         } elsif ($namespace eq 'clickers') {
 1878:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 1879:         }
 1880:     }
 1881:     return %result;
 1882: }
 1883: 
 1884: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 1885: 
 1886: sub updateclickers {
 1887:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 1888:     my %clickers;
 1889:     if (ref($idshashref) eq 'HASH') {
 1890:         %clickers=%{$idshashref};
 1891:     } else {
 1892:         return;
 1893:     }
 1894:     my $items='';
 1895:     foreach my $item (keys(%clickers)) {
 1896:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 1897:     }
 1898:     $items=~s/\&$//;
 1899:     my $request = "updateclickers:$udom:$action:$items";
 1900:     if ($critical) {
 1901:         return &critical($request,$uhome);
 1902:     } else {
 1903:         return &reply($request,$uhome);
 1904:     }
 1905: }
 1906: 
 1907: # ------------------------------dump from db file owned by domainconfig user
 1908: sub dump_dom {
 1909:     my ($namespace, $udom, $regexp) = @_;
 1910: 
 1911:     $udom ||= $env{'user.domain'};
 1912: 
 1913:     return () unless $udom;
 1914: 
 1915:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1916: }
 1917: 
 1918: # ------------------------------------------ get items from domain db files   
 1919: 
 1920: sub get_dom {
 1921:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1922:     return if ($udom eq 'public');
 1923:     my $items='';
 1924:     foreach my $item (@$storearr) {
 1925:         $items.=&escape($item).'&';
 1926:     }
 1927:     $items=~s/\&$//;
 1928:     if (!$udom) {
 1929:         $udom=$env{'user.domain'};
 1930:         return if ($udom eq 'public');
 1931:         if (defined(&domain($udom,'primary'))) {
 1932:             $uhome=&domain($udom,'primary');
 1933:         } else {
 1934:             undef($uhome);
 1935:         }
 1936:     } else {
 1937:         if (!$uhome) {
 1938:             if (defined(&domain($udom,'primary'))) {
 1939:                 $uhome=&domain($udom,'primary');
 1940:             }
 1941:         }
 1942:     }
 1943:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1944:         my $rep;
 1945:         if ($namespace =~ /^enc/) {
 1946:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 1947:         } else {
 1948:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1949:         }
 1950:         my %returnhash;
 1951:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1952:             return %returnhash;
 1953:         }
 1954:         my @pairs=split(/\&/,$rep);
 1955:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1956:             return @pairs;
 1957:         }
 1958:         my $i=0;
 1959:         foreach my $item (@$storearr) {
 1960:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1961:             $i++;
 1962:         }
 1963:         return %returnhash;
 1964:     } else {
 1965:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1966:     }
 1967: }
 1968: 
 1969: # -------------------------------------------- put items in domain db files 
 1970: 
 1971: sub put_dom {
 1972:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1973:     if (!$udom) {
 1974:         $udom=$env{'user.domain'};
 1975:         if (defined(&domain($udom,'primary'))) {
 1976:             $uhome=&domain($udom,'primary');
 1977:         } else {
 1978:             undef($uhome);
 1979:         }
 1980:     } else {
 1981:         if (!$uhome) {
 1982:             if (defined(&domain($udom,'primary'))) {
 1983:                 $uhome=&domain($udom,'primary');
 1984:             }
 1985:         }
 1986:     } 
 1987:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1988:         my $items='';
 1989:         foreach my $item (keys(%$storehash)) {
 1990:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1991:         }
 1992:         $items=~s/\&$//;
 1993:         if ($namespace =~ /^enc/) {
 1994:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 1995:         } else {
 1996:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 1997:         }
 1998:     } else {
 1999:         &logthis("put_dom failed - no homeserver and/or domain");
 2000:     }
 2001: }
 2002: 
 2003: # --------------------- newput for items in db file owned by domainconfig user
 2004: sub newput_dom {
 2005:     my ($namespace,$storehash,$udom) = @_;
 2006:     my $result;
 2007:     if (!$udom) {
 2008:         $udom=$env{'user.domain'};
 2009:     }
 2010:     if ($udom) {
 2011:         my $uname = &get_domainconfiguser($udom);
 2012:         $result = &newput($namespace,$storehash,$udom,$uname);
 2013:     }
 2014:     return $result;
 2015: }
 2016: 
 2017: # --------------------- delete for items in db file owned by domainconfig user
 2018: sub del_dom {
 2019:     my ($namespace,$storearr,$udom)=@_;
 2020:     if (ref($storearr) eq 'ARRAY') {
 2021:         if (!$udom) {
 2022:             $udom=$env{'user.domain'};
 2023:         }
 2024:         if ($udom) {
 2025:             my $uname = &get_domainconfiguser($udom); 
 2026:             return &del($namespace,$storearr,$udom,$uname);
 2027:         }
 2028:     }
 2029: }
 2030: 
 2031: # ----------------------------------construct domainconfig user for a domain 
 2032: sub get_domainconfiguser {
 2033:     my ($udom) = @_;
 2034:     return $udom.'-domainconfig';
 2035: }
 2036: 
 2037: sub retrieve_inst_usertypes {
 2038:     my ($udom) = @_;
 2039:     my (%returnhash,@order);
 2040:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2041:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2042:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2043:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2044:     } else {
 2045:         if (defined(&domain($udom,'primary'))) {
 2046:             my $uhome=&domain($udom,'primary');
 2047:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2048:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2049:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2050:                 return (\%returnhash,\@order);
 2051:             }
 2052:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2053:             my @pairs=split(/\&/,$hashitems);
 2054:             foreach my $item (@pairs) {
 2055:                 my ($key,$value)=split(/=/,$item,2);
 2056:                 $key = &unescape($key);
 2057:                 next if ($key =~ /^error: 2 /);
 2058:                 $returnhash{$key}=&thaw_unescape($value);
 2059:             }
 2060:             my @esc_order = split(/\&/,$orderitems);
 2061:             foreach my $item (@esc_order) {
 2062:                 push(@order,&unescape($item));
 2063:             }
 2064:         } else {
 2065:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2066:         }
 2067:         return (\%returnhash,\@order);
 2068:     }
 2069: }
 2070: 
 2071: sub is_domainimage {
 2072:     my ($url) = @_;
 2073:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2074:         if (&domain($1) ne '') {
 2075:             return '1';
 2076:         }
 2077:     }
 2078:     return;
 2079: }
 2080: 
 2081: sub inst_directory_query {
 2082:     my ($srch) = @_;
 2083:     my $udom = $srch->{'srchdomain'};
 2084:     my %results;
 2085:     my $homeserver = &domain($udom,'primary');
 2086:     my $outcome;
 2087:     if ($homeserver ne '') {
 2088: 	my $queryid=&reply("querysend:instdirsearch:".
 2089: 			   &escape($srch->{'srchby'}).':'.
 2090: 			   &escape($srch->{'srchterm'}).':'.
 2091: 			   &escape($srch->{'srchtype'}),$homeserver);
 2092: 	my $host=&hostname($homeserver);
 2093: 	if ($queryid !~/^\Q$host\E\_/) {
 2094: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2095: 	    return;
 2096: 	}
 2097: 	my $response = &get_query_reply($queryid);
 2098: 	my $maxtries = 5;
 2099: 	my $tries = 1;
 2100: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2101: 	    $response = &get_query_reply($queryid);
 2102: 	    $tries ++;
 2103: 	}
 2104: 
 2105:         if (!&error($response) && $response ne 'refused') {
 2106:             if ($response eq 'unavailable') {
 2107:                 $outcome = $response;
 2108:             } else {
 2109:                 $outcome = 'ok';
 2110:                 my @matches = split(/\n/,$response);
 2111:                 foreach my $match (@matches) {
 2112:                     my ($key,$value) = split(/=/,$match);
 2113:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2114:                 }
 2115:             }
 2116:         }
 2117:     }
 2118:     return ($outcome,%results);
 2119: }
 2120: 
 2121: sub usersearch {
 2122:     my ($srch) = @_;
 2123:     my $dom = $srch->{'srchdomain'};
 2124:     my %results;
 2125:     my %libserv = &all_library();
 2126:     my $query = 'usersearch';
 2127:     foreach my $tryserver (keys(%libserv)) {
 2128:         if (&host_domain($tryserver) eq $dom) {
 2129:             my $host=&hostname($tryserver);
 2130:             my $queryid=
 2131:                 &reply("querysend:".&escape($query).':'.
 2132:                        &escape($srch->{'srchby'}).':'.
 2133:                        &escape($srch->{'srchtype'}).':'.
 2134:                        &escape($srch->{'srchterm'}),$tryserver);
 2135:             if ($queryid !~/^\Q$host\E\_/) {
 2136:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2137:                 next;
 2138:             }
 2139:             my $reply = &get_query_reply($queryid);
 2140:             my $maxtries = 1;
 2141:             my $tries = 1;
 2142:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2143:                 $reply = &get_query_reply($queryid);
 2144:                 $tries ++;
 2145:             }
 2146:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2147:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2148:             } else {
 2149:                 my @matches;
 2150:                 if ($reply =~ /\n/) {
 2151:                     @matches = split(/\n/,$reply);
 2152:                 } else {
 2153:                     @matches = split(/\&/,$reply);
 2154:                 }
 2155:                 foreach my $match (@matches) {
 2156:                     my ($uname,$udom,%userhash);
 2157:                     foreach my $entry (split(/:/,$match)) {
 2158:                         my ($key,$value) =
 2159:                             map {&unescape($_);} split(/=/,$entry);
 2160:                         $userhash{$key} = $value;
 2161:                         if ($key eq 'username') {
 2162:                             $uname = $value;
 2163:                         } elsif ($key eq 'domain') {
 2164:                             $udom = $value;
 2165:                         }
 2166:                     }
 2167:                     $results{$uname.':'.$udom} = \%userhash;
 2168:                 }
 2169:             }
 2170:         }
 2171:     }
 2172:     return %results;
 2173: }
 2174: 
 2175: sub get_instuser {
 2176:     my ($udom,$uname,$id) = @_;
 2177:     my $homeserver = &domain($udom,'primary');
 2178:     my ($outcome,%results);
 2179:     if ($homeserver ne '') {
 2180:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2181:                            &escape($id).':'.&escape($udom),$homeserver);
 2182:         my $host=&hostname($homeserver);
 2183:         if ($queryid !~/^\Q$host\E\_/) {
 2184:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2185:             return;
 2186:         }
 2187:         my $response = &get_query_reply($queryid);
 2188:         my $maxtries = 5;
 2189:         my $tries = 1;
 2190:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2191:             $response = &get_query_reply($queryid);
 2192:             $tries ++;
 2193:         }
 2194:         if (!&error($response) && $response ne 'refused') {
 2195:             if ($response eq 'unavailable') {
 2196:                 $outcome = $response;
 2197:             } else {
 2198:                 $outcome = 'ok';
 2199:                 my @matches = split(/\n/,$response);
 2200:                 foreach my $match (@matches) {
 2201:                     my ($key,$value) = split(/=/,$match);
 2202:                     $results{&unescape($key)} = &thaw_unescape($value);
 2203:                 }
 2204:             }
 2205:         }
 2206:     }
 2207:     my %userinfo;
 2208:     if (ref($results{$uname}) eq 'HASH') {
 2209:         %userinfo = %{$results{$uname}};
 2210:     } 
 2211:     return ($outcome,%userinfo);
 2212: }
 2213: 
 2214: sub get_multiple_instusers {
 2215:     my ($udom,$users,$caller) = @_;
 2216:     my ($outcome,$results);
 2217:     if (ref($users) eq 'HASH') {
 2218:         my $count = keys(%{$users}); 
 2219:         my $requested = &freeze_escape($users);
 2220:         my $homeserver = &domain($udom,'primary');
 2221:         if ($homeserver ne '') {
 2222:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2223:             my $host=&hostname($homeserver);
 2224:             if ($queryid !~/^\Q$host\E\_/) {
 2225:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2226:                          ' for host: '.$homeserver.'in domain '.$udom);
 2227:                 return ($outcome,$results);
 2228:             }
 2229:             my $response = &get_query_reply($queryid);
 2230:             my $maxtries = 5;
 2231:             if ($count > 100) {
 2232:                 $maxtries = 1+int($count/20);
 2233:             }
 2234:             my $tries = 1;
 2235:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2236:                 $response = &get_query_reply($queryid);
 2237:                 $tries ++;
 2238:             }
 2239:             if ($response eq '') {
 2240:                 $results = {};
 2241:                 foreach my $key (keys(%{$users})) {
 2242:                     my ($uname,$id);
 2243:                     if ($caller eq 'id') {
 2244:                         $id = $key;
 2245:                     } else {
 2246:                         $uname = $key;
 2247:                     }
 2248:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2249:                     $outcome = $resp;
 2250:                     if ($resp eq 'ok') {
 2251:                         %{$results} = (%{$results}, %info);
 2252:                     } else {
 2253:                         last;
 2254:                     }
 2255:                 }
 2256:             } elsif(!&error($response) && ($response ne 'refused')) {
 2257:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2258:                     $outcome = $response;
 2259:                 } else {
 2260:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2261:                     if ($outcome eq 'ok') {
 2262:                         $results = &thaw_unescape($userdata); 
 2263:                     }
 2264:                 }
 2265:             }
 2266:         }
 2267:     }
 2268:     return ($outcome,$results);
 2269: }
 2270: 
 2271: sub inst_rulecheck {
 2272:     my ($udom,$uname,$id,$item,$rules) = @_;
 2273:     my %returnhash;
 2274:     if ($udom ne '') {
 2275:         if (ref($rules) eq 'ARRAY') {
 2276:             @{$rules} = map {&escape($_);} (@{$rules});
 2277:             my $rulestr = join(':',@{$rules});
 2278:             my $homeserver=&domain($udom,'primary');
 2279:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2280:                 my $response;
 2281:                 if ($item eq 'username') {                
 2282:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2283:                                               ':'.&escape($uname).':'.$rulestr,
 2284:                                               $homeserver));
 2285:                 } elsif ($item eq 'id') {
 2286:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2287:                                               ':'.&escape($id).':'.$rulestr,
 2288:                                               $homeserver));
 2289:                 } elsif ($item eq 'selfcreate') {
 2290:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2291:                                                &escape($udom).':'.&escape($uname).
 2292:                                               ':'.$rulestr,$homeserver));
 2293:                 }
 2294:                 if ($response ne 'refused') {
 2295:                     my @pairs=split(/\&/,$response);
 2296:                     foreach my $item (@pairs) {
 2297:                         my ($key,$value)=split(/=/,$item,2);
 2298:                         $key = &unescape($key);
 2299:                         next if ($key =~ /^error: 2 /);
 2300:                         $returnhash{$key}=&thaw_unescape($value);
 2301:                     }
 2302:                 }
 2303:             }
 2304:         }
 2305:     }
 2306:     return %returnhash;
 2307: }
 2308: 
 2309: sub inst_userrules {
 2310:     my ($udom,$check) = @_;
 2311:     my (%ruleshash,@ruleorder);
 2312:     if ($udom ne '') {
 2313:         my $homeserver=&domain($udom,'primary');
 2314:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2315:             my $response;
 2316:             if ($check eq 'id') {
 2317:                 $response=&reply('instidrules:'.&escape($udom),
 2318:                                  $homeserver);
 2319:             } elsif ($check eq 'email') {
 2320:                 $response=&reply('instemailrules:'.&escape($udom),
 2321:                                  $homeserver);
 2322:             } else {
 2323:                 $response=&reply('instuserrules:'.&escape($udom),
 2324:                                  $homeserver);
 2325:             }
 2326:             if (($response ne 'refused') && ($response ne 'error') && 
 2327:                 ($response ne 'unknown_cmd') && 
 2328:                 ($response ne 'no_such_host')) {
 2329:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2330:                 my @pairs=split(/\&/,$hashitems);
 2331:                 foreach my $item (@pairs) {
 2332:                     my ($key,$value)=split(/=/,$item,2);
 2333:                     $key = &unescape($key);
 2334:                     next if ($key =~ /^error: 2 /);
 2335:                     $ruleshash{$key}=&thaw_unescape($value);
 2336:                 }
 2337:                 my @esc_order = split(/\&/,$orderitems);
 2338:                 foreach my $item (@esc_order) {
 2339:                     push(@ruleorder,&unescape($item));
 2340:                 }
 2341:             }
 2342:         }
 2343:     }
 2344:     return (\%ruleshash,\@ruleorder);
 2345: }
 2346: 
 2347: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2348: 
 2349: sub get_domain_defaults {
 2350:     my ($domain,$ignore_cache) = @_;
 2351:     return if (($domain eq '') || ($domain eq 'public'));
 2352:     my $cachetime = 60*60*24;
 2353:     unless ($ignore_cache) {
 2354:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2355:         if (defined($cached)) {
 2356:             if (ref($result) eq 'HASH') {
 2357:                 return %{$result};
 2358:             }
 2359:         }
 2360:     }
 2361:     my %domdefaults;
 2362:     my %domconfig =
 2363:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2364:                                   'requestcourses','inststatus',
 2365:                                   'coursedefaults','usersessions',
 2366:                                   'requestauthor','selfenrollment',
 2367:                                   'coursecategories','ssl','autoenroll',
 2368:                                   'trust','helpsettings'],$domain);
 2369:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2370:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2371:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2372:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2373:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2374:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2375:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2376:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2377:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2378:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2379:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2380:     } else {
 2381:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2382:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2383:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2384:     }
 2385:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2386:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2387:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2388:         } else {
 2389:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2390:         }
 2391:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2392:         foreach my $item (@usertools) {
 2393:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2394:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2395:             }
 2396:         }
 2397:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2398:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2399:         }
 2400:     }
 2401:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2402:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2403:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2404:         }
 2405:     }
 2406:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2407:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2408:     }
 2409:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2410:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2411:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2412:         }
 2413:     }
 2414:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2415:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2416:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2417:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2418:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2419:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2420:         }
 2421:         foreach my $type (@coursetypes) {
 2422:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2423:                 unless ($type eq 'community') {
 2424:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2425:                 }
 2426:             }
 2427:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2428:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2429:             }
 2430:             if ($domdefaults{'postsubmit'} eq 'on') {
 2431:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2432:                     $domdefaults{$type.'postsubtimeout'} = 
 2433:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2434:                 }
 2435:             }
 2436:         }
 2437:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2438:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2439:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2440:                 if (@clonecodes) {
 2441:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2442:                 }
 2443:             }
 2444:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2445:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2446:         }
 2447:     }
 2448:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2449:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2450:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2451:         }
 2452:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2453:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2454:         }
 2455:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2456:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2457:         }
 2458:     }
 2459:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2460:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2461:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2462:                             'approval','limit');
 2463:             foreach my $type (@coursetypes) {
 2464:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2465:                     my @mgrdc = ();
 2466:                     foreach my $item (@settings) {
 2467:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2468:                             push(@mgrdc,$item);
 2469:                         }
 2470:                     }
 2471:                     if (@mgrdc) {
 2472:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2473:                     }
 2474:                 }
 2475:             }
 2476:         }
 2477:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2478:             foreach my $type (@coursetypes) {
 2479:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2480:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2481:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2482:                     }
 2483:                 }
 2484:             }
 2485:         }
 2486:     }
 2487:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2488:         $domdefaults{'catauth'} = 'std';
 2489:         $domdefaults{'catunauth'} = 'std';
 2490:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2491:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2492:         }
 2493:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2494:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2495:         }
 2496:     }
 2497:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2498:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2499:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2500:         }
 2501:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2502:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2503:         }
 2504:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2505:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2506:         }
 2507:     }
 2508:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2509:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2510:         foreach my $prefix (@prefixes) {
 2511:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2512:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2513:             }
 2514:         }
 2515:     }
 2516:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2517:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2518:     }
 2519:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2520:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2521:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2522:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2523:         }
 2524:     }
 2525:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2526:     return %domdefaults;
 2527: }
 2528: 
 2529: sub course_portal_url {
 2530:     my ($cnum,$cdom) = @_;
 2531:     my $chome = &homeserver($cnum,$cdom);
 2532:     my $hostname = &hostname($chome);
 2533:     my $protocol = $protocol{$chome};
 2534:     $protocol = 'http' if ($protocol ne 'https');
 2535:     my %domdefaults = &get_domain_defaults($cdom);
 2536:     my $firsturl;
 2537:     if ($domdefaults{'portal_def'}) {
 2538:         $firsturl = $domdefaults{'portal_def'};
 2539:     } else {
 2540:         $firsturl = $protocol.'://'.$hostname;
 2541:     }
 2542:     return $firsturl;
 2543: }
 2544: 
 2545: # --------------------------------------------------- Assign a key to a student
 2546: 
 2547: sub assign_access_key {
 2548: #
 2549: # a valid key looks like uname:udom#comments
 2550: # comments are being appended
 2551: #
 2552:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2553:     $kdom=
 2554:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2555:     $knum=
 2556:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2557:     $cdom=
 2558:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2559:     $cnum=
 2560:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2561:     $udom=$env{'user.name'} unless (defined($udom));
 2562:     $uname=$env{'user.domain'} unless (defined($uname));
 2563:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2564:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2565:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2566:                                                   # assigned to this person
 2567:                                                   # - this should not happen,
 2568:                                                   # unless something went wrong
 2569:                                                   # the first time around
 2570: # ready to assign
 2571:         $logentry=$1.'; '.$logentry;
 2572:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2573:                                                  $kdom,$knum) eq 'ok') {
 2574: # key now belongs to user
 2575: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2576:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2577:                 &appenv({'environment.'.$envkey => $ckey});
 2578:                 return 'ok';
 2579:             } else {
 2580:                 return 
 2581:   'error: Count not permanently assign key, will need to be re-entered later.';
 2582: 	    }
 2583:         } else {
 2584:             return 'error: Could not assign key, try again later.';
 2585:         }
 2586:     } elsif (!$existing{$ckey}) {
 2587: # the key does not exist
 2588: 	return 'error: The key does not exist';
 2589:     } else {
 2590: # the key is somebody else's
 2591: 	return 'error: The key is already in use';
 2592:     }
 2593: }
 2594: 
 2595: # ------------------------------------------ put an additional comment on a key
 2596: 
 2597: sub comment_access_key {
 2598: #
 2599: # a valid key looks like uname:udom#comments
 2600: # comments are being appended
 2601: #
 2602:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 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:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2608:     if ($existing{$ckey}) {
 2609:         $existing{$ckey}.='; '.$logentry;
 2610: # ready to assign
 2611:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2612:                                                  $cdom,$cnum) eq 'ok') {
 2613: 	    return 'ok';
 2614:         } else {
 2615: 	    return 'error: Count not store comment.';
 2616:         }
 2617:     } else {
 2618: # the key does not exist
 2619: 	return 'error: The key does not exist';
 2620:     }
 2621: }
 2622: 
 2623: # ------------------------------------------------------ Generate a set of keys
 2624: 
 2625: sub generate_access_keys {
 2626:     my ($number,$cdom,$cnum,$logentry)=@_;
 2627:     $cdom=
 2628:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2629:     $cnum=
 2630:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2631:     unless (&allowed('mky',$cdom)) { return 0; }
 2632:     unless (($cdom) && ($cnum)) { return 0; }
 2633:     if ($number>10000) { return 0; }
 2634:     sleep(2); # make sure don't get same seed twice
 2635:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2636:     my $total=0;
 2637:     for (my $i=1;$i<=$number;$i++) {
 2638:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2639:                   sprintf("%lx",int(100000*rand)).'-'.
 2640:                   sprintf("%lx",int(100000*rand));
 2641:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2642:        $newkey=~s/0/h/g; # and also 0 and O
 2643:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2644:        if ($existing{$newkey}) {
 2645:            $i--;
 2646:        } else {
 2647: 	  if (&put('accesskeys',
 2648:               { $newkey => '# generated '.localtime().
 2649:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2650:                            '; '.$logentry },
 2651: 		   $cdom,$cnum) eq 'ok') {
 2652:               $total++;
 2653: 	  }
 2654:        }
 2655:     }
 2656:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2657:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2658:     return $total;
 2659: }
 2660: 
 2661: # ------------------------------------------------------- Validate an accesskey
 2662: 
 2663: sub validate_access_key {
 2664:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2665:     $cdom=
 2666:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2667:     $cnum=
 2668:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2669:     $udom=$env{'user.domain'} unless (defined($udom));
 2670:     $uname=$env{'user.name'} unless (defined($uname));
 2671:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2672:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2673: }
 2674: 
 2675: # ------------------------------------- Find the section of student in a course
 2676: sub devalidate_getsection_cache {
 2677:     my ($udom,$unam,$courseid)=@_;
 2678:     my $hashid="$udom:$unam:$courseid";
 2679:     &devalidate_cache_new('getsection',$hashid);
 2680: }
 2681: 
 2682: sub courseid_to_courseurl {
 2683:     my ($courseid) = @_;
 2684:     #already url style courseid
 2685:     return $courseid if ($courseid =~ m{^/});
 2686: 
 2687:     if (exists($env{'course.'.$courseid.'.num'})) {
 2688: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2689: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2690: 	return "/$cdom/$cnum";
 2691:     }
 2692: 
 2693:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2694:     if (exists($courseinfo{'num'})) {
 2695: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2696:     }
 2697: 
 2698:     return undef;
 2699: }
 2700: 
 2701: sub getsection {
 2702:     my ($udom,$unam,$courseid)=@_;
 2703:     my $cachetime=1800;
 2704: 
 2705:     my $hashid="$udom:$unam:$courseid";
 2706:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2707:     if (defined($cached)) { return $result; }
 2708: 
 2709:     my %Pending; 
 2710:     my %Expired;
 2711:     #
 2712:     # Each role can either have not started yet (pending), be active, 
 2713:     #    or have expired.
 2714:     #
 2715:     # If there is an active role, we are done.
 2716:     #
 2717:     # If there is more than one role which has not started yet, 
 2718:     #     choose the one which will start sooner
 2719:     # If there is one role which has not started yet, return it.
 2720:     #
 2721:     # If there is more than one expired role, choose the one which ended last.
 2722:     # If there is a role which has expired, return it.
 2723:     #
 2724:     $courseid = &courseid_to_courseurl($courseid);
 2725:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2726:     foreach my $key (keys(%roleshash)) {
 2727:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2728:         my $section=$1;
 2729:         if ($key eq $courseid.'_st') { $section=''; }
 2730:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2731:         my $now=time;
 2732:         if (defined($end) && $end && ($now > $end)) {
 2733:             $Expired{$end}=$section;
 2734:             next;
 2735:         }
 2736:         if (defined($start) && $start && ($now < $start)) {
 2737:             $Pending{$start}=$section;
 2738:             next;
 2739:         }
 2740:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2741:     }
 2742:     #
 2743:     # Presumedly there will be few matching roles from the above
 2744:     # loop and the sorting time will be negligible.
 2745:     if (scalar(keys(%Pending))) {
 2746:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2747:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2748:     } 
 2749:     if (scalar(keys(%Expired))) {
 2750:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2751:         my $time = pop(@sorted);
 2752:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2753:     }
 2754:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2755: }
 2756: 
 2757: sub save_cache {
 2758:     &purge_remembered();
 2759:     #&Apache::loncommon::validate_page();
 2760:     undef(%env);
 2761:     undef($env_loaded);
 2762: }
 2763: 
 2764: my $to_remember=-1;
 2765: my %remembered;
 2766: my %accessed;
 2767: my $kicks=0;
 2768: my $hits=0;
 2769: sub make_key {
 2770:     my ($name,$id) = @_;
 2771:     if (length($id) > 65 
 2772: 	&& length(&escape($id)) > 200) {
 2773: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2774:     }
 2775:     return &escape($name.':'.$id);
 2776: }
 2777: 
 2778: sub devalidate_cache_new {
 2779:     my ($name,$id,$debug) = @_;
 2780:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2781:     my $remembered_id=$name.':'.$id;
 2782:     $id=&make_key($name,$id);
 2783:     $memcache->delete($id);
 2784:     delete($remembered{$remembered_id});
 2785:     delete($accessed{$remembered_id});
 2786: }
 2787: 
 2788: sub is_cached_new {
 2789:     my ($name,$id,$debug) = @_;
 2790:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2791:     if (exists($remembered{$remembered_id})) {
 2792: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2793: 	$accessed{$remembered_id}=[&gettimeofday()];
 2794: 	$hits++;
 2795: 	return ($remembered{$remembered_id},1);
 2796:     }
 2797:     $id=&make_key($name,$id);
 2798:     my $value = $memcache->get($id);
 2799:     if (!(defined($value))) {
 2800: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2801: 	return (undef,undef);
 2802:     }
 2803:     if ($value eq '__undef__') {
 2804: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2805: 	$value=undef;
 2806:     }
 2807:     &make_room($remembered_id,$value,$debug);
 2808:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2809:     return ($value,1);
 2810: }
 2811: 
 2812: sub do_cache_new {
 2813:     my ($name,$id,$value,$time,$debug) = @_;
 2814:     my $remembered_id=$name.':'.$id;
 2815:     $id=&make_key($name,$id);
 2816:     my $setvalue=$value;
 2817:     if (!defined($setvalue)) {
 2818: 	$setvalue='__undef__';
 2819:     }
 2820:     if (!defined($time) ) {
 2821: 	$time=600;
 2822:     }
 2823:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2824:     my $result = $memcache->set($id,$setvalue,$time);
 2825:     if (! $result) {
 2826: 	&logthis("caching of id -> $id  failed");
 2827: 	$memcache->disconnect_all();
 2828:     }
 2829:     # need to make a copy of $value
 2830:     &make_room($remembered_id,$value,$debug);
 2831:     return $value;
 2832: }
 2833: 
 2834: sub make_room {
 2835:     my ($remembered_id,$value,$debug)=@_;
 2836: 
 2837:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2838:                                     : $value;
 2839:     if ($to_remember<0) { return; }
 2840:     $accessed{$remembered_id}=[&gettimeofday()];
 2841:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2842:     my $to_kick;
 2843:     my $max_time=0;
 2844:     foreach my $other (keys(%accessed)) {
 2845: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2846: 	    $to_kick=$other;
 2847: 	    $max_time=&tv_interval($accessed{$other});
 2848: 	}
 2849:     }
 2850:     delete($remembered{$to_kick});
 2851:     delete($accessed{$to_kick});
 2852:     $kicks++;
 2853:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2854:     return;
 2855: }
 2856: 
 2857: sub purge_remembered {
 2858:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2859:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2860:     undef(%remembered);
 2861:     undef(%accessed);
 2862: }
 2863: # ------------------------------------- Read an entry from a user's environment
 2864: 
 2865: sub userenvironment {
 2866:     my ($udom,$unam,@what)=@_;
 2867:     my $items;
 2868:     foreach my $item (@what) {
 2869:         $items.=&escape($item).'&';
 2870:     }
 2871:     $items=~s/\&$//;
 2872:     my %returnhash=();
 2873:     my $uhome = &homeserver($unam,$udom);
 2874:     unless ($uhome eq 'no_host') {
 2875:         my @answer=split(/\&/, 
 2876:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2877:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2878:             return %returnhash;
 2879:         }
 2880:         my $i;
 2881:         for ($i=0;$i<=$#what;$i++) {
 2882: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2883:         }
 2884:     }
 2885:     return %returnhash;
 2886: }
 2887: 
 2888: # ---------------------------------------------------------- Get a studentphoto
 2889: sub studentphoto {
 2890:     my ($udom,$unam,$ext) = @_;
 2891:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2892:     if (defined($env{'request.course.id'})) {
 2893:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2894:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2895:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2896:             } else {
 2897:                 my ($result,$perm_reqd)=
 2898: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2899:                 if ($result eq 'ok') {
 2900:                     if (!($perm_reqd eq 'yes')) {
 2901:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2902:                     }
 2903:                 }
 2904:             }
 2905:         }
 2906:     } else {
 2907:         my ($result,$perm_reqd) = 
 2908: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2909:         if ($result eq 'ok') {
 2910:             if (!($perm_reqd eq 'yes')) {
 2911:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2912:             }
 2913:         }
 2914:     }
 2915:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2916: }
 2917: 
 2918: sub retrievestudentphoto {
 2919:     my ($udom,$unam,$ext,$type) = @_;
 2920:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2921:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2922:     if ($ret eq 'ok') {
 2923:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2924:         if ($type eq 'thumbnail') {
 2925:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2926:         }
 2927:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2928:         return $tokenurl;
 2929:     } else {
 2930:         if ($type eq 'thumbnail') {
 2931:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2932:         } else { 
 2933:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2934:         }
 2935:     }
 2936: }
 2937: 
 2938: # -------------------------------------------------------------------- New chat
 2939: 
 2940: sub chatsend {
 2941:     my ($newentry,$anon,$group)=@_;
 2942:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2943:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2944:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2945:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2946: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2947: 		   &escape($newentry)).':'.$group,$chome);
 2948: }
 2949: 
 2950: # ------------------------------------------ Find current version of a resource
 2951: 
 2952: sub getversion {
 2953:     my $fname=&clutter(shift);
 2954:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2955:     return &currentversion(&filelocation('',$fname));
 2956: }
 2957: 
 2958: sub currentversion {
 2959:     my $fname=shift;
 2960:     my $author=$fname;
 2961:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2962:     my ($udom,$uname)=split(/\//,$author);
 2963:     my $home=&homeserver($uname,$udom);
 2964:     if ($home eq 'no_host') { 
 2965:         return -1; 
 2966:     }
 2967:     my $answer=&reply("currentversion:$fname",$home);
 2968:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2969: 	return -1;
 2970:     }
 2971:     return $answer;
 2972: }
 2973: 
 2974: #
 2975: # Return special version number of resource if set by override, empty otherwise
 2976: #
 2977: sub usedversion {
 2978:     my $fname=shift;
 2979:     unless ($fname) { $fname=$env{'request.uri'}; }
 2980:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2981:     if ($urlversion) { return $urlversion; }
 2982:     return '';
 2983: }
 2984: 
 2985: # ----------------------------- Subscribe to a resource, return URL if possible
 2986: 
 2987: sub subscribe {
 2988:     my $fname=shift;
 2989:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2990:     $fname=~s/[\n\r]//g;
 2991:     my $author=$fname;
 2992:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2993:     my ($udom,$uname)=split(/\//,$author);
 2994:     my $home=homeserver($uname,$udom);
 2995:     if ($home eq 'no_host') {
 2996:         return 'not_found';
 2997:     }
 2998:     my $answer=reply("sub:$fname",$home);
 2999:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3000: 	$answer.=' by '.$home;
 3001:     }
 3002:     return $answer;
 3003: }
 3004:     
 3005: # -------------------------------------------------------------- Replicate file
 3006: 
 3007: sub repcopy {
 3008:     my $filename=shift;
 3009:     $filename=~s/\/+/\//g;
 3010:     my $londocroot = $perlvar{'lonDocRoot'};
 3011:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3012:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3013:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3014: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3015: 	return &repcopy_userfile($filename);
 3016:     }
 3017:     $filename=~s/[\n\r]//g;
 3018:     my $transname="$filename.in.transfer";
 3019: # FIXME: this should flock
 3020:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3021:     my $remoteurl=subscribe($filename);
 3022:     if ($remoteurl =~ /^con_lost by/) {
 3023: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3024:            return 'unavailable';
 3025:     } elsif ($remoteurl eq 'not_found') {
 3026: 	   #&logthis("Subscribe returned not_found: $filename");
 3027: 	   return 'not_found';
 3028:     } elsif ($remoteurl =~ /^rejected by/) {
 3029: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3030:            return 'forbidden';
 3031:     } elsif ($remoteurl eq 'directory') {
 3032:            return 'ok';
 3033:     } else {
 3034:         my $author=$filename;
 3035:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3036:         my ($udom,$uname)=split(/\//,$author);
 3037:         my $home=homeserver($uname,$udom);
 3038:         unless ($home eq $perlvar{'lonHostID'}) {
 3039:            my @parts=split(/\//,$filename);
 3040:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3041:            if ($path ne "$londocroot/res") {
 3042:                &logthis("Malconfiguration for replication: $filename");
 3043: 	       return 'bad_request';
 3044:            }
 3045:            my $count;
 3046:            for ($count=5;$count<$#parts;$count++) {
 3047:                $path.="/$parts[$count]";
 3048:                if ((-e $path)!=1) {
 3049: 		   mkdir($path,0777);
 3050:                }
 3051:            }
 3052:            my $request=new HTTP::Request('GET',"$remoteurl");
 3053:            my $response;
 3054:            if ($remoteurl =~ m{/raw/}) {
 3055:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3056:            } else {
 3057:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3058:            }
 3059:            if ($response->is_error()) {
 3060: 	       unlink($transname);
 3061:                my $message=$response->status_line;
 3062:                &logthis("<font color=\"blue\">WARNING:"
 3063:                        ." LWP get: $message: $filename</font>");
 3064:                return 'unavailable';
 3065:            } else {
 3066: 	       if ($remoteurl!~/\.meta$/) {
 3067:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3068:                   my $mresponse;
 3069:                   if ($remoteurl =~ m{/raw/}) {
 3070:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3071:                   } else {
 3072:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3073:                   }
 3074:                   if ($mresponse->is_error()) {
 3075: 		      unlink($filename.'.meta');
 3076:                       &logthis(
 3077:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3078:                   }
 3079: 	       }
 3080:                rename($transname,$filename);
 3081:                return 'ok';
 3082:            }
 3083:        }
 3084:     }
 3085: }
 3086: 
 3087: # ------------------------------------------------ Get server side include body
 3088: sub ssi_body {
 3089:     my ($filelink,%form)=@_;
 3090:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3091:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3092:     }
 3093:     my $output='';
 3094:     my $response;
 3095:     if ($filelink=~/^https?\:/) {
 3096:        ($output,$response)=&externalssi($filelink);
 3097:     } else {
 3098:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3099:        $filelink .= 'inhibitmenu=yes';
 3100:        ($output,$response)=&ssi($filelink,%form);
 3101:     }
 3102:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3103:     $output=~s/^.*?\<body[^\>]*\>//si;
 3104:     $output=~s/\<\/body\s*\>.*?$//si;
 3105:     if (wantarray) {
 3106:         return ($output, $response);
 3107:     } else {
 3108:         return $output;
 3109:     }
 3110: }
 3111: 
 3112: # --------------------------------------------------------- Server Side Include
 3113: 
 3114: sub absolute_url {
 3115:     my ($host_name) = @_;
 3116:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3117:     if ($host_name eq '') {
 3118: 	$host_name = $ENV{'SERVER_NAME'};
 3119:     }
 3120:     return $protocol.$host_name;
 3121: }
 3122: 
 3123: #
 3124: #   Server side include.
 3125: # Parameters:
 3126: #  fn     Possibly encrypted resource name/id.
 3127: #  form   Hash that describes how the rendering should be done
 3128: #         and other things.
 3129: # Returns:
 3130: #   Scalar context: The content of the response.
 3131: #   Array context:  2 element list of the content and the full response object.
 3132: #     
 3133: sub ssi {
 3134: 
 3135:     my ($fn,%form)=@_;
 3136:     my $request;
 3137: 
 3138:     $form{'no_update_last_known'}=1;
 3139:     &Apache::lonenc::check_encrypt(\$fn);
 3140:     if (%form) {
 3141:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3142:       $request->content(join('&',map { 
 3143:             my $name = escape($_);
 3144:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3145:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3146:             : &escape($form{$_}) );    
 3147:         } keys(%form)));
 3148:     } else {
 3149:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3150:     }
 3151: 
 3152:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3153:     my $lonhost = $perlvar{'lonHostID'};
 3154:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
 3155: 
 3156:     if (wantarray) {
 3157: 	return ($response->content, $response);
 3158:     } else {
 3159: 	return $response->content;
 3160:     }
 3161: }
 3162: 
 3163: sub externalssi {
 3164:     my ($url)=@_;
 3165:     my $request=new HTTP::Request('GET',$url);
 3166:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3167:     if (wantarray) {
 3168:         return ($response->content, $response);
 3169:     } else {
 3170:         return $response->content;
 3171:     }
 3172: }
 3173: 
 3174: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3175: 
 3176: sub allowuploaded {
 3177:     my ($srcurl,$url)=@_;
 3178:     $url=&clutter(&declutter($url));
 3179:     my $dir=$url;
 3180:     $dir=~s/\/[^\/]+$//;
 3181:     my %httpref=();
 3182:     my $httpurl=&hreflocation('',$url);
 3183:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3184:     &Apache::lonnet::appenv(\%httpref);
 3185: }
 3186: 
 3187: #
 3188: # Determine if the current user should be able to edit a particular resource,
 3189: # when viewing in course context.
 3190: # (a) When viewing resource used to determine if "Edit" item is included in 
 3191: #     Functions.
 3192: # (b) When displaying folder contents in course editor, used to determine if
 3193: #     "Edit" link will be displayed alongside resource.
 3194: #
 3195: #  input: six args -- filename (decluttered), course number, course domain,
 3196: #                   url, symb (if registered) and group (if this is a group
 3197: #                   item -- e.g., bulletin board, group page etc.).
 3198: #  output: array of five scalars -- 
 3199: #          $cfile -- url for file editing if editable on current server
 3200: #          $home -- homeserver of resource (i.e., for author if published,
 3201: #                                           or course if uploaded.).
 3202: #          $switchserver --  1 if server switch will be needed.
 3203: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3204: #          $forceview -- 1 if icon/link should be to go to view mode
 3205: #
 3206: 
 3207: sub can_edit_resource {
 3208:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3209:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3210: #
 3211: # For aboutme pages user can only edit his/her own.
 3212: #
 3213:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3214:         my ($sdom,$sname) = ($1,$2);
 3215:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3216:             $home = $env{'user.home'};
 3217:             $cfile = $resurl;
 3218:             if ($env{'form.forceedit'}) {
 3219:                 $forceview = 1;
 3220:             } else {
 3221:                 $forceedit = 1;
 3222:             }
 3223:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3224:         } else {
 3225:             return;
 3226:         }
 3227:     }
 3228: 
 3229:     if ($env{'request.course.id'}) {
 3230:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3231:         if ($group ne '') {
 3232: # if this is a group homepage or group bulletin board, check group privs
 3233:             my $allowed = 0;
 3234:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3235:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3236:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3237:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3238:                     $allowed = 1;
 3239:                 }
 3240:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3241:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3242:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3243:                     $allowed = 1;
 3244:                 }
 3245:             }
 3246:             if ($allowed) {
 3247:                 $home=&homeserver($cnum,$cdom);
 3248:                 if ($env{'form.forceedit'}) {
 3249:                     $forceview = 1;
 3250:                 } else {
 3251:                     $forceedit = 1;
 3252:                 }
 3253:                 $cfile = $resurl;
 3254:             } else {
 3255:                 return;
 3256:             }
 3257:         } else {
 3258:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3259:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3260:                     return;
 3261:                 }
 3262:             } elsif (!$crsedit) {
 3263: #
 3264: # No edit allowed where CC has switched to student role.
 3265: #
 3266:                 return;
 3267:             }
 3268:         }
 3269:     }
 3270: 
 3271:     if ($file ne '') {
 3272:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3273:             if (&is_course_upload($file,$cnum,$cdom)) {
 3274:                 $uploaded = 1;
 3275:                 $incourse = 1;
 3276:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3277:                     $cfile = &hreflocation('',$file);
 3278:                     if ($env{'form.forceedit'}) {
 3279:                         $forceview = 1;
 3280:                     } else {
 3281:                         $forceedit = 1;
 3282:                     }
 3283:                 }
 3284:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3285:                 $incourse = 1;
 3286:                 if ($env{'form.forceedit'}) {
 3287:                     $forceview = 1;
 3288:                 } else {
 3289:                     $forceedit = 1;
 3290:                 }
 3291:                 $cfile = $resurl;
 3292:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3293:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3294:                     $incourse = 1;
 3295:                     if ($env{'form.forceedit'}) {
 3296:                         $forceview = 1;
 3297:                     } else {
 3298:                         $forceedit = 1;
 3299:                     }
 3300:                     $cfile = $resurl;
 3301:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3302:                     $incourse = 1;
 3303:                     $cfile = $resurl.'/smpedit';
 3304:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3305:                     $incourse = 1;
 3306:                     if ($env{'form.forceedit'}) {
 3307:                         $forceview = 1;
 3308:                     } else {
 3309:                         $forceedit = 1;
 3310:                     }
 3311:                     $cfile = $resurl;
 3312:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3313:                     $incourse = 1;
 3314:                     if ($env{'form.forceedit'}) {
 3315:                         $forceview = 1;
 3316:                     } else {
 3317:                         $forceedit = 1;
 3318:                     }
 3319:                     $cfile = $resurl;
 3320:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3321:                     $incourse = 1;
 3322:                     if ($env{'form.forceedit'}) {
 3323:                         $forceview = 1;
 3324:                     } else {
 3325:                         $forceedit = 1;
 3326:                     }
 3327:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3328:                 }
 3329:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3330:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3331:                 if (&is_on_map($template)) { 
 3332:                     $incourse = 1;
 3333:                     $forceview = 1;
 3334:                     $cfile = $template;
 3335:                 }
 3336:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3337:                     $incourse = 1;
 3338:                     if ($env{'form.forceedit'}) {
 3339:                         $forceview = 1;
 3340:                     } else {
 3341:                         $forceedit = 1;
 3342:                     }
 3343:                     $cfile = $resurl;
 3344:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3345:                 $incourse = 1;
 3346:                 if ($env{'form.forceedit'}) {
 3347:                     $forceview = 1;
 3348:                 } else {
 3349:                     $forceedit = 1;
 3350:                 }
 3351:                 $cfile = $resurl;
 3352:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3353:                 $incourse = 1;
 3354:                 $forceview = 1;
 3355:                 if ($symb) {
 3356:                     my ($map,$id,$res)=&decode_symb($symb);
 3357:                     $env{'request.symb'} = $symb;
 3358:                     $cfile = &clutter($res);
 3359:                 } else {
 3360:                     $cfile = $env{'form.suppurl'};
 3361:                     my $escfile = &unescape($cfile);
 3362:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3363:                         $cfile = '/adm/wrapper'.$escfile;
 3364:                     } else {
 3365:                         $escfile =~ s{^http://}{};
 3366:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3367:                     }
 3368:                 }
 3369:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3370:                 if ($env{'form.forceedit'}) {
 3371:                     $forceview = 1;
 3372:                 } else {
 3373:                     $forceedit = 1;
 3374:                 }
 3375:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3376:             }
 3377:         }
 3378:         if ($uploaded || $incourse) {
 3379:             $home=&homeserver($cnum,$cdom);
 3380:         } elsif ($file !~ m{/$}) {
 3381:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3382:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3383:             # Check that the user has permission to edit this resource
 3384:             my $setpriv = 1;
 3385:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3386:             if (defined($cfudom)) {
 3387:                 $home=&homeserver($cfuname,$cfudom);
 3388:                 $cfile=$file;
 3389:             }
 3390:         }
 3391:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3392:             (($home ne '') && ($home ne 'no_host'))) {
 3393:             my @ids=&current_machine_ids();
 3394:             unless (grep(/^\Q$home\E$/,@ids)) {
 3395:                 $switchserver=1;
 3396:             }
 3397:         }
 3398:     }
 3399:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3400: }
 3401: 
 3402: sub is_course_upload {
 3403:     my ($file,$cnum,$cdom) = @_;
 3404:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3405:     $uploadpath =~ s{^\/}{};
 3406:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3407:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3408:         return 1;
 3409:     }
 3410:     return;
 3411: }
 3412: 
 3413: sub in_course {
 3414:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3415:     if ($hideprivileged) {
 3416:         my $skipuser;
 3417:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3418:         my @possdoms = ($cdom);  
 3419:         if ($coursehash{'checkforpriv'}) { 
 3420:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3421:         }
 3422:         if (&privileged($uname,$udom,\@possdoms)) {
 3423:             $skipuser = 1;
 3424:             if ($coursehash{'nothideprivileged'}) {
 3425:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3426:                     my $user;
 3427:                     if ($item =~ /:/) {
 3428:                         $user = $item;
 3429:                     } else {
 3430:                         $user = join(':',split(/[\@]/,$item));
 3431:                     }
 3432:                     if ($user eq $uname.':'.$udom) {
 3433:                         undef($skipuser);
 3434:                         last;
 3435:                     }
 3436:                 }
 3437:             }
 3438:             if ($skipuser) {
 3439:                 return 0;
 3440:             }
 3441:         }
 3442:     }
 3443:     $type ||= 'any';
 3444:     if (!defined($cdom) || !defined($cnum)) {
 3445:         my $cid  = $env{'request.course.id'};
 3446:         $cdom = $env{'course.'.$cid.'.domain'};
 3447:         $cnum = $env{'course.'.$cid.'.num'};
 3448:     }
 3449:     my $typesref;
 3450:     if (($type eq 'any') || ($type eq 'all')) {
 3451:         $typesref = ['active','previous','future'];
 3452:     } elsif ($type eq 'previous' || $type eq 'future') {
 3453:         $typesref = [$type];
 3454:     }
 3455:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3456:                               $typesref,undef,[$cdom]);
 3457:     my ($tmp) = keys(%roles);
 3458:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3459:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3460:     if (@course_roles > 0) {
 3461:         return 1;
 3462:     }
 3463:     return 0;
 3464: }
 3465: 
 3466: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3467: # input: action, courseID, current domain, intended
 3468: #        path to file, source of file, instruction to parse file for objects,
 3469: #        ref to hash for embedded objects,
 3470: #        ref to hash for codebase of java objects.
 3471: #        reference to scalar to accommodate mime type determined
 3472: #          from File::MMagic if $parser = parse.
 3473: #
 3474: # output: url to file (if action was uploaddoc), 
 3475: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3476: #
 3477: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3478: # course.
 3479: #
 3480: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3481: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3482: #          course's home server.
 3483: #
 3484: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3485: #          be copied from $source (current location) to 
 3486: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3487: #         and will then be copied to
 3488: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3489: #         course's home server.
 3490: #
 3491: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3492: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3493: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3494: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3495: #         in course's home server.
 3496: #
 3497: 
 3498: sub process_coursefile {
 3499:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3500:         $mimetype)=@_;
 3501:     my $fetchresult;
 3502:     my $home=&homeserver($docuname,$docudom);
 3503:     if ($action eq 'propagate') {
 3504:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3505: 			     $home);
 3506:     } else {
 3507:         my $fpath = '';
 3508:         my $fname = $file;
 3509:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3510:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3511:         my $filepath = &build_filepath($fpath);
 3512:         if ($action eq 'copy') {
 3513:             if ($source eq '') {
 3514:                 $fetchresult = 'no source file';
 3515:                 return $fetchresult;
 3516:             } else {
 3517:                 my $destination = $filepath.'/'.$fname;
 3518:                 rename($source,$destination);
 3519:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3520:                                  $home);
 3521:             }
 3522:         } elsif ($action eq 'uploaddoc') {
 3523:             open(my $fh,'>'.$filepath.'/'.$fname);
 3524:             print $fh $env{'form.'.$source};
 3525:             close($fh);
 3526:             if ($parser eq 'parse') {
 3527:                 my $mm = new File::MMagic;
 3528:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3529:                 if ($type eq 'text/html') {
 3530:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3531:                     unless ($parse_result eq 'ok') {
 3532:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3533:                     }
 3534:                 }
 3535:                 if (ref($mimetype)) {
 3536:                     $$mimetype = $type;
 3537:                 } 
 3538:             }
 3539:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3540:                                  $home);
 3541:             if ($fetchresult eq 'ok') {
 3542:                 return '/uploaded/'.$fpath.'/'.$fname;
 3543:             } else {
 3544:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3545:                         ' to host '.$home.': '.$fetchresult);
 3546:                 return '/adm/notfound.html';
 3547:             }
 3548:         }
 3549:     }
 3550:     unless ( $fetchresult eq 'ok') {
 3551:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3552:              ' to host '.$home.': '.$fetchresult);
 3553:     }
 3554:     return $fetchresult;
 3555: }
 3556: 
 3557: sub build_filepath {
 3558:     my ($fpath) = @_;
 3559:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3560:     unless ($fpath eq '') {
 3561:         my @parts=split('/',$fpath);
 3562:         foreach my $part (@parts) {
 3563:             $filepath.= '/'.$part;
 3564:             if ((-e $filepath)!=1) {
 3565:                 mkdir($filepath,0777);
 3566:             }
 3567:         }
 3568:     }
 3569:     return $filepath;
 3570: }
 3571: 
 3572: sub store_edited_file {
 3573:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3574:     my $file = $primary_url;
 3575:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3576:     my $fpath = '';
 3577:     my $fname = $file;
 3578:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3579:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3580:     my $filepath = &build_filepath($fpath);
 3581:     open(my $fh,'>'.$filepath.'/'.$fname);
 3582:     print $fh $content;
 3583:     close($fh);
 3584:     my $home=&homeserver($docuname,$docudom);
 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: sub clean_filename {
 3597:     my ($fname,$args)=@_;
 3598: # Replace Windows backslashes by forward slashes
 3599:     $fname=~s/\\/\//g;
 3600:     if (!$args->{'keep_path'}) {
 3601:         # Get rid of everything but the actual filename
 3602: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3603:     }
 3604: # Replace spaces by underscores
 3605:     $fname=~s/\s+/\_/g;
 3606: # Replace all other weird characters by nothing
 3607:     $fname=~s{[^/\w\.\-]}{}g;
 3608: # Replace all .\d. sequences with _\d. so they no longer look like version
 3609: # numbers
 3610:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3611:     return $fname;
 3612: }
 3613: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3614: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3615: # image with the same aspect ratio as the original, but with dimensions which do 
 3616: # not exceed $resizewidth and $resizeheight.
 3617:  
 3618: sub resizeImage {
 3619:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3620:     my $ima = Image::Magick->new;
 3621:     my $resized;
 3622:     if (-e $img_path) {
 3623:         $ima->Read($img_path);
 3624:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3625:             my $width = $ima->Get('width');
 3626:             my $height = $ima->Get('height');
 3627:             if ($width > $resizewidth) {
 3628: 	        my $factor = $width/$resizewidth;
 3629:                 my $newheight = $height/$factor;
 3630:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3631:                 $resized = 1;
 3632:             }
 3633:         }
 3634:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3635:             my $width = $ima->Get('width');
 3636:             my $height = $ima->Get('height');
 3637:             if ($height > $resizeheight) {
 3638:                 my $factor = $height/$resizeheight;
 3639:                 my $newwidth = $width/$factor;
 3640:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3641:                 $resized = 1;
 3642:             }
 3643:         }
 3644:         if ($resized) {
 3645:             $ima->Write($img_path);
 3646:         }
 3647:     }
 3648:     return;
 3649: }
 3650: 
 3651: # --------------- Take an uploaded file and put it into the userfiles directory
 3652: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3653: #                    the desired filename is in $env{"form.$formname.filename"}
 3654: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3655: #                                    canceloverwrite, or ''. 
 3656: #                   if 'coursedoc': upload to the current course
 3657: #                   if 'existingfile': write file to tmp/overwrites directory 
 3658: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3659: #                   $context is passed as argument to &finishuserfileupload
 3660: #        $subdir - directory in userfile to store the file into
 3661: #        $parser - instruction to parse file for objects ($parser = parse)    
 3662: #        $allfiles - reference to hash for embedded objects
 3663: #        $codebase - reference to hash for codebase of java objects
 3664: #        $desuname - username for permanent storage of uploaded file
 3665: #        $dsetudom - domain for permanaent storage of uploaded file
 3666: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3667: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3668: #        $resizewidth - width (pixels) to which to resize uploaded image
 3669: #        $resizeheight - height (pixels) to which to resize uploaded image
 3670: #        $mimetype - reference to scalar to accommodate mime type determined
 3671: #                    from File::MMagic.
 3672: # 
 3673: # output: url of file in userspace, or error: <message> 
 3674: #             or /adm/notfound.html if failure to upload occurse
 3675: 
 3676: sub userfileupload {
 3677:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3678:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3679:     if (!defined($subdir)) { $subdir='unknown'; }
 3680:     my $fname=$env{'form.'.$formname.'.filename'};
 3681:     $fname=&clean_filename($fname);
 3682:     # See if there is anything left
 3683:     unless ($fname) { return 'error: no uploaded file'; }
 3684:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3685:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3686:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3687:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3688:         my $now = time;
 3689:         my $filepath;
 3690:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3691:              $filepath = 'tmp/helprequests/'.$now;
 3692:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3693:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3694:                          '_'.$env{'user.domain'}.'/pending';
 3695:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3696:             my ($docuname,$docudom);
 3697:             if ($destudom) {
 3698:                 $docudom = $destudom;
 3699:             } else {
 3700:                 $docudom = $env{'user.domain'};
 3701:             }
 3702:             if ($destuname) {
 3703:                 $docuname = $destuname;
 3704:             } else {
 3705:                 $docuname = $env{'user.name'};
 3706:             }
 3707:             if (exists($env{'form.group'})) {
 3708:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3709:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3710:             }
 3711:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3712:             if ($context eq 'canceloverwrite') {
 3713:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3714:                 if (-e  $tempfile) {
 3715:                     my @info = stat($tempfile);
 3716:                     if ($info[9] eq $env{'form.timestamp'}) {
 3717:                         unlink($tempfile);
 3718:                     }
 3719:                 }
 3720:                 return;
 3721:             }
 3722:         }
 3723:         # Create the directory if not present
 3724:         my @parts=split(/\//,$filepath);
 3725:         my $fullpath = $perlvar{'lonDaemons'};
 3726:         for (my $i=0;$i<@parts;$i++) {
 3727:             $fullpath .= '/'.$parts[$i];
 3728:             if ((-e $fullpath)!=1) {
 3729:                 mkdir($fullpath,0777);
 3730:             }
 3731:         }
 3732:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3733:         print $fh $env{'form.'.$formname};
 3734:         close($fh);
 3735:         if ($context eq 'existingfile') {
 3736:             my @info = stat($fullpath.'/'.$fname);
 3737:             return ($fullpath.'/'.$fname,$info[9]);
 3738:         } else {
 3739:             return $fullpath.'/'.$fname;
 3740:         }
 3741:     }
 3742:     if ($subdir eq 'scantron') {
 3743:         $fname = 'scantron_orig_'.$fname;
 3744:     } else {
 3745:         $fname="$subdir/$fname";
 3746:     }
 3747:     if ($context eq 'coursedoc') {
 3748: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3749: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3750:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3751:             return &finishuserfileupload($docuname,$docudom,
 3752: 					 $formname,$fname,$parser,$allfiles,
 3753: 					 $codebase,$thumbwidth,$thumbheight,
 3754:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3755:         } else {
 3756:             if ($env{'form.folder'}) {
 3757:                 $fname=$env{'form.folder'}.'/'.$fname;
 3758:             }
 3759:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3760: 				       $fname,$formname,$parser,
 3761: 				       $allfiles,$codebase,$mimetype);
 3762:         }
 3763:     } elsif (defined($destuname)) {
 3764:         my $docuname=$destuname;
 3765:         my $docudom=$destudom;
 3766: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3767: 				     $parser,$allfiles,$codebase,
 3768:                                      $thumbwidth,$thumbheight,
 3769:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3770:     } else {
 3771:         my $docuname=$env{'user.name'};
 3772:         my $docudom=$env{'user.domain'};
 3773:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3774:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3775:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3776:         }
 3777: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3778: 				     $parser,$allfiles,$codebase,
 3779:                                      $thumbwidth,$thumbheight,
 3780:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3781:     }
 3782: }
 3783: 
 3784: sub finishuserfileupload {
 3785:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3786:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3787:     my $path=$docudom.'/'.$docuname.'/';
 3788:     my $filepath=$perlvar{'lonDocRoot'};
 3789:   
 3790:     my ($fnamepath,$file,$fetchthumb);
 3791:     $file=$fname;
 3792:     if ($fname=~m|/|) {
 3793:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3794: 	$path.=$fnamepath.'/';
 3795:     }
 3796:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3797:     my $count;
 3798:     for ($count=4;$count<=$#parts;$count++) {
 3799:         $filepath.="/$parts[$count]";
 3800:         if ((-e $filepath)!=1) {
 3801: 	    mkdir($filepath,0777);
 3802:         }
 3803:     }
 3804: 
 3805: # Save the file
 3806:     {
 3807: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3808: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3809: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3810: 	    return '/adm/notfound.html';
 3811: 	}
 3812:         if ($context eq 'overwrite') {
 3813:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3814:             my $target = $filepath.'/'.$file;
 3815:             if (-e $source) {
 3816:                 my @info = stat($source);
 3817:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3818:                     unless (&File::Copy::move($source,$target)) {
 3819:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3820:                         return "Moving from $source failed";
 3821:                     }
 3822:                 } else {
 3823:                     return "Temporary file: $source had unexpected date/time for last modification";
 3824:                 }
 3825:             } else {
 3826:                 return "Temporary file: $source missing";
 3827:             }
 3828:         } elsif (!print FH ($env{'form.'.$formname})) {
 3829: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3830: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3831: 	    return '/adm/notfound.html';
 3832: 	}
 3833: 	close(FH);
 3834:         if ($resizewidth && $resizeheight) {
 3835:             my $mm = new File::MMagic;
 3836:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3837:             if ($mime_type =~ m{^image/}) {
 3838: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3839:             }  
 3840: 	}
 3841:     }
 3842:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3843:         if (ref($mimetype)) {
 3844:             if ($$mimetype eq '') {
 3845:                 my $mm = new File::MMagic;
 3846:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3847:                 $$mimetype = $type;
 3848:             }
 3849:         }
 3850:     }
 3851:     if ($parser eq 'parse') {
 3852:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3853:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3854:                                                        $allfiles,$codebase);
 3855:             unless ($parse_result eq 'ok') {
 3856:                 &logthis('Failed to parse '.$filepath.$file.
 3857: 	   	         ' for embedded media: '.$parse_result); 
 3858:             }
 3859:         }
 3860:     }
 3861:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3862:         my $input = $filepath.'/'.$file;
 3863:         my $output = $filepath.'/'.'tn-'.$file;
 3864:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3865:         system("convert -sample $thumbsize $input $output");
 3866:         if (-e $filepath.'/'.'tn-'.$file) {
 3867:             $fetchthumb  = 1; 
 3868:         }
 3869:     }
 3870:  
 3871: # Notify homeserver to grep it
 3872: #
 3873:     my $docuhome=&homeserver($docuname,$docudom);	
 3874:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3875:     if ($fetchresult eq 'ok') {
 3876:         if ($fetchthumb) {
 3877:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3878:             if ($thumbresult ne 'ok') {
 3879:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3880:                          $docuhome.': '.$thumbresult);
 3881:             }
 3882:         }
 3883: #
 3884: # Return the URL to it
 3885:         return '/uploaded/'.$path.$file;
 3886:     } else {
 3887:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3888: 		 ': '.$fetchresult);
 3889:         return '/adm/notfound.html';
 3890:     }
 3891: }
 3892: 
 3893: sub extract_embedded_items {
 3894:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3895:     my @state = ();
 3896:     my (%lastids,%related,%shockwave,%flashvars);
 3897:     my %javafiles = (
 3898:                       codebase => '',
 3899:                       code => '',
 3900:                       archive => ''
 3901:                     );
 3902:     my %mediafiles = (
 3903:                       src => '',
 3904:                       movie => '',
 3905:                      );
 3906:     my $p;
 3907:     if ($content) {
 3908:         $p = HTML::LCParser->new($content);
 3909:     } else {
 3910:         $p = HTML::LCParser->new($fullpath);
 3911:     }
 3912:     while (my $t=$p->get_token()) {
 3913: 	if ($t->[0] eq 'S') {
 3914: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3915: 	    push(@state, $tagname);
 3916:             if (lc($tagname) eq 'allow') {
 3917:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3918:             }
 3919: 	    if (lc($tagname) eq 'img') {
 3920: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3921: 	    }
 3922: 	    if (lc($tagname) eq 'a') {
 3923:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3924:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3925:                 }
 3926: 	    }
 3927:             if (lc($tagname) eq 'script') {
 3928:                 my $src;
 3929:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3930:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3931:                 } else {
 3932:                     if ($attr->{'src'} ne '') {
 3933:                         $src = $attr->{'src'};
 3934:                         &add_filetype($allfiles,$src,'src');
 3935:                     }
 3936:                 }
 3937:                 my $text = $p->get_trimmed_text();
 3938:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3939:                     my @swfargs = split(/,/,$1);
 3940:                     foreach my $item (@swfargs) {
 3941:                         $item =~ s/["']//g;
 3942:                         $item =~ s/^\s+//;
 3943:                         $item =~ s/\s+$//;
 3944:                     }
 3945:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3946:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3947:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3948:                         } else {
 3949:                             $related{$swfargs[0]} = [$swfargs[2]];
 3950:                         }
 3951:                     }
 3952:                 }
 3953:             }
 3954:             if (lc($tagname) eq 'link') {
 3955:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3956:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3957:                 }
 3958:             }
 3959: 	    if (lc($tagname) eq 'object' ||
 3960: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3961: 		foreach my $item (keys(%javafiles)) {
 3962: 		    $javafiles{$item} = '';
 3963: 		}
 3964:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3965:                     $lastids{lc($tagname)} = $attr->{'id'};
 3966:                 }
 3967: 	    }
 3968: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3969: 		my $name = lc($attr->{'name'});
 3970: 		foreach my $item (keys(%javafiles)) {
 3971: 		    if ($name eq $item) {
 3972: 			$javafiles{$item} = $attr->{'value'};
 3973: 			last;
 3974: 		    }
 3975: 		}
 3976:                 my $pathfrom;
 3977: 		foreach my $item (keys(%mediafiles)) {
 3978: 		    if ($name eq $item) {
 3979:                         $pathfrom = $attr->{'value'};
 3980:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3981: 			&add_filetype($allfiles,$pathfrom,$name);
 3982: 			last;
 3983: 		    }
 3984: 		}
 3985:                 if ($name eq 'flashvars') {
 3986:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3987:                 }
 3988:                 if ($pathfrom ne '') {
 3989:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3990:                                          $pathfrom);
 3991:                 }
 3992: 	    }
 3993: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3994: 		foreach my $item (keys(%javafiles)) {
 3995: 		    if ($attr->{$item}) {
 3996: 			$javafiles{$item} = $attr->{$item};
 3997: 			last;
 3998: 		    }
 3999: 		}
 4000: 		foreach my $item (keys(%mediafiles)) {
 4001: 		    if ($attr->{$item}) {
 4002: 			&add_filetype($allfiles,$attr->{$item},$item);
 4003: 			last;
 4004: 		    }
 4005: 		}
 4006:                 if (lc($tagname) eq 'embed') {
 4007:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4008:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4009:                                              $attr->{'src'});
 4010:                     }
 4011:                 }
 4012: 	    }
 4013:             if (lc($tagname) eq 'iframe') {
 4014:                 my $src = $attr->{'src'} ;
 4015:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4016:                     &add_filetype($allfiles,$src,'src');
 4017:                 } elsif ($src =~ m{^/}) {
 4018:                     if ($env{'request.course.id'}) {
 4019:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4020:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4021:                         my $url = &hreflocation('',$fullpath);
 4022:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4023:                             my $relpath = $1;
 4024:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4025:                                 &add_filetype($allfiles,$1,'src');
 4026:                             }
 4027:                         }
 4028:                     }
 4029:                 }
 4030:             }
 4031:             if ($t->[4] =~ m{/>$}) {
 4032:                 pop(@state);
 4033:             }
 4034: 	} elsif ($t->[0] eq 'E') {
 4035: 	    my ($tagname) = ($t->[1]);
 4036: 	    if ($javafiles{'codebase'} ne '') {
 4037: 		$javafiles{'codebase'} .= '/';
 4038: 	    }  
 4039: 	    if (lc($tagname) eq 'applet' ||
 4040: 		lc($tagname) eq 'object' ||
 4041: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4042: 		) {
 4043: 		foreach my $item (keys(%javafiles)) {
 4044: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4045: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4046: 			&add_filetype($allfiles,$file,$item);
 4047: 		    }
 4048: 		}
 4049: 	    } 
 4050: 	    pop @state;
 4051: 	}
 4052:     }
 4053:     foreach my $id (sort(keys(%flashvars))) {
 4054:         if ($shockwave{$id} ne '') {
 4055:             my @pairs = split(/\&/,$flashvars{$id});
 4056:             foreach my $pair (@pairs) {
 4057:                 my ($key,$value) = split(/\=/,$pair);
 4058:                 if ($key eq 'thumb') {
 4059:                     &add_filetype($allfiles,$value,$key);
 4060:                 } elsif ($key eq 'content') {
 4061:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4062:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4063:                     if ($ext ne '') {
 4064:                         &add_filetype($allfiles,$path.$value,$ext);
 4065:                     }
 4066:                 }
 4067:             }
 4068:         }
 4069:     }
 4070:     return 'ok';
 4071: }
 4072: 
 4073: sub add_filetype {
 4074:     my ($allfiles,$file,$type)=@_;
 4075:     if (exists($allfiles->{$file})) {
 4076: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4077: 	    push(@{$allfiles->{$file}}, &escape($type));
 4078: 	}
 4079:     } else {
 4080: 	@{$allfiles->{$file}} = (&escape($type));
 4081:     }
 4082: }
 4083: 
 4084: sub embedded_dependency {
 4085:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4086:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4087:         if (($identifier ne '') &&
 4088:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4089:             ($pathfrom ne '')) {
 4090:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4091:             foreach my $dep (@{$related->{$identifier}}) {
 4092:                 &add_filetype($allfiles,$path.$dep,'object');
 4093:             }
 4094:         }
 4095:     }
 4096:     return;
 4097: }
 4098: 
 4099: sub removeuploadedurl {
 4100:     my ($url)=@_;	
 4101:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4102:     return &removeuserfile($uname,$udom,$fname);
 4103: }
 4104: 
 4105: sub removeuserfile {
 4106:     my ($docuname,$docudom,$fname)=@_;
 4107:     my $home=&homeserver($docuname,$docudom);    
 4108:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4109:     if ($result eq 'ok') {	
 4110:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4111:             my $metafile = $fname.'.meta';
 4112:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4113: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4114:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4115:             my $sqlresult = 
 4116:                 &update_portfolio_table($docuname,$docudom,$file,
 4117:                                         'portfolio_metadata',$group,
 4118:                                         'delete');
 4119:         }
 4120:     }
 4121:     return $result;
 4122: }
 4123: 
 4124: sub mkdiruserfile {
 4125:     my ($docuname,$docudom,$dir)=@_;
 4126:     my $home=&homeserver($docuname,$docudom);
 4127:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4128: }
 4129: 
 4130: sub renameuserfile {
 4131:     my ($docuname,$docudom,$old,$new)=@_;
 4132:     my $home=&homeserver($docuname,$docudom);
 4133:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4134:                         &escape("$old").':'.&escape("$new"),$home);
 4135:     if ($result eq 'ok') {
 4136:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4137:             my $oldmeta = $old.'.meta';
 4138:             my $newmeta = $new.'.meta';
 4139:             my $metaresult = 
 4140:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4141: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4142:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4143:             my $sqlresult = 
 4144:                 &update_portfolio_table($docuname,$docudom,$file,
 4145:                                         'portfolio_metadata',$group,
 4146:                                         'delete');
 4147:         }
 4148:     }
 4149:     return $result;
 4150: }
 4151: 
 4152: # ------------------------------------------------------------------------- Log
 4153: 
 4154: sub log {
 4155:     my ($dom,$nam,$hom,$what)=@_;
 4156:     return critical("log:$dom:$nam:$what",$hom);
 4157: }
 4158: 
 4159: # ------------------------------------------------------------------ Course Log
 4160: #
 4161: # This routine flushes several buffers of non-mission-critical nature
 4162: #
 4163: 
 4164: sub flushcourselogs {
 4165:     &logthis('Flushing log buffers');
 4166: #
 4167: # course logs
 4168: # This is a log of all transactions in a course, which can be used
 4169: # for data mining purposes
 4170: #
 4171: # It also collects the courseid database, which lists last transaction
 4172: # times and course titles for all courseids
 4173: #
 4174:     my %courseidbuffer=();
 4175:     foreach my $crsid (keys(%courselogs)) {
 4176:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4177: 		          &escape($courselogs{$crsid}),
 4178: 		          $coursehombuf{$crsid}) eq 'ok') {
 4179: 	    delete $courselogs{$crsid};
 4180:         } else {
 4181:             &logthis('Failed to flush log buffer for '.$crsid);
 4182:             if (length($courselogs{$crsid})>40000) {
 4183:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4184:                         " exceeded maximum size, deleting.</font>");
 4185:                delete $courselogs{$crsid};
 4186:             }
 4187:         }
 4188:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4189:             'description' => $coursedescrbuf{$crsid},
 4190:             'inst_code'    => $courseinstcodebuf{$crsid},
 4191:             'type'        => $coursetypebuf{$crsid},
 4192:             'owner'       => $courseownerbuf{$crsid},
 4193:         };
 4194:     }
 4195: #
 4196: # Write course id database (reverse lookup) to homeserver of courses 
 4197: # Is used in pickcourse
 4198: #
 4199:     foreach my $crs_home (keys(%courseidbuffer)) {
 4200:         my $response = &courseidput(&host_domain($crs_home),
 4201:                                     $courseidbuffer{$crs_home},
 4202:                                     $crs_home,'timeonly');
 4203:     }
 4204: #
 4205: # File accesses
 4206: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4207: #
 4208:     foreach my $entry (keys(%accesshash)) {
 4209:         if ($entry =~ /___count$/) {
 4210:             my ($dom,$name);
 4211:             ($dom,$name,undef)=
 4212: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4213:             if (! defined($dom) || $dom eq '' || 
 4214:                 ! defined($name) || $name eq '') {
 4215:                 my $cid = $env{'request.course.id'};
 4216:                 $dom  = $env{'request.'.$cid.'.domain'};
 4217:                 $name = $env{'request.'.$cid.'.num'};
 4218:             }
 4219:             my $value = $accesshash{$entry};
 4220:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4221:             my %temphash=($url => $value);
 4222:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4223:             if ($result eq 'ok') {
 4224:                 delete $accesshash{$entry};
 4225:             }
 4226:         } else {
 4227:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4228:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4229:             my %temphash=($entry => $accesshash{$entry});
 4230:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4231:                 delete $accesshash{$entry};
 4232:             }
 4233:         }
 4234:     }
 4235: #
 4236: # Roles
 4237: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4238: #
 4239:     foreach my $entry (keys(%userrolehash)) {
 4240:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4241: 	    split(/\:/,$entry);
 4242:         if (&Apache::lonnet::put('nohist_userroles',
 4243:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4244:                 $rudom,$runame) eq 'ok') {
 4245: 	    delete $userrolehash{$entry};
 4246:         }
 4247:     }
 4248: #
 4249: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4250: #
 4251:     my %domrolebuffer = ();
 4252:     foreach my $entry (keys(%domainrolehash)) {
 4253:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4254:         if ($domrolebuffer{$rudom}) {
 4255:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4256:                       '='.&escape($domainrolehash{$entry});
 4257:         } else {
 4258:             $domrolebuffer{$rudom}.=&escape($entry).
 4259:                       '='.&escape($domainrolehash{$entry});
 4260:         }
 4261:         delete $domainrolehash{$entry};
 4262:     }
 4263:     foreach my $dom (keys(%domrolebuffer)) {
 4264: 	my %servers;
 4265: 	if (defined(&domain($dom,'primary'))) {
 4266: 	    my $primary=&domain($dom,'primary');
 4267: 	    my $hostname=&hostname($primary);
 4268: 	    $servers{$primary} = $hostname;
 4269: 	} else { 
 4270: 	    %servers = &get_servers($dom,'library');
 4271: 	}
 4272: 	foreach my $tryserver (keys(%servers)) {
 4273: 	    if (&reply('domroleput:'.$dom.':'.
 4274: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4275: 		last;
 4276: 	    } else {  
 4277: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4278: 	    }
 4279:         }
 4280:     }
 4281:     $dumpcount++;
 4282: }
 4283: 
 4284: sub courselog {
 4285:     my $what=shift;
 4286:     $what=time.':'.$what;
 4287:     unless ($env{'request.course.id'}) { return ''; }
 4288:     $coursedombuf{$env{'request.course.id'}}=
 4289:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4290:     $coursenumbuf{$env{'request.course.id'}}=
 4291:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4292:     $coursehombuf{$env{'request.course.id'}}=
 4293:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4294:     $coursedescrbuf{$env{'request.course.id'}}=
 4295:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4296:     $courseinstcodebuf{$env{'request.course.id'}}=
 4297:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4298:     $courseownerbuf{$env{'request.course.id'}}=
 4299:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4300:     $coursetypebuf{$env{'request.course.id'}}=
 4301:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4302:     if (defined $courselogs{$env{'request.course.id'}}) {
 4303: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4304:     } else {
 4305: 	$courselogs{$env{'request.course.id'}}.=$what;
 4306:     }
 4307:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4308: 	&flushcourselogs();
 4309:     }
 4310: }
 4311: 
 4312: sub courseacclog {
 4313:     my $fnsymb=shift;
 4314:     unless ($env{'request.course.id'}) { return ''; }
 4315:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4316:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4317:         $what.=':POST';
 4318:         # FIXME: Probably ought to escape things....
 4319: 	foreach my $key (keys(%env)) {
 4320:             if ($key=~/^form\.(.*)/) {
 4321:                 my $formitem = $1;
 4322:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4323:                     $what.=':'.$formitem.'='.$env{$key};
 4324:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4325:                     $what.=':'.$formitem.'='.$env{$key};
 4326:                 }
 4327:             }
 4328:         }
 4329:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4330:         # FIXME: We should not be depending on a form parameter that someone
 4331:         # editing lonsearchcat.pm might change in the future.
 4332:         if ($env{'form.phase'} eq 'course_search') {
 4333:             $what.= ':POST';
 4334:             # FIXME: Probably ought to escape things....
 4335:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4336:                                  'crsdiscuss') {
 4337:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4338:             }
 4339:         }
 4340:     }
 4341:     &courselog($what);
 4342: }
 4343: 
 4344: sub countacc {
 4345:     my $url=&declutter(shift);
 4346:     return if (! defined($url) || $url eq '');
 4347:     unless ($env{'request.course.id'}) { return ''; }
 4348: #
 4349: # Mark that this url was used in this course
 4350: #
 4351:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4352: #
 4353: # Increase the access count for this resource in this child process
 4354: #
 4355:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4356:     $accesshash{$key}++;
 4357: }
 4358: 
 4359: sub linklog {
 4360:     my ($from,$to)=@_;
 4361:     $from=&declutter($from);
 4362:     $to=&declutter($to);
 4363:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4364:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4365: }
 4366: 
 4367: sub statslog {
 4368:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4369:     if ($users<2) { return; }
 4370:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4371:             'course'       => $env{'request.course.id'},
 4372:             'sections'     => '"all"',
 4373:             'num_students' => $users,
 4374:             'part'         => $part,
 4375:             'symb'         => $symb,
 4376:             'mean_tries'   => $av_attempts,
 4377:             'deg_of_diff'  => $degdiff});
 4378:     foreach my $key (keys(%dynstore)) {
 4379:         $accesshash{$key}=$dynstore{$key};
 4380:     }
 4381: }
 4382:   
 4383: sub userrolelog {
 4384:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4385:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4386:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4387:        $userrolehash
 4388:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4389:                     =$tend.':'.$tstart;
 4390:     }
 4391:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4392:        $userrolehash
 4393:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4394:                     =$tend.':'.$tstart;
 4395:     }
 4396:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4397:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4398:        $domainrolehash
 4399:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4400:                     = $tend.':'.$tstart;
 4401:     }
 4402: }
 4403: 
 4404: sub courserolelog {
 4405:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4406:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4407:         my $cdom = $1;
 4408:         my $cnum = $2;
 4409:         my $sec = $3;
 4410:         my $namespace = 'rolelog';
 4411:         my %storehash = (
 4412:                            role    => $trole,
 4413:                            start   => $tstart,
 4414:                            end     => $tend,
 4415:                            selfenroll => $selfenroll,
 4416:                            context    => $context,
 4417:                         );
 4418:         if ($trole eq 'gr') {
 4419:             $namespace = 'groupslog';
 4420:             $storehash{'group'} = $sec;
 4421:         } else {
 4422:             $storehash{'section'} = $sec;
 4423:         }
 4424:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4425:                    $domain,$cnum,$cdom);
 4426:         if (($trole ne 'st') || ($sec ne '')) {
 4427:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4428:         }
 4429:     }
 4430:     return;
 4431: }
 4432: 
 4433: sub domainrolelog {
 4434:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4435:     if ($area =~ m{^/($match_domain)/$}) {
 4436:         my $cdom = $1;
 4437:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4438:         my $namespace = 'rolelog';
 4439:         my %storehash = (
 4440:                            role    => $trole,
 4441:                            start   => $tstart,
 4442:                            end     => $tend,
 4443:                            context => $context,
 4444:                         );
 4445:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4446:                    $domain,$domconfiguser,$cdom);
 4447:     }
 4448:     return;
 4449: 
 4450: }
 4451: 
 4452: sub coauthorrolelog {
 4453:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4454:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4455:         my $audom = $1;
 4456:         my $auname = $2;
 4457:         my $namespace = 'rolelog';
 4458:         my %storehash = (
 4459:                            role    => $trole,
 4460:                            start   => $tstart,
 4461:                            end     => $tend,
 4462:                            context => $context,
 4463:                         );
 4464:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4465:                    $domain,$auname,$audom);
 4466:     }
 4467:     return;
 4468: }
 4469: 
 4470: sub get_course_adv_roles {
 4471:     my ($cid,$codes) = @_;
 4472:     $cid=$env{'request.course.id'} unless (defined($cid));
 4473:     my %coursehash=&coursedescription($cid);
 4474:     my $crstype = &Apache::loncommon::course_type($cid);
 4475:     my %nothide=();
 4476:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4477:         if ($user !~ /:/) {
 4478: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4479:         } else {
 4480:             $nothide{$user}=1;
 4481:         }
 4482:     }
 4483:     my @possdoms = ($coursehash{'domain'});
 4484:     if ($coursehash{'checkforpriv'}) {
 4485:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4486:     }
 4487:     my %returnhash=();
 4488:     my %dumphash=
 4489:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4490:     my $now=time;
 4491:     my %privileged;
 4492:     foreach my $entry (keys(%dumphash)) {
 4493: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4494:         if (($tstart) && ($tstart<0)) { next; }
 4495:         if (($tend) && ($tend<$now)) { next; }
 4496:         if (($tstart) && ($now<$tstart)) { next; }
 4497:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4498: 	if ($username eq '' || $domain eq '') { next; }
 4499:         if ((&privileged($username,$domain,\@possdoms)) &&
 4500:             (!$nothide{$username.':'.$domain})) { next; }
 4501: 	if ($role eq 'cr') { next; }
 4502:         if ($codes) {
 4503:             if ($section) { $role .= ':'.$section; }
 4504:             if ($returnhash{$role}) {
 4505:                 $returnhash{$role}.=','.$username.':'.$domain;
 4506:             } else {
 4507:                 $returnhash{$role}=$username.':'.$domain;
 4508:             }
 4509:         } else {
 4510:             my $key=&plaintext($role,$crstype);
 4511:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4512:             if ($returnhash{$key}) {
 4513: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4514:             } else {
 4515:                 $returnhash{$key}=$username.':'.$domain;
 4516:             }
 4517:         }
 4518:     }
 4519:     return %returnhash;
 4520: }
 4521: 
 4522: sub get_my_roles {
 4523:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4524:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4525:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4526:     my (%dumphash,%nothide);
 4527:     if ($context eq 'userroles') {
 4528:         %dumphash = &dump('roles',$udom,$uname);
 4529:     } else {
 4530:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4531:         if ($hidepriv) {
 4532:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4533:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4534:                 if ($user !~ /:/) {
 4535:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4536:                 } else {
 4537:                     $nothide{$user} = 1;
 4538:                 }
 4539:             }
 4540:         }
 4541:     }
 4542:     my %returnhash=();
 4543:     my $now=time;
 4544:     my %privileged;
 4545:     foreach my $entry (keys(%dumphash)) {
 4546:         my ($role,$tend,$tstart);
 4547:         if ($context eq 'userroles') {
 4548:             next if ($entry =~ /^rolesdef/);
 4549: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4550:         } else {
 4551:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4552:         }
 4553:         if (($tstart) && ($tstart<0)) { next; }
 4554:         my $status = 'active';
 4555:         if (($tend) && ($tend<=$now)) {
 4556:             $status = 'previous';
 4557:         } 
 4558:         if (($tstart) && ($now<$tstart)) {
 4559:             $status = 'future';
 4560:         }
 4561:         if (ref($types) eq 'ARRAY') {
 4562:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4563:                 next;
 4564:             } 
 4565:         } else {
 4566:             if ($status ne 'active') {
 4567:                 next;
 4568:             }
 4569:         }
 4570:         my ($rolecode,$username,$domain,$section,$area);
 4571:         if ($context eq 'userroles') {
 4572:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4573:             (undef,$domain,$username,$section) = split(/\//,$area);
 4574:         } else {
 4575:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4576:         }
 4577:         if (ref($roledoms) eq 'ARRAY') {
 4578:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4579:                 next;
 4580:             }
 4581:         }
 4582:         if (ref($roles) eq 'ARRAY') {
 4583:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4584:                 if ($role =~ /^cr\//) {
 4585:                     if (!grep(/^cr$/,@{$roles})) {
 4586:                         next;
 4587:                     }
 4588:                 } elsif ($role =~ /^gr\//) {
 4589:                     if (!grep(/^gr$/,@{$roles})) {
 4590:                         next;
 4591:                     }
 4592:                 } else {
 4593:                     next;
 4594:                 }
 4595:             }
 4596:         }
 4597:         if ($hidepriv) {
 4598:             my @privroles = ('dc','su');
 4599:             if ($context eq 'userroles') {
 4600:                 next if (grep(/^\Q$role\E$/,@privroles));
 4601:             } else {
 4602:                 my $possdoms = [$domain];
 4603:                 if (ref($roledoms) eq 'ARRAY') {
 4604:                    push(@{$possdoms},@{$roledoms}); 
 4605:                 }
 4606:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4607:                     if (!$nothide{$username.':'.$domain}) {
 4608:                         next;
 4609:                     }
 4610:                 }
 4611:             }
 4612:         }
 4613:         if ($withsec) {
 4614:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4615:                 $tstart.':'.$tend;
 4616:         } else {
 4617:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4618:         }
 4619:     }
 4620:     return %returnhash;
 4621: }
 4622: 
 4623: sub get_all_adhocroles {
 4624:     my ($dom) = @_;
 4625:     my @roles_by_num = ();
 4626:     my %domdefaults = &get_domain_defaults($dom);
 4627:     my (%description,%access_in_dom,%access_info);
 4628:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4629:         my $count = 0;
 4630:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4631:         my %ordered;
 4632:         foreach my $role (sort(keys(%domcurrent))) {
 4633:             my ($order,$desc,$access_in_dom);
 4634:             if (ref($domcurrent{$role}) eq 'HASH') {
 4635:                 $order = $domcurrent{$role}{'order'};
 4636:                 $desc = $domcurrent{$role}{'desc'};
 4637:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4638:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4639:             }
 4640:             if ($order eq '') {
 4641:                 $order = $count;
 4642:             }
 4643:             $ordered{$order} = $role;
 4644:             if ($desc ne '') {
 4645:                 $description{$role} = $desc;
 4646:             } else {
 4647:                 $description{$role}= $role;
 4648:             }
 4649:             $count++;
 4650:         }
 4651:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4652:             push(@roles_by_num,$ordered{$item});
 4653:         }
 4654:     }
 4655:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4656: }
 4657: 
 4658: sub get_my_adhocroles {
 4659:     my ($cid,$checkreg) = @_;
 4660:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4661:     if ($env{'request.course.id'} eq $cid) {
 4662:         $cdom = $env{'course.'.$cid.'.domain'};
 4663:         $cnum = $env{'course.'.$cid.'.num'};
 4664:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4665:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4666:         $cdom = $1;
 4667:         $cnum = $2;
 4668:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4669:                                      $cdom,$cnum);
 4670:     }
 4671:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4672:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4673:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4674:         if ($rosterhash{$user} ne '') {
 4675:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4676:             return ([],{}) if ($type eq 'auto');
 4677:         }
 4678:     }
 4679:     if (($cdom ne '') && ($cnum ne ''))  {
 4680:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4681:             my $then=$env{'user.login.time'};
 4682:             my $update=$env{'user.update.time'};
 4683:             if (!$update) {
 4684:                 $update = $then;
 4685:             }
 4686:             my @liveroles;
 4687:             foreach my $role ('dh','da') {
 4688:                 if ($env{"user.role.$role./$cdom/"}) {
 4689:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4690:                     my $limit = $update;
 4691:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4692:                         $limit = $then;
 4693:                     }
 4694:                     my $activerole = 1;
 4695:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4696:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4697:                     if ($activerole) {
 4698:                         push(@liveroles,$role);
 4699:                     }
 4700:                 }
 4701:             }
 4702:             if (@liveroles) {
 4703:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4704:                     my ($accessref,$accessinfo,%access_in_dom);
 4705:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4706:                     if (ref($roles_by_num) eq 'ARRAY') {
 4707:                         if (@{$roles_by_num}) {
 4708:                             my %settings;
 4709:                             if ($env{'request.course.id'} eq $cid) {
 4710:                                 foreach my $envkey (keys(%env)) {
 4711:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4712:                                         $settings{$1} = $env{$envkey};
 4713:                                     }
 4714:                                 }
 4715:                             } else {
 4716:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4717:                             }
 4718:                             my %setincrs;
 4719:                             if ($settings{'internal.adhocaccess'}) {
 4720:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4721:                             }
 4722:                             my @statuses;
 4723:                             if ($env{'environment.inststatus'}) {
 4724:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4725:                             }
 4726:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4727:                             if (ref($accessref) eq 'HASH') {
 4728:                                 %access_in_dom = %{$accessref};
 4729:                             }
 4730:                             foreach my $role (@{$roles_by_num}) {
 4731:                                 my ($curraccess,@okstatus,@personnel);
 4732:                                 if ($setincrs{$role}) {
 4733:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4734:                                     if ($curraccess eq 'status') {
 4735:                                         @okstatus = split(/\&/,$rest);
 4736:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4737:                                         @personnel = split(/\&/,$rest);
 4738:                                     }
 4739:                                 } else {
 4740:                                     $curraccess = $access_in_dom{$role};
 4741:                                     if (ref($accessinfo) eq 'HASH') {
 4742:                                         if ($curraccess eq 'status') {
 4743:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4744:                                                 @okstatus = @{$accessinfo->{$role}};
 4745:                                             }
 4746:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4747:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4748:                                                 @personnel = @{$accessinfo->{$role}};
 4749:                                             }
 4750:                                         }
 4751:                                     }
 4752:                                 }
 4753:                                 if ($curraccess eq 'none') {
 4754:                                     next;
 4755:                                 } elsif ($curraccess eq 'all') {
 4756:                                     push(@possroles,$role);
 4757:                                 } elsif ($curraccess eq 'dh') {
 4758:                                     if (grep(/^dh$/,@liveroles)) {
 4759:                                         push(@possroles,$role);
 4760:                                     } else {
 4761:                                         next;
 4762:                                     }
 4763:                                 } elsif ($curraccess eq 'da') {
 4764:                                     if (grep(/^da$/,@liveroles)) {
 4765:                                         push(@possroles,$role);
 4766:                                     } else {
 4767:                                         next;
 4768:                                     }
 4769:                                 } elsif ($curraccess eq 'status') {
 4770:                                     if (@okstatus) {
 4771:                                         if (!@statuses) {
 4772:                                             if (grep(/^default$/,@okstatus)) {
 4773:                                                 push(@possroles,$role);
 4774:                                             }
 4775:                                         } else {
 4776:                                             foreach my $status (@okstatus) {
 4777:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 4778:                                                     push(@possroles,$role);
 4779:                                                     last;
 4780:                                                 }
 4781:                                             }
 4782:                                         }
 4783:                                     }
 4784:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4785:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 4786:                                         if ($curraccess eq 'exc') {
 4787:                                             push(@possroles,$role);
 4788:                                         }
 4789:                                     } elsif ($curraccess eq 'inc') {
 4790:                                         push(@possroles,$role);
 4791:                                     }
 4792:                                 }
 4793:                             }
 4794:                         }
 4795:                     }
 4796:                 }
 4797:             }
 4798:         }
 4799:     }
 4800:     unless (ref($description) eq 'HASH') {
 4801:         if (ref($roles_by_num) eq 'ARRAY') {
 4802:             my %desc;
 4803:             map { $desc{$_} = $_; } (@{$roles_by_num});
 4804:             $description = \%desc;
 4805:         } else {
 4806:             $description = {};
 4807:         }
 4808:     }
 4809:     return (\@possroles,$description);
 4810: }
 4811: 
 4812: # ----------------------------------------------------- Frontpage Announcements
 4813: #
 4814: #
 4815: 
 4816: sub postannounce {
 4817:     my ($server,$text)=@_;
 4818:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4819:     unless ($text=~/\w/) { $text=''; }
 4820:     return &reply('setannounce:'.&escape($text),$server);
 4821: }
 4822: 
 4823: sub getannounce {
 4824: 
 4825:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4826: 	my $announcement='';
 4827: 	while (my $line = <$fh>) { $announcement .= $line; }
 4828: 	close($fh);
 4829: 	if ($announcement=~/\w/) { 
 4830: 	    return 
 4831:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4832:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4833: 	} else {
 4834: 	    return '';
 4835: 	}
 4836:     } else {
 4837: 	return '';
 4838:     }
 4839: }
 4840: 
 4841: # ---------------------------------------------------------- Course ID routines
 4842: # Deal with domain's nohist_courseid.db files
 4843: #
 4844: 
 4845: sub courseidput {
 4846:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4847:     return unless (ref($storehash) eq 'HASH');
 4848:     my $outcome;
 4849:     if ($caller eq 'timeonly') {
 4850:         my $cids = '';
 4851:         foreach my $item (keys(%$storehash)) {
 4852:             $cids.=&escape($item).'&';
 4853:         }
 4854:         $cids=~s/\&$//;
 4855:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4856:                           $coursehome);       
 4857:     } else {
 4858:         my $items = '';
 4859:         foreach my $item (keys(%$storehash)) {
 4860:             $items.= &escape($item).'='.
 4861:                      &freeze_escape($$storehash{$item}).'&';
 4862:         }
 4863:         $items=~s/\&$//;
 4864:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4865:                           $coursehome);
 4866:     }
 4867:     if ($outcome eq 'unknown_cmd') {
 4868:         my $what;
 4869:         foreach my $cid (keys(%$storehash)) {
 4870:             $what .= &escape($cid).'=';
 4871:             foreach my $item ('description','inst_code','owner','type') {
 4872:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4873:             }
 4874:             $what =~ s/\:$/&/;
 4875:         }
 4876:         $what =~ s/\&$//;  
 4877:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4878:     } else {
 4879:         return $outcome;
 4880:     }
 4881: }
 4882: 
 4883: sub courseiddump {
 4884:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4885:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4886:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4887:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4888:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 4889:     my $as_hash = 1;
 4890:     my %returnhash;
 4891:     if (!$domfilter) { $domfilter=''; }
 4892:     my %libserv = &all_library();
 4893:     foreach my $tryserver (keys(%libserv)) {
 4894:         if ( (  $hostidflag == 1 
 4895: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4896: 	     || (!defined($hostidflag)) ) {
 4897: 
 4898: 	    if (($domfilter eq '') ||
 4899: 		(&host_domain($tryserver) eq $domfilter)) {
 4900:                 my $rep;
 4901:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4902:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4903:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4904:                                 &escape($descfilter), &escape($instcodefilter), 
 4905:                                 &escape($ownerfilter), &escape($coursefilter),
 4906:                                 &escape($typefilter), &escape($regexp_ok), 
 4907:                                 $as_hash, &escape($selfenrollonly), 
 4908:                                 &escape($catfilter), $showhidden, $caller, 
 4909:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4910:                                 &escape($createdbefore), &escape($createdafter), 
 4911:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 4912:                                 $reqcrsdom,&escape($reqinstcode))));
 4913:                 } else {
 4914:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4915:                              $sincefilter.':'.&escape($descfilter).':'.
 4916:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4917:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4918:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4919:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4920:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4921:                              &escape($cc_clone).':'.$cloneonly.':'.
 4922:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4923:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 4924:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 4925:                 }
 4926:                      
 4927:                 my @pairs=split(/\&/,$rep);
 4928:                 foreach my $item (@pairs) {
 4929:                     my ($key,$value)=split(/\=/,$item,2);
 4930:                     $key = &unescape($key);
 4931:                     next if ($key =~ /^error: 2 /);
 4932:                     my $result = &thaw_unescape($value);
 4933:                     if (ref($result) eq 'HASH') {
 4934:                         $returnhash{$key}=$result;
 4935:                     } else {
 4936:                         my @responses = split(/:/,$value);
 4937:                         my @items = ('description','inst_code','owner','type');
 4938:                         for (my $i=0; $i<@responses; $i++) {
 4939:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4940:                         }
 4941:                     }
 4942:                 }
 4943:             }
 4944:         }
 4945:     }
 4946:     return %returnhash;
 4947: }
 4948: 
 4949: sub courselastaccess {
 4950:     my ($cdom,$cnum,$hostidref) = @_;
 4951:     my %returnhash;
 4952:     if ($cdom && $cnum) {
 4953:         my $chome = &homeserver($cnum,$cdom);
 4954:         if ($chome ne 'no_host') {
 4955:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4956:             &extract_lastaccess(\%returnhash,$rep);
 4957:         }
 4958:     } else {
 4959:         if (!$cdom) { $cdom=''; }
 4960:         my %libserv = &all_library();
 4961:         foreach my $tryserver (keys(%libserv)) {
 4962:             if (ref($hostidref) eq 'ARRAY') {
 4963:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4964:             } 
 4965:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4966:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4967:                 &extract_lastaccess(\%returnhash,$rep);
 4968:             }
 4969:         }
 4970:     }
 4971:     return %returnhash;
 4972: }
 4973: 
 4974: sub extract_lastaccess {
 4975:     my ($returnhash,$rep) = @_;
 4976:     if (ref($returnhash) eq 'HASH') {
 4977:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4978:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4979:                  $rep eq '') {
 4980:             my @pairs=split(/\&/,$rep);
 4981:             foreach my $item (@pairs) {
 4982:                 my ($key,$value)=split(/\=/,$item,2);
 4983:                 $key = &unescape($key);
 4984:                 next if ($key =~ /^error: 2 /);
 4985:                 $returnhash->{$key} = &thaw_unescape($value);
 4986:             }
 4987:         }
 4988:     }
 4989:     return;
 4990: }
 4991: 
 4992: # ---------------------------------------------------------- DC e-mail
 4993: 
 4994: sub dcmailput {
 4995:     my ($domain,$msgid,$message,$server)=@_;
 4996:     my $status = &Apache::lonnet::critical(
 4997:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4998:        &escape($message),$server);
 4999:     return $status;
 5000: }
 5001: 
 5002: sub dcmaildump {
 5003:     my ($dom,$startdate,$enddate,$senders) = @_;
 5004:     my %returnhash=();
 5005: 
 5006:     if (defined(&domain($dom,'primary'))) {
 5007:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5008:                                                          &escape($enddate).':';
 5009: 	my @esc_senders=map { &escape($_)} @$senders;
 5010: 	$cmd.=&escape(join('&',@esc_senders));
 5011: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5012:             my ($key,$value) = split(/\=/,$line,2);
 5013:             if (($key) && ($value)) {
 5014:                 $returnhash{&unescape($key)} = &unescape($value);
 5015:             }
 5016:         }
 5017:     }
 5018:     return %returnhash;
 5019: }
 5020: # ---------------------------------------------------------- Domain roles
 5021: 
 5022: sub get_domain_roles {
 5023:     my ($dom,$roles,$startdate,$enddate)=@_;
 5024:     if ((!defined($startdate)) || ($startdate eq '')) {
 5025:         $startdate = '.';
 5026:     }
 5027:     if ((!defined($enddate)) || ($enddate eq '')) {
 5028:         $enddate = '.';
 5029:     }
 5030:     my $rolelist;
 5031:     if (ref($roles) eq 'ARRAY') {
 5032:         $rolelist = join('&',@{$roles});
 5033:     }
 5034:     my %personnel = ();
 5035: 
 5036:     my %servers = &get_servers($dom,'library');
 5037:     foreach my $tryserver (keys(%servers)) {
 5038: 	%{$personnel{$tryserver}}=();
 5039: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5040: 					    &escape($startdate).':'.
 5041: 					    &escape($enddate).':'.
 5042: 					    &escape($rolelist), $tryserver))) {
 5043: 	    my ($key,$value) = split(/\=/,$line,2);
 5044: 	    if (($key) && ($value)) {
 5045: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5046: 	    }
 5047: 	}
 5048:     }
 5049:     return %personnel;
 5050: }
 5051: 
 5052: sub get_active_domroles {
 5053:     my ($dom,$roles) = @_;
 5054:     return () unless (ref($roles) eq 'ARRAY');
 5055:     my $now = time;
 5056:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5057:     my %domroles;
 5058:     foreach my $server (keys(%dompersonnel)) {
 5059:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5060:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5061:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5062:         }
 5063:     }
 5064:     return %domroles;
 5065: }
 5066: 
 5067: # ----------------------------------------------------------- Interval timing 
 5068: 
 5069: {
 5070: # Caches needed for speedup of navmaps
 5071: # We don't want to cache this for very long at all (5 seconds at most)
 5072: # 
 5073: # The user for whom we cache
 5074: my $cachedkey='';
 5075: # The cached times for this user
 5076: my %cachedtimes=();
 5077: # When this was last done
 5078: my $cachedtime='';
 5079: 
 5080: sub load_all_first_access {
 5081:     my ($uname,$udom,$ignorecache)=@_;
 5082:     if (($cachedkey eq $uname.':'.$udom) &&
 5083:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5084:         (!$ignorecache)) {
 5085:         return;
 5086:     }
 5087:     $cachedtime=time;
 5088:     $cachedkey=$uname.':'.$udom;
 5089:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5090: }
 5091: 
 5092: sub get_first_access {
 5093:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5094:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5095:     if ($argsymb) { $symb=$argsymb; }
 5096:     my ($map,$id,$res)=&decode_symb($symb);
 5097:     if ($argmap) { $map = $argmap; }
 5098:     if ($type eq 'course') {
 5099: 	$res='course';
 5100:     } elsif ($type eq 'map') {
 5101: 	$res=&symbread($map);
 5102:     } else {
 5103: 	$res=$symb;
 5104:     }
 5105:     &load_all_first_access($uname,$udom,$ignorecache);
 5106:     return $cachedtimes{"$courseid\0$res"};
 5107: }
 5108: 
 5109: sub set_first_access {
 5110:     my ($type,$interval)=@_;
 5111:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5112:     my ($map,$id,$res)=&decode_symb($symb);
 5113:     if ($type eq 'course') {
 5114: 	$res='course';
 5115:     } elsif ($type eq 'map') {
 5116: 	$res=&symbread($map);
 5117:     } else {
 5118: 	$res=$symb;
 5119:     }
 5120:     $cachedkey='';
 5121:     my $firstaccess=&get_first_access($type,$symb,$map);
 5122:     if (!$firstaccess) {
 5123:         my $start = time;
 5124: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5125:                           $udom,$uname);
 5126:         if ($putres eq 'ok') {
 5127:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5128:                  $udom,$uname); 
 5129:             &appenv(
 5130:                      {
 5131:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5132:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5133:                      }
 5134:                   );
 5135:         }
 5136:         return $putres;
 5137:     }
 5138:     return 'already_set';
 5139: }
 5140: }
 5141: 
 5142: # --------------------------------------------- Set Expire Date for Spreadsheet
 5143: 
 5144: sub expirespread {
 5145:     my ($uname,$udom,$stype,$usymb)=@_;
 5146:     my $cid=$env{'request.course.id'}; 
 5147:     if ($cid) {
 5148:        my $now=time;
 5149:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5150:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5151:                             $env{'course.'.$cid.'.num'}.
 5152: 	        	    ':nohist_expirationdates:'.
 5153:                             &escape($key).'='.$now,
 5154:                             $env{'course.'.$cid.'.home'})
 5155:     }
 5156:     return 'ok';
 5157: }
 5158: 
 5159: # ----------------------------------------------------- Devalidate Spreadsheets
 5160: 
 5161: sub devalidate {
 5162:     my ($symb,$uname,$udom)=@_;
 5163:     my $cid=$env{'request.course.id'}; 
 5164:     if ($cid) {
 5165:         # delete the stored spreadsheets for
 5166:         # - the student level sheet of this user in course's homespace
 5167:         # - the assessment level sheet for this resource 
 5168:         #   for this user in user's homespace
 5169: 	# - current conditional state info
 5170: 	my $key=$uname.':'.$udom.':';
 5171:         my $status=
 5172: 	    &del('nohist_calculatedsheets',
 5173: 		 [$key.'studentcalc:'],
 5174: 		 $env{'course.'.$cid.'.domain'},
 5175: 		 $env{'course.'.$cid.'.num'})
 5176: 		.' '.
 5177: 	    &del('nohist_calculatedsheets_'.$cid,
 5178: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5179:         unless ($status eq 'ok ok') {
 5180:            &logthis('Could not devalidate spreadsheet '.
 5181:                     $uname.' at '.$udom.' for '.
 5182: 		    $symb.': '.$status);
 5183:         }
 5184: 	&delenv('user.state.'.$cid);
 5185:     }
 5186: }
 5187: 
 5188: sub get_scalar {
 5189:     my ($string,$end) = @_;
 5190:     my $value;
 5191:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5192: 	$value = $1;
 5193:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5194: 	$value = $1;
 5195:     }
 5196:     return &unescape($value);
 5197: }
 5198: 
 5199: sub array2str {
 5200:   my (@array) = @_;
 5201:   my $result=&arrayref2str(\@array);
 5202:   $result=~s/^__ARRAY_REF__//;
 5203:   $result=~s/__END_ARRAY_REF__$//;
 5204:   return $result;
 5205: }
 5206: 
 5207: sub arrayref2str {
 5208:   my ($arrayref) = @_;
 5209:   my $result='__ARRAY_REF__';
 5210:   foreach my $elem (@$arrayref) {
 5211:     if(ref($elem) eq 'ARRAY') {
 5212:       $result.=&arrayref2str($elem).'&';
 5213:     } elsif(ref($elem) eq 'HASH') {
 5214:       $result.=&hashref2str($elem).'&';
 5215:     } elsif(ref($elem)) {
 5216:       #print("Got a ref of ".(ref($elem))." skipping.");
 5217:     } else {
 5218:       $result.=&escape($elem).'&';
 5219:     }
 5220:   }
 5221:   $result=~s/\&$//;
 5222:   $result .= '__END_ARRAY_REF__';
 5223:   return $result;
 5224: }
 5225: 
 5226: sub hash2str {
 5227:   my (%hash) = @_;
 5228:   my $result=&hashref2str(\%hash);
 5229:   $result=~s/^__HASH_REF__//;
 5230:   $result=~s/__END_HASH_REF__$//;
 5231:   return $result;
 5232: }
 5233: 
 5234: sub hashref2str {
 5235:   my ($hashref)=@_;
 5236:   my $result='__HASH_REF__';
 5237:   foreach my $key (sort(keys(%$hashref))) {
 5238:     if (ref($key) eq 'ARRAY') {
 5239:       $result.=&arrayref2str($key).'=';
 5240:     } elsif (ref($key) eq 'HASH') {
 5241:       $result.=&hashref2str($key).'=';
 5242:     } elsif (ref($key)) {
 5243:       $result.='=';
 5244:       #print("Got a ref of ".(ref($key))." skipping.");
 5245:     } else {
 5246: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5247:     }
 5248: 
 5249:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5250:       $result.=&arrayref2str($hashref->{$key}).'&';
 5251:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5252:       $result.=&hashref2str($hashref->{$key}).'&';
 5253:     } elsif(ref($hashref->{$key})) {
 5254:        $result.='&';
 5255:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5256:     } else {
 5257:       $result.=&escape($hashref->{$key}).'&';
 5258:     }
 5259:   }
 5260:   $result=~s/\&$//;
 5261:   $result .= '__END_HASH_REF__';
 5262:   return $result;
 5263: }
 5264: 
 5265: sub str2hash {
 5266:     my ($string)=@_;
 5267:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5268:     return %$hash;
 5269: }
 5270: 
 5271: sub str2hashref {
 5272:   my ($string) = @_;
 5273: 
 5274:   my %hash;
 5275: 
 5276:   if($string !~ /^__HASH_REF__/) {
 5277:       if (! ($string eq '' || !defined($string))) {
 5278: 	  $hash{'error'}='Not hash reference';
 5279:       }
 5280:       return (\%hash, $string);
 5281:   }
 5282: 
 5283:   $string =~ s/^__HASH_REF__//;
 5284: 
 5285:   while($string !~ /^__END_HASH_REF__/) {
 5286:       #key
 5287:       my $key='';
 5288:       if($string =~ /^__HASH_REF__/) {
 5289:           ($key, $string)=&str2hashref($string);
 5290:           if(defined($key->{'error'})) {
 5291:               $hash{'error'}='Bad data';
 5292:               return (\%hash, $string);
 5293:           }
 5294:       } elsif($string =~ /^__ARRAY_REF__/) {
 5295:           ($key, $string)=&str2arrayref($string);
 5296:           if($key->[0] eq 'Array reference error') {
 5297:               $hash{'error'}='Bad data';
 5298:               return (\%hash, $string);
 5299:           }
 5300:       } else {
 5301:           $string =~ s/^(.*?)=//;
 5302: 	  $key=&unescape($1);
 5303:       }
 5304:       $string =~ s/^=//;
 5305: 
 5306:       #value
 5307:       my $value='';
 5308:       if($string =~ /^__HASH_REF__/) {
 5309:           ($value, $string)=&str2hashref($string);
 5310:           if(defined($value->{'error'})) {
 5311:               $hash{'error'}='Bad data';
 5312:               return (\%hash, $string);
 5313:           }
 5314:       } elsif($string =~ /^__ARRAY_REF__/) {
 5315:           ($value, $string)=&str2arrayref($string);
 5316:           if($value->[0] eq 'Array reference error') {
 5317:               $hash{'error'}='Bad data';
 5318:               return (\%hash, $string);
 5319:           }
 5320:       } else {
 5321: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5322:       }
 5323:       $string =~ s/^&//;
 5324: 
 5325:       $hash{$key}=$value;
 5326:   }
 5327: 
 5328:   $string =~ s/^__END_HASH_REF__//;
 5329: 
 5330:   return (\%hash, $string);
 5331: }
 5332: 
 5333: sub str2array {
 5334:     my ($string)=@_;
 5335:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5336:     return @$array;
 5337: }
 5338: 
 5339: sub str2arrayref {
 5340:   my ($string) = @_;
 5341:   my @array;
 5342: 
 5343:   if($string !~ /^__ARRAY_REF__/) {
 5344:       if (! ($string eq '' || !defined($string))) {
 5345: 	  $array[0]='Array reference error';
 5346:       }
 5347:       return (\@array, $string);
 5348:   }
 5349: 
 5350:   $string =~ s/^__ARRAY_REF__//;
 5351: 
 5352:   while($string !~ /^__END_ARRAY_REF__/) {
 5353:       my $value='';
 5354:       if($string =~ /^__HASH_REF__/) {
 5355:           ($value, $string)=&str2hashref($string);
 5356:           if(defined($value->{'error'})) {
 5357:               $array[0] ='Array reference error';
 5358:               return (\@array, $string);
 5359:           }
 5360:       } elsif($string =~ /^__ARRAY_REF__/) {
 5361:           ($value, $string)=&str2arrayref($string);
 5362:           if($value->[0] eq 'Array reference error') {
 5363:               $array[0] ='Array reference error';
 5364:               return (\@array, $string);
 5365:           }
 5366:       } else {
 5367: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5368:       }
 5369:       $string =~ s/^&//;
 5370: 
 5371:       push(@array, $value);
 5372:   }
 5373: 
 5374:   $string =~ s/^__END_ARRAY_REF__//;
 5375: 
 5376:   return (\@array, $string);
 5377: }
 5378: 
 5379: # -------------------------------------------------------------------Temp Store
 5380: 
 5381: sub tmpreset {
 5382:   my ($symb,$namespace,$domain,$stuname) = @_;
 5383:   if (!$symb) {
 5384:     $symb=&symbread();
 5385:     if (!$symb) { $symb= $env{'request.url'}; }
 5386:   }
 5387:   $symb=escape($symb);
 5388: 
 5389:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5390:   $namespace=~s/\//\_/g;
 5391:   $namespace=~s/\W//g;
 5392: 
 5393:   if (!$domain) { $domain=$env{'user.domain'}; }
 5394:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5395:   if ($domain eq 'public' && $stuname eq 'public') {
 5396:       $stuname=$ENV{'REMOTE_ADDR'};
 5397:   }
 5398:   my $path=LONCAPA::tempdir();
 5399:   my %hash;
 5400:   if (tie(%hash,'GDBM_File',
 5401: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5402: 	  &GDBM_WRCREAT(),0640)) {
 5403:     foreach my $key (keys(%hash)) {
 5404:       if ($key=~ /:$symb/) {
 5405: 	delete($hash{$key});
 5406:       }
 5407:     }
 5408:   }
 5409: }
 5410: 
 5411: sub tmpstore {
 5412:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5413: 
 5414:   if (!$symb) {
 5415:     $symb=&symbread();
 5416:     if (!$symb) { $symb= $env{'request.url'}; }
 5417:   }
 5418:   $symb=escape($symb);
 5419: 
 5420:   if (!$namespace) {
 5421:     # I don't think we would ever want to store this for a course.
 5422:     # it seems this will only be used if we don't have a course.
 5423:     #$namespace=$env{'request.course.id'};
 5424:     #if (!$namespace) {
 5425:       $namespace=$env{'request.state'};
 5426:     #}
 5427:   }
 5428:   $namespace=~s/\//\_/g;
 5429:   $namespace=~s/\W//g;
 5430:   if (!$domain) { $domain=$env{'user.domain'}; }
 5431:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5432:   if ($domain eq 'public' && $stuname eq 'public') {
 5433:       $stuname=$ENV{'REMOTE_ADDR'};
 5434:   }
 5435:   my $now=time;
 5436:   my %hash;
 5437:   my $path=LONCAPA::tempdir();
 5438:   if (tie(%hash,'GDBM_File',
 5439: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5440: 	  &GDBM_WRCREAT(),0640)) {
 5441:     $hash{"version:$symb"}++;
 5442:     my $version=$hash{"version:$symb"};
 5443:     my $allkeys=''; 
 5444:     foreach my $key (keys(%$storehash)) {
 5445:       $allkeys.=$key.':';
 5446:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5447:     }
 5448:     $hash{"$version:$symb:timestamp"}=$now;
 5449:     $allkeys.='timestamp';
 5450:     $hash{"$version:keys:$symb"}=$allkeys;
 5451:     if (untie(%hash)) {
 5452:       return 'ok';
 5453:     } else {
 5454:       return "error:$!";
 5455:     }
 5456:   } else {
 5457:     return "error:$!";
 5458:   }
 5459: }
 5460: 
 5461: # -----------------------------------------------------------------Temp Restore
 5462: 
 5463: sub tmprestore {
 5464:   my ($symb,$namespace,$domain,$stuname) = @_;
 5465: 
 5466:   if (!$symb) {
 5467:     $symb=&symbread();
 5468:     if (!$symb) { $symb= $env{'request.url'}; }
 5469:   }
 5470:   $symb=escape($symb);
 5471: 
 5472:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5473: 
 5474:   if (!$domain) { $domain=$env{'user.domain'}; }
 5475:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5476:   if ($domain eq 'public' && $stuname eq 'public') {
 5477:       $stuname=$ENV{'REMOTE_ADDR'};
 5478:   }
 5479:   my %returnhash;
 5480:   $namespace=~s/\//\_/g;
 5481:   $namespace=~s/\W//g;
 5482:   my %hash;
 5483:   my $path=LONCAPA::tempdir();
 5484:   if (tie(%hash,'GDBM_File',
 5485: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5486: 	  &GDBM_READER(),0640)) {
 5487:     my $version=$hash{"version:$symb"};
 5488:     $returnhash{'version'}=$version;
 5489:     my $scope;
 5490:     for ($scope=1;$scope<=$version;$scope++) {
 5491:       my $vkeys=$hash{"$scope:keys:$symb"};
 5492:       my @keys=split(/:/,$vkeys);
 5493:       my $key;
 5494:       $returnhash{"$scope:keys"}=$vkeys;
 5495:       foreach $key (@keys) {
 5496: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5497: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5498:       }
 5499:     }
 5500:     if (!(untie(%hash))) {
 5501:       return "error:$!";
 5502:     }
 5503:   } else {
 5504:     return "error:$!";
 5505:   }
 5506:   return %returnhash;
 5507: }
 5508: 
 5509: # ----------------------------------------------------------------------- Store
 5510: 
 5511: sub store {
 5512:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5513:     my $home='';
 5514: 
 5515:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5516: 
 5517:     $symb=&symbclean($symb);
 5518:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5519: 
 5520:     if (!$domain) { $domain=$env{'user.domain'}; }
 5521:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5522: 
 5523:     &devalidate($symb,$stuname,$domain);
 5524: 
 5525:     $symb=escape($symb);
 5526:     if (!$namespace) { 
 5527:        unless ($namespace=$env{'request.course.id'}) { 
 5528:           return ''; 
 5529:        } 
 5530:     }
 5531:     if (!$home) { $home=$env{'user.home'}; }
 5532: 
 5533:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5534:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5535: 
 5536:     my $namevalue='';
 5537:     foreach my $key (keys(%$storehash)) {
 5538:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5539:     }
 5540:     $namevalue=~s/\&$//;
 5541:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5542:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5543: }
 5544: 
 5545: # -------------------------------------------------------------- Critical Store
 5546: 
 5547: sub cstore {
 5548:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5549:     my $home='';
 5550: 
 5551:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5552: 
 5553:     $symb=&symbclean($symb);
 5554:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5555: 
 5556:     if (!$domain) { $domain=$env{'user.domain'}; }
 5557:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5558: 
 5559:     &devalidate($symb,$stuname,$domain);
 5560: 
 5561:     $symb=escape($symb);
 5562:     if (!$namespace) { 
 5563:        unless ($namespace=$env{'request.course.id'}) { 
 5564:           return ''; 
 5565:        } 
 5566:     }
 5567:     if (!$home) { $home=$env{'user.home'}; }
 5568: 
 5569:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5570:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5571: 
 5572:     my $namevalue='';
 5573:     foreach my $key (keys(%$storehash)) {
 5574:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5575:     }
 5576:     $namevalue=~s/\&$//;
 5577:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5578:     return critical
 5579:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5580: }
 5581: 
 5582: # --------------------------------------------------------------------- Restore
 5583: 
 5584: sub restore {
 5585:     my ($symb,$namespace,$domain,$stuname) = @_;
 5586:     my $home='';
 5587: 
 5588:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5589: 
 5590:     if (!$symb) {
 5591:         return if ($namespace eq 'courserequests');
 5592:         unless ($symb=escape(&symbread())) { return ''; }
 5593:     } else {
 5594:         unless ($namespace eq 'courserequests') {
 5595:             $symb=&escape(&symbclean($symb));
 5596:         }
 5597:     }
 5598:     if (!$namespace) { 
 5599:        unless ($namespace=$env{'request.course.id'}) { 
 5600:           return ''; 
 5601:        } 
 5602:     }
 5603:     if (!$domain) { $domain=$env{'user.domain'}; }
 5604:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5605:     if (!$home) { $home=$env{'user.home'}; }
 5606:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5607: 
 5608:     my %returnhash=();
 5609:     foreach my $line (split(/\&/,$answer)) {
 5610: 	my ($name,$value)=split(/\=/,$line);
 5611:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5612:     }
 5613:     my $version;
 5614:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5615:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5616:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5617:        }
 5618:     }
 5619:     return %returnhash;
 5620: }
 5621: 
 5622: # ---------------------------------------------------------- Course Description
 5623: #
 5624: #  
 5625: 
 5626: sub coursedescription {
 5627:     my ($courseid,$args)=@_;
 5628:     $courseid=~s/^\///;
 5629:     $courseid=~s/\_/\//g;
 5630:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5631:     my $chome=&homeserver($cnum,$cdomain);
 5632:     my $normalid=$cdomain.'_'.$cnum;
 5633:     # need to always cache even if we get errors otherwise we keep 
 5634:     # trying and trying and trying to get the course description.
 5635:     my %envhash=();
 5636:     my %returnhash=();
 5637:     
 5638:     my $expiretime=600;
 5639:     if ($env{'request.course.id'} eq $normalid) {
 5640: 	$expiretime=120;
 5641:     }
 5642: 
 5643:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5644:     if (!$args->{'freshen_cache'}
 5645: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5646: 	foreach my $key (keys(%env)) {
 5647: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5648: 	    my ($setting) = $1;
 5649: 	    $returnhash{$setting} = $env{$key};
 5650: 	}
 5651: 	return %returnhash;
 5652:     }
 5653: 
 5654:     # get the data again
 5655: 
 5656:     if (!$args->{'one_time'}) {
 5657: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5658:     }
 5659: 
 5660:     if ($chome ne 'no_host') {
 5661:        %returnhash=&dump('environment',$cdomain,$cnum);
 5662:        if (!exists($returnhash{'con_lost'})) {
 5663: 	   my $username = $env{'user.name'}; # Defult username
 5664: 	   if(defined $args->{'user'}) {
 5665: 	       $username = $args->{'user'};
 5666: 	   }
 5667:            $returnhash{'home'}= $chome;
 5668: 	   $returnhash{'domain'} = $cdomain;
 5669: 	   $returnhash{'num'} = $cnum;
 5670:            if (!defined($returnhash{'type'})) {
 5671:                $returnhash{'type'} = 'Course';
 5672:            }
 5673:            while (my ($name,$value) = each %returnhash) {
 5674:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5675:            }
 5676:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5677:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5678: 	       $username.'_'.$cdomain.'_'.$cnum;
 5679:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5680:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5681:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5682:        }
 5683:     }
 5684:     if (!$args->{'one_time'}) {
 5685: 	&appenv(\%envhash);
 5686:     }
 5687:     return %returnhash;
 5688: }
 5689: 
 5690: sub update_released_required {
 5691:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5692:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5693:         $cid = $env{'request.course.id'};
 5694:         $cdom = $env{'course.'.$cid.'.domain'};
 5695:         $cnum = $env{'course.'.$cid.'.num'};
 5696:         $chome = $env{'course.'.$cid.'.home'};
 5697:     }
 5698:     if ($needsrelease) {
 5699:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5700:         my $needsupdate;
 5701:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5702:             $needsupdate = 1;
 5703:         } else {
 5704:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5705:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5706:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5707:                 $needsupdate = 1;
 5708:             }
 5709:         }
 5710:         if ($needsupdate) {
 5711:             my %needshash = (
 5712:                              'internal.releaserequired' => $needsrelease,
 5713:                             );
 5714:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5715:             if ($putresult eq 'ok') {
 5716:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5717:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5718:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5719:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5720:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5721:                 }
 5722:             }
 5723:         }
 5724:     }
 5725:     return;
 5726: }
 5727: 
 5728: # -------------------------------------------------See if a user is privileged
 5729: 
 5730: sub privileged {
 5731:     my ($username,$domain,$possdomains,$possroles)=@_;
 5732:     my $now = time;
 5733:     my $roles;
 5734:     if (ref($possroles) eq 'ARRAY') {
 5735:         $roles = $possroles; 
 5736:     } else {
 5737:         $roles = ['dc','su'];
 5738:     }
 5739:     if (ref($possdomains) eq 'ARRAY') {
 5740:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5741:         foreach my $dom (@{$possdomains}) {
 5742:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5743:                 (ref($privileged{$dom}) eq 'HASH')) {
 5744:                 foreach my $role (@{$roles}) {
 5745:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5746:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5747:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5748:                             return 1 unless (($end && $end < $now) ||
 5749:                                              ($start && $start > $now));
 5750:                         }
 5751:                     }
 5752:                 }
 5753:             }
 5754:         }
 5755:     } else {
 5756:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5757:         my $now = time;
 5758: 
 5759:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5760:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5761:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5762:                 return 1 unless ($tend && $tend < $now) 
 5763:                         or ($tstart && $tstart > $now);
 5764:             }
 5765:         }
 5766:     }
 5767:     return 0;
 5768: }
 5769: 
 5770: sub privileged_by_domain {
 5771:     my ($domains,$roles) = @_;
 5772:     my %privileged = ();
 5773:     my $cachetime = 60*60*24;
 5774:     my $now = time;
 5775:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5776:         return %privileged;
 5777:     }
 5778:     foreach my $dom (@{$domains}) {
 5779:         next if (ref($privileged{$dom}) eq 'HASH');
 5780:         my $needroles;
 5781:         foreach my $role (@{$roles}) {
 5782:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5783:             if (defined($cached)) {
 5784:                 if (ref($result) eq 'HASH') {
 5785:                     $privileged{$dom}{$role} = $result;
 5786:                 }
 5787:             } else {
 5788:                 $needroles = 1;
 5789:             }
 5790:         }
 5791:         if ($needroles) {
 5792:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5793:             $privileged{$dom} = {};
 5794:             foreach my $server (keys(%dompersonnel)) {
 5795:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5796:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5797:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5798:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5799:                         next if ($end && $end < $now);
 5800:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5801:                             $dompersonnel{$server}{$item};
 5802:                     }
 5803:                 }
 5804:             }
 5805:             if (ref($privileged{$dom}) eq 'HASH') {
 5806:                 foreach my $role (@{$roles}) {
 5807:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5808:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5809:                     } else {
 5810:                         my %hash = ();
 5811:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5812:                     }
 5813:                 }
 5814:             }
 5815:         }
 5816:     }
 5817:     return %privileged;
 5818: }
 5819: 
 5820: # -------------------------------------------------------- Get user privileges
 5821: 
 5822: sub rolesinit {
 5823:     my ($domain, $username) = @_;
 5824:     my %userroles = ('user.login.time' => time);
 5825:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5826: 
 5827:     # firstaccess and timerinterval are related to timed maps/resources. 
 5828:     # also, blocking can be triggered by an activating timer
 5829:     # it's saved in the user's %env.
 5830:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5831:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5832:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5833:         %timerintchk, %timerintenv);
 5834: 
 5835:     foreach my $key (keys(%firstaccess)) {
 5836:         my ($cid, $rest) = split(/\0/, $key);
 5837:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5838:     }
 5839: 
 5840:     foreach my $key (keys(%timerinterval)) {
 5841:         my ($cid,$rest) = split(/\0/,$key);
 5842:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5843:     }
 5844: 
 5845:     my %allroles=();
 5846:     my %allgroups=();
 5847: 
 5848:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5849:         my $role = $rolesdump{$area};
 5850:         $area =~ s/\_\w\w$//;
 5851: 
 5852:         my ($trole, $tend, $tstart, $group_privs);
 5853: 
 5854:         if ($role =~ /^cr/) {
 5855:         # Custom role, defined by a user 
 5856:         # e.g., user.role.cr/msu/smith/mynewrole
 5857:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5858:                 $trole = $1;
 5859:                 ($tend, $tstart) = split('_', $2);
 5860:             } else {
 5861:                 $trole = $role;
 5862:             }
 5863:         } elsif ($role =~ m|^gr/|) {
 5864:         # Role of member in a group, defined within a course/community
 5865:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5866:             ($trole, $tend, $tstart) = split(/_/, $role);
 5867:             next if $tstart eq '-1';
 5868:             ($trole, $group_privs) = split(/\//, $trole);
 5869:             $group_privs = &unescape($group_privs);
 5870:         } else {
 5871:         # Just a normal role, defined in roles.tab
 5872:             ($trole, $tend, $tstart) = split(/_/,$role);
 5873:         }
 5874: 
 5875:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5876:                  $username);
 5877:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5878: 
 5879:         # role expired or not available yet?
 5880:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5881:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5882: 
 5883:         next if $area eq '' or $trole eq '';
 5884: 
 5885:         my $spec = "$trole.$area";
 5886:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5887: 
 5888:         if ($trole =~ /^cr\//) {
 5889:         # Custom role, defined by a user
 5890:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5891:         } elsif ($trole eq 'gr') {
 5892:         # Role of a member in a group, defined within a course/community
 5893:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5894:             next;
 5895:         } else {
 5896:         # Normal role, defined in roles.tab
 5897:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5898:         }
 5899: 
 5900:         my $cid = $tdomain.'_'.$trest;
 5901:         unless ($firstaccchk{$cid}) {
 5902:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5903:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5904:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5905:                         $coursetimerstarts{$cid}{$item}; 
 5906:                 }
 5907:             }
 5908:             $firstaccchk{$cid} = 1;
 5909:         }
 5910:         unless ($timerintchk{$cid}) {
 5911:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5912:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5913:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5914:                        $coursetimerintervals{$cid}{$item};
 5915:                 }
 5916:             }
 5917:             $timerintchk{$cid} = 1;
 5918:         }
 5919:     }
 5920: 
 5921:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 5922:                                                           \%allroles, \%allgroups);
 5923:     $env{'user.adv'} = $userroles{'user.adv'};
 5924:     $env{'user.rar'} = $userroles{'user.rar'};
 5925: 
 5926:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5927: }
 5928: 
 5929: sub set_arearole {
 5930:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5931:     unless ($nolog) {
 5932: # log the associated role with the area
 5933:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5934:     }
 5935:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5936: }
 5937: 
 5938: sub custom_roleprivs {
 5939:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5940:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5941:     my $homsvr = &homeserver($rauthor,$rdomain);
 5942:     if (&hostname($homsvr) ne '') {
 5943:         my ($rdummy,$roledef)=
 5944:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5945:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5946:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5947:             if (defined($syspriv)) {
 5948:                 if ($trest =~ /^$match_community$/) {
 5949:                     $syspriv =~ s/bre\&S//; 
 5950:                 }
 5951:                 $$allroles{'cm./'}.=':'.$syspriv;
 5952:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5953:             }
 5954:             if ($tdomain ne '') {
 5955:                 if (defined($dompriv)) {
 5956:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5957:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5958:                 }
 5959:                 if (($trest ne '') && (defined($coursepriv))) {
 5960:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 5961:                         my $rolename = $1;
 5962:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 5963:                     }
 5964:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5965:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5966:                 }
 5967:             }
 5968:         }
 5969:     }
 5970: }
 5971: 
 5972: sub course_adhocrole_privs {
 5973:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 5974:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 5975:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 5976:         my (%currprivs,%storeprivs);
 5977:         foreach my $item (split(/:/,$coursepriv)) {
 5978:             my ($priv,$restrict) = split(/\&/,$item);
 5979:             $currprivs{$priv} = $restrict;
 5980:         }
 5981:         my (%possadd,%possremove,%full);
 5982:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 5983:             my ($priv,$restrict)=split(/\&/,$item);
 5984:             $full{$priv} = $restrict;
 5985:         }
 5986:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 5987:              next if ($item eq '');
 5988:              my ($rule,$rest) = split(/=/,$item);
 5989:              next unless (($rule eq 'off') || ($rule eq 'on'));
 5990:              foreach my $priv (split(/:/,$rest)) {
 5991:                  if ($priv ne '') {
 5992:                      if ($rule eq 'off') {
 5993:                          $possremove{$priv} = 1;
 5994:                      } else {
 5995:                          $possadd{$priv} = 1;
 5996:                      }
 5997:                  }
 5998:              }
 5999:          }
 6000:          foreach my $priv (sort(keys(%full))) {
 6001:              if (exists($currprivs{$priv})) {
 6002:                  unless (exists($possremove{$priv})) {
 6003:                      $storeprivs{$priv} = $currprivs{$priv};
 6004:                  }
 6005:              } elsif (exists($possadd{$priv})) {
 6006:                  $storeprivs{$priv} = $full{$priv};
 6007:              }
 6008:          }
 6009:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6010:      }
 6011:      return $coursepriv;
 6012: }
 6013: 
 6014: sub group_roleprivs {
 6015:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6016:     my $access = 1;
 6017:     my $now = time;
 6018:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6019:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6020:     if ($access) {
 6021:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6022:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6023:     }
 6024: }
 6025: 
 6026: sub standard_roleprivs {
 6027:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6028:     if (defined($pr{$trole.':s'})) {
 6029:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6030:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6031:     }
 6032:     if ($tdomain ne '') {
 6033:         if (defined($pr{$trole.':d'})) {
 6034:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6035:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6036:         }
 6037:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6038:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6039:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6040:         }
 6041:     }
 6042: }
 6043: 
 6044: sub set_userprivs {
 6045:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6046:     my $author=0;
 6047:     my $adv=0;
 6048:     my $rar=0;
 6049:     my %grouproles = ();
 6050:     if (keys(%{$allgroups}) > 0) {
 6051:         my @groupkeys; 
 6052:         foreach my $role (keys(%{$allroles})) {
 6053:             push(@groupkeys,$role);
 6054:         }
 6055:         if (ref($groups_roles) eq 'HASH') {
 6056:             foreach my $key (keys(%{$groups_roles})) {
 6057:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6058:                     push(@groupkeys,$key);
 6059:                 }
 6060:             }
 6061:         }
 6062:         if (@groupkeys > 0) {
 6063:             foreach my $role (@groupkeys) {
 6064:                 my ($trole,$area,$sec,$extendedarea);
 6065:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6066:                     $trole = $1;
 6067:                     $area = $2;
 6068:                     $sec = $3;
 6069:                     $extendedarea = $area.$sec;
 6070:                     if (exists($$allgroups{$area})) {
 6071:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6072:                             my $spec = $trole.'.'.$extendedarea;
 6073:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6074:                                                 $$allgroups{$area}{$group};
 6075:                         }
 6076:                     }
 6077:                 }
 6078:             }
 6079:         }
 6080:     }
 6081:     foreach my $group (keys(%grouproles)) {
 6082:         $$allroles{$group} = $grouproles{$group};
 6083:     }
 6084:     foreach my $role (keys(%{$allroles})) {
 6085:         my %thesepriv;
 6086:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6087:         foreach my $item (split(/:/,$$allroles{$role})) {
 6088:             if ($item ne '') {
 6089:                 my ($privilege,$restrictions)=split(/&/,$item);
 6090:                 if ($restrictions eq '') {
 6091:                     $thesepriv{$privilege}='F';
 6092:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6093:                     $thesepriv{$privilege}.=$restrictions;
 6094:                 }
 6095:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6096:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6097:             }
 6098:         }
 6099:         my $thesestr='';
 6100:         foreach my $priv (sort(keys(%thesepriv))) {
 6101: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6102: 	}
 6103:         $userroles->{'user.priv.'.$role} = $thesestr;
 6104:     }
 6105:     return ($author,$adv,$rar);
 6106: }
 6107: 
 6108: sub role_status {
 6109:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6110:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6111:         my ($one,$two) = split(m{\./},$rolekey,2);
 6112:         (undef,undef,$$role) = split(/\./,$one,3);
 6113:         unless (!defined($$role) || $$role eq '') {
 6114:             $$where = '/'.$two;
 6115:             $$trolecode=$$role.'.'.$$where;
 6116:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6117:             $$tstatus='is';
 6118:             if ($$tstart && $$tstart>$update) {
 6119:                 $$tstatus='future';
 6120:                 if ($$tstart<$now) {
 6121:                     if ($$tstart && $$tstart>$refresh) {
 6122:                         if (($$where ne '') && ($$role ne '')) {
 6123:                             my (%allroles,%allgroups,$group_privs,
 6124:                                 %groups_roles,@rolecodes);
 6125:                             my %userroles = (
 6126:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6127:                             );
 6128:                             @rolecodes = ('cm'); 
 6129:                             my $spec=$$role.'.'.$$where;
 6130:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6131:                             if ($$role =~ /^cr\//) {
 6132:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6133:                                 push(@rolecodes,'cr');
 6134:                             } elsif ($$role eq 'gr') {
 6135:                                 push(@rolecodes,$$role);
 6136:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6137:                                                     $env{'user.name'});
 6138:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6139:                                 (undef,my $group_privs) = split(/\//,$trole);
 6140:                                 $group_privs = &unescape($group_privs);
 6141:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6142:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6143:                                 &get_groups_roles($tdomain,$trest,
 6144:                                                   \%course_roles,\@rolecodes,
 6145:                                                   \%groups_roles);
 6146:                             } else {
 6147:                                 push(@rolecodes,$$role);
 6148:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6149:                             }
 6150:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6151:                                                                    \%groups_roles);
 6152:                             &appenv(\%userroles,\@rolecodes);
 6153:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6154:                         }
 6155:                     }
 6156:                     $$tstatus = 'is';
 6157:                 }
 6158:             }
 6159:             if ($$tend) {
 6160:                 if ($$tend<$update) {
 6161:                     $$tstatus='expired';
 6162:                 } elsif ($$tend<$now) {
 6163:                     $$tstatus='will_not';
 6164:                 }
 6165:             }
 6166:         }
 6167:     }
 6168: }
 6169: 
 6170: sub get_groups_roles {
 6171:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6172:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6173:                   (ref($rolecodes) eq 'ARRAY') && 
 6174:                   (ref($groups_roles) eq 'HASH')); 
 6175:     if (keys(%{$cdom_courseroles}) > 0) {
 6176:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6177:         if ($cdom ne '' && $cnum ne '') {
 6178:             foreach my $key (keys(%{$cdom_courseroles})) {
 6179:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6180:                     my $crsrole = $1;
 6181:                     my $crssec = $2;
 6182:                     if ($crsrole =~ /^cr/) {
 6183:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6184:                             push(@{$rolecodes},'cr');
 6185:                         }
 6186:                     } else {
 6187:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6188:                             push(@{$rolecodes},$crsrole);
 6189:                         }
 6190:                     }
 6191:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6192:                     if ($crssec ne '') {
 6193:                         $rolekey .= "/$crssec";
 6194:                     }
 6195:                     $rolekey .= './';
 6196:                     $groups_roles->{$rolekey} = $rolecodes;
 6197:                 }
 6198:             }
 6199:         }
 6200:     }
 6201:     return;
 6202: }
 6203: 
 6204: sub delete_env_groupprivs {
 6205:     my ($where,$courseroles,$possroles) = @_;
 6206:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6207:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6208:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6209:         %{$courseroles->{$udom}} =
 6210:             &get_my_roles('','','userroles',['active'],
 6211:                           $possroles,[$udom],1);
 6212:     }
 6213:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6214:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6215:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6216:             my $area = '/'.$cdom.'/'.$cnum;
 6217:             my $privkey = "user.priv.$crsrole.$area";
 6218:             if ($crssec ne '') {
 6219:                 $privkey .= '/'.$crssec;
 6220:             }
 6221:             $privkey .= ".$area/$group";
 6222:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6223:         }
 6224:     }
 6225:     return;
 6226: }
 6227: 
 6228: sub check_adhoc_privs {
 6229:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6230:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6231:     if ($sec) {
 6232:         $cckey .= '/'.$sec;
 6233:     } 
 6234:     my $setprivs;
 6235:     if ($env{$cckey}) {
 6236:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6237:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6238:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6239:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6240:             $setprivs = 1;
 6241:         }
 6242:     } else {
 6243:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6244:         $setprivs = 1;
 6245:     }
 6246:     return $setprivs;
 6247: }
 6248: 
 6249: sub set_adhoc_privileges {
 6250: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6251:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6252:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6253:     if ($sec ne '') {
 6254:         $area .= '/'.$sec;
 6255:     }
 6256:     my $spec = $role.'.'.$area;
 6257:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6258:                                   $env{'user.name'},1);
 6259:     my %rolehash = ();
 6260:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6261:         my $rolename = $1;
 6262:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6263:         my %domdef = &get_domain_defaults($dcdom);
 6264:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6265:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6266:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6267:             }
 6268:         }
 6269:     } else {
 6270:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6271:     }
 6272:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6273:     &appenv(\%userroles,[$role,'cm']);
 6274:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6275:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6276:         &appenv( {'request.role'        => $spec,
 6277:                   'request.role.domain' => $dcdom,
 6278:                   'request.course.sec'  => $sec,
 6279:                  }
 6280:                );
 6281:         my $tadv=0;
 6282:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6283:         &appenv({'request.role.adv'    => $tadv});
 6284:     }
 6285: }
 6286: 
 6287: # --------------------------------------------------------------- get interface
 6288: 
 6289: sub get {
 6290:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6291:    my $items='';
 6292:    foreach my $item (@$storearr) {
 6293:        $items.=&escape($item).'&';
 6294:    }
 6295:    $items=~s/\&$//;
 6296:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6297:    if (!$uname) { $uname=$env{'user.name'}; }
 6298:    my $uhome=&homeserver($uname,$udomain);
 6299: 
 6300:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6301:    my @pairs=split(/\&/,$rep);
 6302:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6303:      return @pairs;
 6304:    }
 6305:    my %returnhash=();
 6306:    my $i=0;
 6307:    foreach my $item (@$storearr) {
 6308:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6309:       $i++;
 6310:    }
 6311:    return %returnhash;
 6312: }
 6313: 
 6314: # --------------------------------------------------------------- del interface
 6315: 
 6316: sub del {
 6317:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6318:    my $items='';
 6319:    foreach my $item (@$storearr) {
 6320:        $items.=&escape($item).'&';
 6321:    }
 6322: 
 6323:    $items=~s/\&$//;
 6324:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6325:    if (!$uname) { $uname=$env{'user.name'}; }
 6326:    my $uhome=&homeserver($uname,$udomain);
 6327:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6328: }
 6329: 
 6330: # -------------------------------------------------------------- dump interface
 6331: 
 6332: sub unserialize {
 6333:     my ($rep, $escapedkeys) = @_;
 6334: 
 6335:     return {} if $rep =~ /^error/;
 6336: 
 6337:     my %returnhash=();
 6338: 	foreach my $item (split(/\&/,$rep)) {
 6339: 	    my ($key, $value) = split(/=/, $item, 2);
 6340: 	    $key = unescape($key) unless $escapedkeys;
 6341: 	    next if $key =~ /^error: 2 /;
 6342: 	    $returnhash{$key} = &thaw_unescape($value);
 6343: 	}
 6344:     #return %returnhash;
 6345:     return \%returnhash;
 6346: }        
 6347: 
 6348: # see Lond::dump_with_regexp
 6349: # if $escapedkeys hash keys won't get unescaped.
 6350: sub dump {
 6351:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6352:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6353:     if (!$uname) { $uname=$env{'user.name'}; }
 6354:     my $uhome=&homeserver($uname,$udomain);
 6355: 
 6356:     if ($regexp) {
 6357:         $regexp=&escape($regexp);
 6358:     } else {
 6359:         $regexp='.';
 6360:     }
 6361:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6362:         # user is hosted on this machine
 6363:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6364:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6365:         return %{unserialize($reply, $escapedkeys)};
 6366:     }
 6367:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6368:     my @pairs=split(/\&/,$rep);
 6369:     my %returnhash=();
 6370:     if (!($rep =~ /^error/ )) {
 6371: 	foreach my $item (@pairs) {
 6372: 	    my ($key,$value)=split(/=/,$item,2);
 6373:         $key = unescape($key) unless $escapedkeys;
 6374:         #$key = &unescape($key);
 6375: 	    next if ($key =~ /^error: 2 /);
 6376: 	    $returnhash{$key}=&thaw_unescape($value);
 6377: 	}
 6378:     }
 6379:     return %returnhash;
 6380: }
 6381: 
 6382: 
 6383: # --------------------------------------------------------- dumpstore interface
 6384: 
 6385: sub dumpstore {
 6386:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6387:    # same as dump but keys must be escaped. They may contain colon separated
 6388:    # lists of values that may themself contain colons (e.g. symbs).
 6389:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6390: }
 6391: 
 6392: # -------------------------------------------------------------- keys interface
 6393: 
 6394: sub getkeys {
 6395:    my ($namespace,$udomain,$uname)=@_;
 6396:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6397:    if (!$uname) { $uname=$env{'user.name'}; }
 6398:    my $uhome=&homeserver($uname,$udomain);
 6399:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6400:    my @keyarray=();
 6401:    foreach my $key (split(/\&/,$rep)) {
 6402:       next if ($key =~ /^error: 2 /);
 6403:       push(@keyarray,&unescape($key));
 6404:    }
 6405:    return @keyarray;
 6406: }
 6407: 
 6408: # --------------------------------------------------------------- currentdump
 6409: sub currentdump {
 6410:    my ($courseid,$sdom,$sname)=@_;
 6411:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6412:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6413:    $sname    = $env{'user.name'}         if (! defined($sname));
 6414:    my $uhome = &homeserver($sname,$sdom);
 6415:    my $rep;
 6416: 
 6417:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6418:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6419:                    $courseid)));
 6420:    } else {
 6421:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6422:    }
 6423: 
 6424:    return if ($rep =~ /^(error:|no_such_host)/);
 6425:    #
 6426:    my %returnhash=();
 6427:    #
 6428:    if ($rep eq 'unknown_cmd') {
 6429:        # an old lond will not know currentdump
 6430:        # Do a dump and make it look like a currentdump
 6431:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6432:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6433:        my %hash = @tmp;
 6434:        @tmp=();
 6435:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6436:    } else {
 6437:        my @pairs=split(/\&/,$rep);
 6438:        foreach my $pair (@pairs) {
 6439:            my ($key,$value)=split(/=/,$pair,2);
 6440:            my ($symb,$param) = split(/:/,$key);
 6441:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6442:                                                         &thaw_unescape($value);
 6443:        }
 6444:    }
 6445:    return %returnhash;
 6446: }
 6447: 
 6448: sub convert_dump_to_currentdump{
 6449:     my %hash = %{shift()};
 6450:     my %returnhash;
 6451:     # Code ripped from lond, essentially.  The only difference
 6452:     # here is the unescaping done by lonnet::dump().  Conceivably
 6453:     # we might run in to problems with parameter names =~ /^v\./
 6454:     while (my ($key,$value) = each(%hash)) {
 6455:         my ($v,$symb,$param) = split(/:/,$key);
 6456: 	$symb  = &unescape($symb);
 6457: 	$param = &unescape($param);
 6458:         next if ($v eq 'version' || $symb eq 'keys');
 6459:         next if (exists($returnhash{$symb}) &&
 6460:                  exists($returnhash{$symb}->{$param}) &&
 6461:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6462:         $returnhash{$symb}->{$param}=$value;
 6463:         $returnhash{$symb}->{'v.'.$param}=$v;
 6464:     }
 6465:     #
 6466:     # Remove all of the keys in the hashes which keep track of
 6467:     # the version of the parameter.
 6468:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6469:         # use a foreach because we are going to delete from the hash.
 6470:         foreach my $key (keys(%$param_hash)) {
 6471:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6472:         }
 6473:     }
 6474:     return \%returnhash;
 6475: }
 6476: 
 6477: # ------------------------------------------------------ critical inc interface
 6478: 
 6479: sub cinc {
 6480:     return &inc(@_,'critical');
 6481: }
 6482: 
 6483: # --------------------------------------------------------------- inc interface
 6484: 
 6485: sub inc {
 6486:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6487:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6488:     if (!$uname) { $uname=$env{'user.name'}; }
 6489:     my $uhome=&homeserver($uname,$udomain);
 6490:     my $items='';
 6491:     if (! ref($store)) {
 6492:         # got a single value, so use that instead
 6493:         $items = &escape($store).'=&';
 6494:     } elsif (ref($store) eq 'SCALAR') {
 6495:         $items = &escape($$store).'=&';        
 6496:     } elsif (ref($store) eq 'ARRAY') {
 6497:         $items = join('=&',map {&escape($_);} @{$store});
 6498:     } elsif (ref($store) eq 'HASH') {
 6499:         while (my($key,$value) = each(%{$store})) {
 6500:             $items.= &escape($key).'='.&escape($value).'&';
 6501:         }
 6502:     }
 6503:     $items=~s/\&$//;
 6504:     if ($critical) {
 6505: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6506:     } else {
 6507: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6508:     }
 6509: }
 6510: 
 6511: # --------------------------------------------------------------- put interface
 6512: 
 6513: sub put {
 6514:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6515:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6516:    if (!$uname) { $uname=$env{'user.name'}; }
 6517:    my $uhome=&homeserver($uname,$udomain);
 6518:    my $items='';
 6519:    foreach my $item (keys(%$storehash)) {
 6520:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6521:    }
 6522:    $items=~s/\&$//;
 6523:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6524: }
 6525: 
 6526: # ------------------------------------------------------------ newput interface
 6527: 
 6528: sub newput {
 6529:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6530:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6531:    if (!$uname) { $uname=$env{'user.name'}; }
 6532:    my $uhome=&homeserver($uname,$udomain);
 6533:    my $items='';
 6534:    foreach my $key (keys(%$storehash)) {
 6535:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6536:    }
 6537:    $items=~s/\&$//;
 6538:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6539: }
 6540: 
 6541: # ---------------------------------------------------------  putstore interface
 6542: 
 6543: sub putstore {
 6544:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6545:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6546:    if (!$uname) { $uname=$env{'user.name'}; }
 6547:    my $uhome=&homeserver($uname,$udomain);
 6548:    my $items='';
 6549:    foreach my $key (keys(%$storehash)) {
 6550:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6551:    }
 6552:    $items=~s/\&$//;
 6553:    my $esc_symb=&escape($symb);
 6554:    my $esc_v=&escape($version);
 6555:    my $reply =
 6556:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6557: 	      $uhome);
 6558:    if (($tolog) && ($reply eq 'ok')) {
 6559:        my $namevalue='';
 6560:        foreach my $key (keys(%{$storehash})) {
 6561:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6562:        }
 6563:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6564:                      '&host='.&escape($perlvar{'lonHostID'}).
 6565:                      '&version='.$esc_v.
 6566:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6567:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6568:    }
 6569:    if ($reply eq 'unknown_cmd') {
 6570:        # gfall back to way things use to be done
 6571:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6572: 			    $uname);
 6573:    }
 6574:    return $reply;
 6575: }
 6576: 
 6577: sub old_putstore {
 6578:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6579:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6580:     if (!$uname) { $uname=$env{'user.name'}; }
 6581:     my $uhome=&homeserver($uname,$udomain);
 6582:     my %newstorehash;
 6583:     foreach my $item (keys(%$storehash)) {
 6584: 	my $key = $version.':'.&escape($symb).':'.$item;
 6585: 	$newstorehash{$key} = $storehash->{$item};
 6586:     }
 6587:     my $items='';
 6588:     my %allitems = ();
 6589:     foreach my $item (keys(%newstorehash)) {
 6590: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6591: 	    my $key = $1.':keys:'.$2;
 6592: 	    $allitems{$key} .= $3.':';
 6593: 	}
 6594: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6595:     }
 6596:     foreach my $item (keys(%allitems)) {
 6597: 	$allitems{$item} =~ s/\:$//;
 6598: 	$items.= $item.'='.$allitems{$item}.'&';
 6599:     }
 6600:     $items=~s/\&$//;
 6601:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6602: }
 6603: 
 6604: # ------------------------------------------------------ critical put interface
 6605: 
 6606: sub cput {
 6607:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6608:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6609:    if (!$uname) { $uname=$env{'user.name'}; }
 6610:    my $uhome=&homeserver($uname,$udomain);
 6611:    my $items='';
 6612:    foreach my $item (keys(%$storehash)) {
 6613:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6614:    }
 6615:    $items=~s/\&$//;
 6616:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6617: }
 6618: 
 6619: # -------------------------------------------------------------- eget interface
 6620: 
 6621: sub eget {
 6622:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6623:    my $items='';
 6624:    foreach my $item (@$storearr) {
 6625:        $items.=&escape($item).'&';
 6626:    }
 6627:    $items=~s/\&$//;
 6628:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6629:    if (!$uname) { $uname=$env{'user.name'}; }
 6630:    my $uhome=&homeserver($uname,$udomain);
 6631:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6632:    my @pairs=split(/\&/,$rep);
 6633:    my %returnhash=();
 6634:    my $i=0;
 6635:    foreach my $item (@$storearr) {
 6636:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6637:       $i++;
 6638:    }
 6639:    return %returnhash;
 6640: }
 6641: 
 6642: # ------------------------------------------------------------ tmpput interface
 6643: sub tmpput {
 6644:     my ($storehash,$server,$context)=@_;
 6645:     my $items='';
 6646:     foreach my $item (keys(%$storehash)) {
 6647: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6648:     }
 6649:     $items=~s/\&$//;
 6650:     if (defined($context)) {
 6651:         $items .= ':'.&escape($context);
 6652:     }
 6653:     return &reply("tmpput:$items",$server);
 6654: }
 6655: 
 6656: # ------------------------------------------------------------ tmpget interface
 6657: sub tmpget {
 6658:     my ($token,$server)=@_;
 6659:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6660:     my $rep=&reply("tmpget:$token",$server);
 6661:     my %returnhash;
 6662:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6663:         return %returnhash;
 6664:     }
 6665:     foreach my $item (split(/\&/,$rep)) {
 6666: 	my ($key,$value)=split(/=/,$item);
 6667: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6668:     }
 6669:     return %returnhash;
 6670: }
 6671: 
 6672: # ------------------------------------------------------------ tmpdel interface
 6673: sub tmpdel {
 6674:     my ($token,$server)=@_;
 6675:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6676:     return &reply("tmpdel:$token",$server);
 6677: }
 6678: 
 6679: # ------------------------------------------------------------ get_timebased_id 
 6680: 
 6681: sub get_timebased_id {
 6682:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6683:         $maxtries) = @_;
 6684:     my ($newid,$error,$dellock);
 6685:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6686:         return ('','ok','invalid call to get suffix');
 6687:     }
 6688: 
 6689: # set defaults for any optional args for which values were not supplied
 6690:     if ($who eq '') {
 6691:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6692:     }
 6693:     if (!$locktries) {
 6694:         $locktries = 3;
 6695:     }
 6696:     if (!$maxtries) {
 6697:         $maxtries = 10;
 6698:     }
 6699:     
 6700:     if (($cdom eq '') || ($cnum eq '')) {
 6701:         if ($env{'request.course.id'}) {
 6702:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6703:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6704:         }
 6705:         if (($cdom eq '') || ($cnum eq '')) {
 6706:             return ('','ok','call to get suffix not in course context');
 6707:         }
 6708:     }
 6709: 
 6710: # construct locking item
 6711:     my $lockhash = {
 6712:                       $prefix."\0".'locked_'.$keyid => $who,
 6713:                    };
 6714:     my $tries = 0;
 6715: 
 6716: # attempt to get lock on nohist_$namespace file
 6717:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6718:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6719:         $tries ++;
 6720:         sleep 1;
 6721:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6722:     }
 6723: 
 6724: # attempt to get unique identifier, based on current timestamp
 6725:     if ($gotlock eq 'ok') {
 6726:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6727:         my $id = time;
 6728:         $newid = $id;
 6729:         if ($idtype eq 'addcode') {
 6730:             $newid .= &sixnum_code();
 6731:         }
 6732:         my $idtries = 0;
 6733:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6734:             if ($idtype eq 'concat') {
 6735:                 $newid = $id.$idtries;
 6736:             } elsif ($idtype eq 'addcode') {
 6737:                 $newid = $newid.&sixnum_code();
 6738:             } else {
 6739:                 $newid ++;
 6740:             }
 6741:             $idtries ++;
 6742:         }
 6743:         if (!exists($inuse{$prefix."\0".$newid})) {
 6744:             my %new_item =  (
 6745:                               $prefix."\0".$newid => $who,
 6746:                             );
 6747:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6748:                                                  $cdom,$cnum);
 6749:             if ($putresult ne 'ok') {
 6750:                 undef($newid);
 6751:                 $error = 'error saving new item: '.$putresult;
 6752:             }
 6753:         } else {
 6754:              undef($newid);
 6755:              $error = ('error: no unique suffix available for the new item ');
 6756:         }
 6757: #  remove lock
 6758:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6759:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6760:     } else {
 6761:         $error = "error: could not obtain lockfile\n";
 6762:         $dellock = 'ok';
 6763:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6764:             $dellock = 'nolock';
 6765:         }
 6766:     }
 6767:     return ($newid,$dellock,$error);
 6768: }
 6769: 
 6770: sub sixnum_code {
 6771:     my $code;
 6772:     for (0..6) {
 6773:         $code .= int( rand(9) );
 6774:     }
 6775:     return $code;
 6776: }
 6777: 
 6778: # -------------------------------------------------- portfolio access checking
 6779: 
 6780: sub portfolio_access {
 6781:     my ($requrl,$clientip) = @_;
 6782:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6783:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6784:     if ($result) {
 6785:         my %setters;
 6786:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6787:             my ($startblock,$endblock) =
 6788:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6789:             if ($startblock && $endblock) {
 6790:                 return 'B';
 6791:             }
 6792:         } else {
 6793:             my ($startblock,$endblock) =
 6794:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6795:             if ($startblock && $endblock) {
 6796:                 return 'B';
 6797:             }
 6798:         }
 6799:     }
 6800:     if ($result eq 'ok') {
 6801:        return 'F';
 6802:     } elsif ($result =~ /^[^:]+:guest_/) {
 6803:        return 'A';
 6804:     }
 6805:     return '';
 6806: }
 6807: 
 6808: sub get_portfolio_access {
 6809:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6810: 
 6811:     if (!ref($access_hash)) {
 6812: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6813: 	my %access_controls = &get_access_controls($current_perms,$group,
 6814: 						   $file_name);
 6815: 	$access_hash = $access_controls{$file_name};
 6816:     }
 6817: 
 6818:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6819:     my $now = time;
 6820:     if (ref($access_hash) eq 'HASH') {
 6821:         foreach my $key (keys(%{$access_hash})) {
 6822:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6823:             if ($start > $now) {
 6824:                 next;
 6825:             }
 6826:             if ($end && $end<$now) {
 6827:                 next;
 6828:             }
 6829:             if ($scope eq 'public') {
 6830:                 $public = $key;
 6831:                 last;
 6832:             } elsif ($scope eq 'guest') {
 6833:                 $guest = $key;
 6834:             } elsif ($scope eq 'domains') {
 6835:                 push(@domains,$key);
 6836:             } elsif ($scope eq 'users') {
 6837:                 push(@users,$key);
 6838:             } elsif ($scope eq 'course') {
 6839:                 push(@courses,$key);
 6840:             } elsif ($scope eq 'group') {
 6841:                 push(@groups,$key);
 6842:             } elsif ($scope eq 'ip') {
 6843:                 push(@ips,$key);
 6844:             }
 6845:         }
 6846:         if ($public) {
 6847:             return 'ok';
 6848:         } elsif (@ips > 0) {
 6849:             my $allowed;
 6850:             foreach my $ipkey (@ips) {
 6851:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6852:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6853:                         $allowed = 1;
 6854:                         last; 
 6855:                     }
 6856:                 }
 6857:             }
 6858:             if ($allowed) {
 6859:                 return 'ok';
 6860:             }
 6861:         }
 6862:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6863:             if ($guest) {
 6864:                 return $guest;
 6865:             }
 6866:         } else {
 6867:             if (@domains > 0) {
 6868:                 foreach my $domkey (@domains) {
 6869:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6870:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6871:                             return 'ok';
 6872:                         }
 6873:                     }
 6874:                 }
 6875:             }
 6876:             if (@users > 0) {
 6877:                 foreach my $userkey (@users) {
 6878:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6879:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6880:                             if (ref($item) eq 'HASH') {
 6881:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6882:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6883:                                     return 'ok';
 6884:                                 }
 6885:                             }
 6886:                         }
 6887:                     } 
 6888:                 }
 6889:             }
 6890:             my %roleshash;
 6891:             my @courses_and_groups = @courses;
 6892:             push(@courses_and_groups,@groups); 
 6893:             if (@courses_and_groups > 0) {
 6894:                 my (%allgroups,%allroles); 
 6895:                 my ($start,$end,$role,$sec,$group);
 6896:                 foreach my $envkey (%env) {
 6897:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6898:                         my $cid = $2.'_'.$3; 
 6899:                         if ($1 eq 'gr') {
 6900:                             $group = $4;
 6901:                             $allgroups{$cid}{$group} = $env{$envkey};
 6902:                         } else {
 6903:                             if ($4 eq '') {
 6904:                                 $sec = 'none';
 6905:                             } else {
 6906:                                 $sec = $4;
 6907:                             }
 6908:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6909:                         }
 6910:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6911:                         my $cid = $2.'_'.$3;
 6912:                         if ($4 eq '') {
 6913:                             $sec = 'none';
 6914:                         } else {
 6915:                             $sec = $4;
 6916:                         }
 6917:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6918:                     }
 6919:                 }
 6920:                 if (keys(%allroles) == 0) {
 6921:                     return;
 6922:                 }
 6923:                 foreach my $key (@courses_and_groups) {
 6924:                     my %content = %{$$access_hash{$key}};
 6925:                     my $cnum = $content{'number'};
 6926:                     my $cdom = $content{'domain'};
 6927:                     my $cid = $cdom.'_'.$cnum;
 6928:                     if (!exists($allroles{$cid})) {
 6929:                         next;
 6930:                     }    
 6931:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6932:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6933:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6934:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6935:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6936:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6937:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6938:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6939:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6940:                                         if (grep/^all$/,@sections) {
 6941:                                             return 'ok';
 6942:                                         } else {
 6943:                                             if (grep/^$sec$/,@sections) {
 6944:                                                 return 'ok';
 6945:                                             }
 6946:                                         }
 6947:                                     }
 6948:                                 }
 6949:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6950:                                     if (grep/^none$/,@groups) {
 6951:                                         return 'ok';
 6952:                                     }
 6953:                                 } else {
 6954:                                     if (grep/^all$/,@groups) {
 6955:                                         return 'ok';
 6956:                                     } 
 6957:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6958:                                         if (grep/^$group$/,@groups) {
 6959:                                             return 'ok';
 6960:                                         }
 6961:                                     }
 6962:                                 } 
 6963:                             }
 6964:                         }
 6965:                     }
 6966:                 }
 6967:             }
 6968:             if ($guest) {
 6969:                 return $guest;
 6970:             }
 6971:         }
 6972:     }
 6973:     return;
 6974: }
 6975: 
 6976: sub course_group_datechecker {
 6977:     my ($dates,$now,$status) = @_;
 6978:     my ($start,$end) = split(/\./,$dates);
 6979:     if (!$start && !$end) {
 6980:         return 'ok';
 6981:     }
 6982:     if (grep/^active$/,@{$status}) {
 6983:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6984:             return 'ok';
 6985:         }
 6986:     }
 6987:     if (grep/^previous$/,@{$status}) {
 6988:         if ($end > $now ) {
 6989:             return 'ok';
 6990:         }
 6991:     }
 6992:     if (grep/^future$/,@{$status}) {
 6993:         if ($start > $now) {
 6994:             return 'ok';
 6995:         }
 6996:     }
 6997:     return; 
 6998: }
 6999: 
 7000: sub parse_portfolio_url {
 7001:     my ($url) = @_;
 7002: 
 7003:     my ($type,$udom,$unum,$group,$file_name);
 7004:     
 7005:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7006: 	$type = 1;
 7007:         $udom = $1;
 7008:         $unum = $2;
 7009:         $file_name = $3;
 7010:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7011: 	$type = 2;
 7012:         $udom = $1;
 7013:         $unum = $2;
 7014:         $group = $3;
 7015:         $file_name = $3.'/'.$4;
 7016:     }
 7017:     if (wantarray) {
 7018: 	return ($type,$udom,$unum,$file_name,$group);
 7019:     }
 7020:     return $type;
 7021: }
 7022: 
 7023: sub is_portfolio_url {
 7024:     my ($url) = @_;
 7025:     return scalar(&parse_portfolio_url($url));
 7026: }
 7027: 
 7028: sub is_portfolio_file {
 7029:     my ($file) = @_;
 7030:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7031:         return 1;
 7032:     }
 7033:     return;
 7034: }
 7035: 
 7036: sub usertools_access {
 7037:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7038:     my ($access,%tools);
 7039:     if ($context eq '') {
 7040:         $context = 'tools';
 7041:     }
 7042:     if ($context eq 'requestcourses') {
 7043:         %tools = (
 7044:                       official   => 1,
 7045:                       unofficial => 1,
 7046:                       community  => 1,
 7047:                       textbook   => 1,
 7048:                       placement  => 1,
 7049:                  );
 7050:     } elsif ($context eq 'requestauthor') {
 7051:         %tools = (
 7052:                       requestauthor => 1,
 7053:                  );
 7054:     } else {
 7055:         %tools = (
 7056:                       aboutme   => 1,
 7057:                       blog      => 1,
 7058:                       webdav    => 1,
 7059:                       portfolio => 1,
 7060:                  );
 7061:     }
 7062:     return if (!defined($tools{$tool}));
 7063: 
 7064:     if (($udom eq '') || ($uname eq '')) {
 7065:         $udom = $env{'user.domain'};
 7066:         $uname = $env{'user.name'};
 7067:     }
 7068: 
 7069:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7070:         if ($action ne 'reload') {
 7071:             if ($context eq 'requestcourses') {
 7072:                 return $env{'environment.canrequest.'.$tool};
 7073:             } elsif ($context eq 'requestauthor') {
 7074:                 return $env{'environment.canrequest.author'};
 7075:             } else {
 7076:                 return $env{'environment.availabletools.'.$tool};
 7077:             }
 7078:         }
 7079:     }
 7080: 
 7081:     my ($toolstatus,$inststatus,$envkey);
 7082:     if ($context eq 'requestauthor') {
 7083:         $envkey = $context; 
 7084:     } else {
 7085:         $envkey = $context.'.'.$tool;
 7086:     }
 7087: 
 7088:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7089:          ($action ne 'reload')) {
 7090:         $toolstatus = $env{'environment.'.$envkey};
 7091:         $inststatus = $env{'environment.inststatus'};
 7092:     } else {
 7093:         if (ref($userenvref) eq 'HASH') {
 7094:             $toolstatus = $userenvref->{$envkey};
 7095:             $inststatus = $userenvref->{'inststatus'};
 7096:         } else {
 7097:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7098:             $toolstatus = $userenv{$envkey};
 7099:             $inststatus = $userenv{'inststatus'};
 7100:         }
 7101:     }
 7102: 
 7103:     if ($toolstatus ne '') {
 7104:         if ($toolstatus) {
 7105:             $access = 1;
 7106:         } else {
 7107:             $access = 0;
 7108:         }
 7109:         return $access;
 7110:     }
 7111: 
 7112:     my ($is_adv,%domdef);
 7113:     if (ref($is_advref) eq 'HASH') {
 7114:         $is_adv = $is_advref->{'is_adv'};
 7115:     } else {
 7116:         $is_adv = &is_advanced_user($udom,$uname);
 7117:     }
 7118:     if (ref($domdefref) eq 'HASH') {
 7119:         %domdef = %{$domdefref};
 7120:     } else {
 7121:         %domdef = &get_domain_defaults($udom);
 7122:     }
 7123:     if (ref($domdef{$tool}) eq 'HASH') {
 7124:         if ($is_adv) {
 7125:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7126:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7127:                     $access = 1;
 7128:                 } else {
 7129:                     $access = 0;
 7130:                 }
 7131:                 return $access;
 7132:             }
 7133:         }
 7134:         if ($inststatus ne '') {
 7135:             my ($hasaccess,$hasnoaccess);
 7136:             foreach my $affiliation (split(/:/,$inststatus)) {
 7137:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7138:                     if ($domdef{$tool}{$affiliation}) {
 7139:                         $hasaccess = 1;
 7140:                     } else {
 7141:                         $hasnoaccess = 1;
 7142:                     }
 7143:                 }
 7144:             }
 7145:             if ($hasaccess || $hasnoaccess) {
 7146:                 if ($hasaccess) {
 7147:                     $access = 1;
 7148:                 } elsif ($hasnoaccess) {
 7149:                     $access = 0; 
 7150:                 }
 7151:                 return $access;
 7152:             }
 7153:         } else {
 7154:             if ($domdef{$tool}{'default'} ne '') {
 7155:                 if ($domdef{$tool}{'default'}) {
 7156:                     $access = 1;
 7157:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7158:                     $access = 0;
 7159:                 }
 7160:                 return $access;
 7161:             }
 7162:         }
 7163:     } else {
 7164:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7165:             $access = 1;
 7166:         } else {
 7167:             $access = 0;
 7168:         }
 7169:         return $access;
 7170:     }
 7171: }
 7172: 
 7173: sub is_course_owner {
 7174:     my ($cdom,$cnum,$udom,$uname) = @_;
 7175:     if (($udom eq '') || ($uname eq '')) {
 7176:         $udom = $env{'user.domain'};
 7177:         $uname = $env{'user.name'};
 7178:     }
 7179:     unless (($udom eq '') || ($uname eq '')) {
 7180:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7181:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7182:                 return 1;
 7183:             } else {
 7184:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7185:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7186:                     return 1;
 7187:                 }
 7188:             }
 7189:         }
 7190:     }
 7191:     return;
 7192: }
 7193: 
 7194: sub is_advanced_user {
 7195:     my ($udom,$uname) = @_;
 7196:     if ($udom ne '' && $uname ne '') {
 7197:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7198:             if (wantarray) {
 7199:                 return ($env{'user.adv'},$env{'user.author'});
 7200:             } else {
 7201:                 return $env{'user.adv'};
 7202:             }
 7203:         }
 7204:     }
 7205:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7206:     my %allroles;
 7207:     my ($is_adv,$is_author);
 7208:     foreach my $role (keys(%roleshash)) {
 7209:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7210:         my $area = '/'.$tdomain.'/'.$trest;
 7211:         if ($sec ne '') {
 7212:             $area .= '/'.$sec;
 7213:         }
 7214:         if (($area ne '') && ($trole ne '')) {
 7215:             my $spec=$trole.'.'.$area;
 7216:             if ($trole =~ /^cr\//) {
 7217:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7218:             } elsif ($trole ne 'gr') {
 7219:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7220:             }
 7221:             if ($trole eq 'au') {
 7222:                 $is_author = 1;
 7223:             }
 7224:         }
 7225:     }
 7226:     foreach my $role (keys(%allroles)) {
 7227:         last if ($is_adv);
 7228:         foreach my $item (split(/:/,$allroles{$role})) {
 7229:             if ($item ne '') {
 7230:                 my ($privilege,$restrictions)=split(/&/,$item);
 7231:                 if ($privilege eq 'adv') {
 7232:                     $is_adv = 1;
 7233:                     last;
 7234:                 }
 7235:             }
 7236:         }
 7237:     }
 7238:     if (wantarray) {
 7239:         return ($is_adv,$is_author);
 7240:     }
 7241:     return $is_adv;
 7242: }
 7243: 
 7244: sub check_can_request {
 7245:     my ($dom,$can_request,$request_domains) = @_;
 7246:     my $canreq = 0;
 7247:     my ($types,$typename) = &Apache::loncommon::course_types();
 7248:     my @options = ('approval','validate','autolimit');
 7249:     my $optregex = join('|',@options);
 7250:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7251:         foreach my $type (@{$types}) {
 7252:             if (&usertools_access($env{'user.name'},
 7253:                                   $env{'user.domain'},
 7254:                                   $type,undef,'requestcourses')) {
 7255:                 $canreq ++;
 7256:                 if (ref($request_domains) eq 'HASH') {
 7257:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 7258:                 }
 7259:                 if ($dom eq $env{'user.domain'}) {
 7260:                     $can_request->{$type} = 1;
 7261:                 }
 7262:             }
 7263:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 7264:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7265:                 if (@curr > 0) {
 7266:                     foreach my $item (@curr) {
 7267:                         if (ref($request_domains) eq 'HASH') {
 7268:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7269:                             if ($otherdom ne '') {
 7270:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7271:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7272:                                         push(@{$request_domains->{$type}},$otherdom);
 7273:                                     }
 7274:                                 } else {
 7275:                                     push(@{$request_domains->{$type}},$otherdom);
 7276:                                 }
 7277:                             }
 7278:                         }
 7279:                     }
 7280:                     unless($dom eq $env{'user.domain'}) {
 7281:                         $canreq ++;
 7282:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7283:                             $can_request->{$type} = 1;
 7284:                         }
 7285:                     }
 7286:                 }
 7287:             }
 7288:         }
 7289:     }
 7290:     return $canreq;
 7291: }
 7292: 
 7293: # ---------------------------------------------- Custom access rule evaluation
 7294: 
 7295: sub customaccess {
 7296:     my ($priv,$uri)=@_;
 7297:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7298:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7299:     $udom = &LONCAPA::clean_domain($udom);
 7300:     $ucrs = &LONCAPA::clean_username($ucrs);
 7301:     my $access=0;
 7302:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7303: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7304: 	if ($type eq 'user') {
 7305: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7306: 		my ($tdom,$tuname)=split(m{/},$scope);
 7307: 		if ($tdom) {
 7308: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7309: 		}
 7310: 		if ($tuname) {
 7311: 		    if ($tuname ne $env{'user.name'}) { next; }
 7312: 		}
 7313: 		$access=($effect eq 'allow');
 7314: 		last;
 7315: 	    }
 7316: 	} else {
 7317: 	    if ($role) {
 7318: 		if ($role ne $urole) { next; }
 7319: 	    }
 7320: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7321: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7322: 		if ($tdom) {
 7323: 		    if ($tdom ne $udom) { next; }
 7324: 		}
 7325: 		if ($tcrs) {
 7326: 		    if ($tcrs ne $ucrs) { next; }
 7327: 		}
 7328: 		if ($tsec) {
 7329: 		    if ($tsec ne $usec) { next; }
 7330: 		}
 7331: 		$access=($effect eq 'allow');
 7332: 		last;
 7333: 	    }
 7334: 	    if ($realm eq '' && $role eq '') {
 7335: 		$access=($effect eq 'allow');
 7336: 	    }
 7337: 	}
 7338:     }
 7339:     return $access;
 7340: }
 7341: 
 7342: # ------------------------------------------------- Check for a user privilege
 7343: 
 7344: sub allowed {
 7345:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7346:     my $ver_orguri=$uri;
 7347:     $uri=&deversion($uri);
 7348:     my $orguri=$uri;
 7349:     $uri=&declutter($uri);
 7350: 
 7351:     if ($priv eq 'evb') {
 7352: # Evade communication block restrictions for specified role in a course
 7353:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7354:             return $1;
 7355:         } else {
 7356:             return;
 7357:         }
 7358:     }
 7359: 
 7360:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7361: # Free bre access to adm and meta resources
 7362:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7363: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7364: 	&& ($priv eq 'bre')) {
 7365: 	return 'F';
 7366:     }
 7367: 
 7368: # Free bre access to user's own portfolio contents
 7369:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7370:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7371: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7372:         my %setters;
 7373:         my ($startblock,$endblock) = 
 7374:             &Apache::loncommon::blockcheck(\%setters,'port');
 7375:         if ($startblock && $endblock) {
 7376:             return 'B';
 7377:         } else {
 7378:             return 'F';
 7379:         }
 7380:     }
 7381: 
 7382: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7383:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7384:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7385:         if (exists($env{'request.course.id'})) {
 7386:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7387:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7388:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7389:                 my $courseprivid=$env{'request.course.id'};
 7390:                 $courseprivid=~s/\_/\//;
 7391:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7392:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7393:                     return $1; 
 7394:                 } else {
 7395:                     if ($env{'request.course.sec'}) {
 7396:                         $courseprivid.='/'.$env{'request.course.sec'};
 7397:                     }
 7398:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7399:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7400:                         return $2;
 7401:                     }
 7402:                 }
 7403:             }
 7404:         }
 7405:     }
 7406: 
 7407: # Free bre to public access
 7408: 
 7409:     if ($priv eq 'bre') {
 7410:         my $copyright=&metadata($uri,'copyright');
 7411: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7412:            return 'F'; 
 7413:         }
 7414:         if ($copyright eq 'priv') {
 7415:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7416: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7417: 		return '';
 7418:             }
 7419:         }
 7420:         if ($copyright eq 'domain') {
 7421:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7422: 	    unless (($env{'user.domain'} eq $1) ||
 7423:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7424: 		return '';
 7425:             }
 7426:         }
 7427:         if ($env{'request.role'}=~ /li\.\//) {
 7428:             # Library role, so allow browsing of resources in this domain.
 7429:             return 'F';
 7430:         }
 7431:         if ($copyright eq 'custom') {
 7432: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7433:         }
 7434:     }
 7435:     # Domain coordinator is trying to create a course
 7436:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7437:         # uri is the requested domain in this case.
 7438:         # comparison to 'request.role.domain' shows if the user has selected
 7439:         # a role of dc for the domain in question.
 7440:         return 'F' if ($uri eq $env{'request.role.domain'});
 7441:     }
 7442: 
 7443:     my $thisallowed='';
 7444:     my $statecond=0;
 7445:     my $courseprivid='';
 7446: 
 7447:     my $ownaccess;
 7448:     # Community Coordinator or Assistant Co-author browsing resource space.
 7449:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7450:         if ($uri eq '') {
 7451:             $ownaccess = 1;
 7452:         } else {
 7453:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7454:                 my $udom = $env{'user.domain'};
 7455:                 my $uname = $env{'user.name'};
 7456:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7457:                     $ownaccess = 1;
 7458:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7459:                     unless ($uri =~ m{\.\./}) {
 7460:                         $ownaccess = 1;
 7461:                     }
 7462:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7463:                     my $now = time;
 7464:                     if ($uri =~ m{^([^/]+)/?$}) {
 7465:                         my $adom = $1;
 7466:                         foreach my $key (keys(%env)) {
 7467:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7468:                                 my ($start,$end) = split('.',$env{$key});
 7469:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7470:                                     $ownaccess = 1;
 7471:                                     last;
 7472:                                 }
 7473:                             }
 7474:                         }
 7475:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7476:                         my $adom = $1;
 7477:                         my $aname = $2;
 7478:                         foreach my $role ('ca','aa') { 
 7479:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7480:                                 my ($start,$end) =
 7481:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7482:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7483:                                     $ownaccess = 1;
 7484:                                     last;
 7485:                                 }
 7486:                             }
 7487:                         }
 7488:                     }
 7489:                 }
 7490:             }
 7491:         }
 7492:     }
 7493: 
 7494: # Course
 7495: 
 7496:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7497:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7498:             $thisallowed.=$1;
 7499:         }
 7500:     }
 7501: 
 7502: # Domain
 7503: 
 7504:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7505:        =~/\Q$priv\E\&([^\:]*)/) {
 7506:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7507:             $thisallowed.=$1;
 7508:         }
 7509:     }
 7510: 
 7511: # User who is not author or co-author might still be able to edit
 7512: # resource of an author in the domain (e.g., if Domain Coordinator).
 7513:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7514:         (&allowed('mdc',$env{'request.course.id'}))) {
 7515:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7516:             $thisallowed.=$1;
 7517:         }
 7518:     }
 7519: 
 7520: # Course: uri itself is a course
 7521:     my $courseuri=$uri;
 7522:     $courseuri=~s/\_(\d)/\/$1/;
 7523:     $courseuri=~s/^([^\/])/\/$1/;
 7524: 
 7525:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7526:        =~/\Q$priv\E\&([^\:]*)/) {
 7527:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7528:             $thisallowed.=$1;
 7529:         }
 7530:     }
 7531: 
 7532: # URI is an uploaded document for this course, default permissions don't matter
 7533: # not allowing 'edit' access (editupload) to uploaded course docs
 7534:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7535: 	$thisallowed='';
 7536:         my ($match)=&is_on_map($uri);
 7537:         if ($match) {
 7538:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7539:                   =~/\Q$priv\E\&([^\:]*)/) {
 7540:                 my $value = $1;
 7541:                 if ($noblockcheck) {
 7542:                     $thisallowed.=$value;
 7543:                 } else {
 7544:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7545:                     if (@blockers > 0) {
 7546:                         $thisallowed = 'B';
 7547:                     } else {
 7548:                         $thisallowed.=$value;
 7549:                     }
 7550:                 }
 7551:             }
 7552:         } else {
 7553:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7554:             if ($refuri) {
 7555:                 if ($refuri =~ m|^/adm/|) {
 7556:                     $thisallowed='F';
 7557:                 } else {
 7558:                     $refuri=&declutter($refuri);
 7559:                     my ($match) = &is_on_map($refuri);
 7560:                     if ($match) {
 7561:                         if ($noblockcheck) {
 7562:                             $thisallowed='F';
 7563:                         } else {
 7564:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7565:                             if (@blockers > 0) {
 7566:                                 $thisallowed = 'B';
 7567:                             } else {
 7568:                                 $thisallowed='F';
 7569:                             }
 7570:                         }
 7571:                     }
 7572:                 }
 7573:             }
 7574:         }
 7575:     }
 7576: 
 7577:     if ($priv eq 'bre'
 7578: 	&& $thisallowed ne 'F' 
 7579: 	&& $thisallowed ne '2'
 7580: 	&& &is_portfolio_url($uri)) {
 7581: 	$thisallowed = &portfolio_access($uri,$clientip);
 7582:     }
 7583: 
 7584: # Full access at system, domain or course-wide level? Exit.
 7585:     if ($thisallowed=~/F/) {
 7586: 	return 'F';
 7587:     }
 7588: 
 7589: # If this is generating or modifying users, exit with special codes
 7590: 
 7591:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7592: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7593: 	    my ($audom,$auname)=split('/',$uri);
 7594: # no author name given, so this just checks on the general right to make a co-author in this domain
 7595: 	    unless ($auname) { return $thisallowed; }
 7596: # an author name is given, so we are about to actually make a co-author for a certain account
 7597: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7598: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7599: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7600: 	}
 7601: 	return $thisallowed;
 7602:     }
 7603: #
 7604: # Gathered so far: system, domain and course wide privileges
 7605: #
 7606: # Course: See if uri or referer is an individual resource that is part of 
 7607: # the course
 7608: 
 7609:     if ($env{'request.course.id'}) {
 7610: 
 7611:        $courseprivid=$env{'request.course.id'};
 7612:        if ($env{'request.course.sec'}) {
 7613:           $courseprivid.='/'.$env{'request.course.sec'};
 7614:        }
 7615:        $courseprivid=~s/\_/\//;
 7616:        my $checkreferer=1;
 7617:        my ($match,$cond)=&is_on_map($uri);
 7618:        if ($match) {
 7619:            $statecond=$cond;
 7620:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7621:                =~/\Q$priv\E\&([^\:]*)/) {
 7622:                my $value = $1;
 7623:                if ($priv eq 'bre') {
 7624:                    if ($noblockcheck) {
 7625:                        $thisallowed.=$value;
 7626:                    } else {
 7627:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7628:                        if (@blockers > 0) {
 7629:                            $thisallowed = 'B';
 7630:                        } else {
 7631:                            $thisallowed.=$value;
 7632:                        }
 7633:                    }
 7634:                } else {
 7635:                    $thisallowed.=$value;
 7636:                }
 7637:                $checkreferer=0;
 7638:            }
 7639:        }
 7640:        
 7641:        if ($checkreferer) {
 7642: 	  my $refuri=$env{'httpref.'.$orguri};
 7643:             unless ($refuri) {
 7644:                 foreach my $key (keys(%env)) {
 7645: 		    if ($key=~/^httpref\..*\*/) {
 7646: 			my $pattern=$key;
 7647:                         $pattern=~s/^httpref\.\/res\///;
 7648:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7649:                         $pattern=~s/\//\\\//g;
 7650:                         if ($orguri=~/$pattern/) {
 7651: 			    $refuri=$env{$key};
 7652:                         }
 7653:                     }
 7654:                 }
 7655:             }
 7656: 
 7657:          if ($refuri) { 
 7658: 	  $refuri=&declutter($refuri);
 7659:           my ($match,$cond)=&is_on_map($refuri);
 7660:             if ($match) {
 7661:               my $refstatecond=$cond;
 7662:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7663:                   =~/\Q$priv\E\&([^\:]*)/) {
 7664:                   my $value = $1;
 7665:                   if ($priv eq 'bre') {
 7666:                       if ($noblockcheck) {
 7667:                           $thisallowed.=$value;
 7668:                       } else {
 7669:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7670:                           if (@blockers > 0) {
 7671:                               $thisallowed = 'B';
 7672:                           } else {
 7673:                               $thisallowed.=$value;
 7674:                           }
 7675:                       }
 7676:                   } else {
 7677:                       $thisallowed.=$value;
 7678:                   }
 7679:                   $uri=$refuri;
 7680:                   $statecond=$refstatecond;
 7681:               }
 7682:           }
 7683:         }
 7684:        }
 7685:    }
 7686: 
 7687: #
 7688: # Gathered now: all privileges that could apply, and condition number
 7689: # 
 7690: #
 7691: # Full or no access?
 7692: #
 7693: 
 7694:     if ($thisallowed=~/F/) {
 7695: 	return 'F';
 7696:     }
 7697: 
 7698:     unless ($thisallowed) {
 7699:         return '';
 7700:     }
 7701: 
 7702: # Restrictions exist, deal with them
 7703: #
 7704: #   C:according to course preferences
 7705: #   R:according to resource settings
 7706: #   L:unless locked
 7707: #   X:according to user session state
 7708: #
 7709: 
 7710: # Possibly locked functionality, check all courses
 7711: # Locks might take effect only after 10 minutes cache expiration for other
 7712: # courses, and 2 minutes for current course
 7713: 
 7714:     my $envkey;
 7715:     if ($thisallowed=~/L/) {
 7716:         foreach $envkey (keys(%env)) {
 7717:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7718:                my $courseid=$2;
 7719:                my $roleid=$1.'.'.$2;
 7720:                $courseid=~s/^\///;
 7721:                my $expiretime=600;
 7722:                if ($env{'request.role'} eq $roleid) {
 7723: 		  $expiretime=120;
 7724:                }
 7725: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7726:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7727:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7728: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7729:                }
 7730:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7731:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7732: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7733:                        &log($env{'user.domain'},$env{'user.name'},
 7734:                             $env{'user.home'},
 7735:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7736:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7737:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7738: 		       return '';
 7739:                    }
 7740:                }
 7741:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7742:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7743: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7744:                        &log($env{'user.domain'},$env{'user.name'},
 7745:                             $env{'user.home'},
 7746:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7747:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7748:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7749: 		       return '';
 7750:                    }
 7751:                }
 7752: 	   }
 7753:        }
 7754:     }
 7755:    
 7756: #
 7757: # Rest of the restrictions depend on selected course
 7758: #
 7759: 
 7760:     unless ($env{'request.course.id'}) {
 7761: 	if ($thisallowed eq 'A') {
 7762: 	    return 'A';
 7763:         } elsif ($thisallowed eq 'B') {
 7764:             return 'B';
 7765: 	} else {
 7766: 	    return '1';
 7767: 	}
 7768:     }
 7769: 
 7770: #
 7771: # Now user is definitely in a course
 7772: #
 7773: 
 7774: 
 7775: # Course preferences
 7776: 
 7777:    if ($thisallowed=~/C/) {
 7778:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7779:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7780:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7781: 	   =~/\Q$rolecode\E/) {
 7782: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7783: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7784: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7785: 			$env{'request.course.id'});
 7786: 	   }
 7787:            return '';
 7788:        }
 7789: 
 7790:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7791: 	   =~/\Q$unamedom\E/) {
 7792: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7793: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7794: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7795: 			$env{'request.course.id'});
 7796: 	   }
 7797:            return '';
 7798:        }
 7799:    }
 7800: 
 7801: # Resource preferences
 7802: 
 7803:    if ($thisallowed=~/R/) {
 7804:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7805:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7806: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7807: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7808: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7809: 	   }
 7810: 	   return '';
 7811:        }
 7812:    }
 7813: 
 7814: # Restricted by state or randomout?
 7815: 
 7816:    if ($thisallowed=~/X/) {
 7817:       if ($env{'acc.randomout'}) {
 7818: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7819:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7820:             return ''; 
 7821:          }
 7822:       }
 7823:       if (&condval($statecond)) {
 7824: 	 return '2';
 7825:       } else {
 7826:          return '';
 7827:       }
 7828:    }
 7829: 
 7830:     if ($thisallowed eq 'A') {
 7831: 	return 'A';
 7832:     } elsif ($thisallowed eq 'B') {
 7833:         return 'B';
 7834:     }
 7835:    return 'F';
 7836: }
 7837: 
 7838: # ------------------------------------------- Check construction space access
 7839: 
 7840: sub constructaccess {
 7841:     my ($url,$setpriv)=@_;
 7842: 
 7843: # We do not allow editing of previous versions of files
 7844:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7845: 
 7846: # Get username and domain from URL
 7847:     my ($ownername,$ownerdomain,$ownerhome);
 7848: 
 7849:     ($ownerdomain,$ownername) =
 7850:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 7851: 
 7852: # The URL does not really point to any authorspace, forget it
 7853:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7854: 
 7855: # Now we need to see if the user has access to the authorspace of
 7856: # $ownername at $ownerdomain
 7857: 
 7858:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7859: # Real author for this?
 7860:        $ownerhome = $env{'user.home'};
 7861:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7862:           return ($ownername,$ownerdomain,$ownerhome);
 7863:        }
 7864:     } else {
 7865: # Co-author for this?
 7866:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7867:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7868:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7869:             return ($ownername,$ownerdomain,$ownerhome);
 7870:         }
 7871:         if ($env{'request.course.id'}) {
 7872:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 7873:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 7874:                 if (&allowed('mdc',$env{'request.course.id'})) {
 7875:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 7876:                     return ($ownername,$ownerdomain,$ownerhome);
 7877:                 }
 7878:             }
 7879:         }
 7880:     }
 7881: 
 7882: # We don't have any access right now. If we are not possibly going to do anything about this,
 7883: # we might as well leave
 7884:    unless ($setpriv) { return ''; }
 7885: 
 7886: # Backdoor access?
 7887:     my $allowed=&allowed('eco',$ownerdomain);
 7888: # Nope
 7889:     unless ($allowed) { return ''; }
 7890: # Looks like we may have access, but could be locked by the owner of the construction space
 7891:     if ($allowed eq 'U') {
 7892:         my %blocked=&get('environment',['domcoord.author'],
 7893:                          $ownerdomain,$ownername);
 7894: # Is blocked by owner
 7895:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7896:     }
 7897:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7898: # Grant temporary access
 7899:         my $then=$env{'user.login.time'};
 7900:         my $update=$env{'user.update.time'};
 7901:         if (!$update) { $update = $then; }
 7902:         my $refresh=$env{'user.refresh.time'};
 7903:         if (!$refresh) { $refresh = $update; }
 7904:         my $now = time;
 7905:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7906:                            $now,'ca','constructaccess');
 7907:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7908:         return($ownername,$ownerdomain,$ownerhome);
 7909:     }
 7910: # No business here
 7911:     return '';
 7912: }
 7913: 
 7914: # ----------------------------------------------------------- Content Blocking
 7915: 
 7916: {
 7917: # Caches for faster Course Contents display where content blocking
 7918: # is in operation (i.e., interval param set) for timed quiz.
 7919: #
 7920: # User for whom data are being temporarily cached.
 7921: my $cacheduser='';
 7922: # Cached blockers for this user (a hash of blocking items). 
 7923: my %cachedblockers=();
 7924: # When the data were last cached.
 7925: my $cachedlast='';
 7926: 
 7927: sub load_all_blockers {
 7928:     my ($uname,$udom,$blocks)=@_;
 7929:     if (($uname ne '') && ($udom ne '')) { 
 7930:         if (($cacheduser eq $uname.':'.$udom) &&
 7931:             (abs($cachedlast-time)<5)) {
 7932:             return;
 7933:         }
 7934:     }
 7935:     $cachedlast=time;
 7936:     $cacheduser=$uname.':'.$udom;
 7937:     %cachedblockers = &get_commblock_resources($blocks);
 7938: }
 7939: 
 7940: sub get_comm_blocks {
 7941:     my ($cdom,$cnum) = @_;
 7942:     if ($cdom eq '' || $cnum eq '') {
 7943:         return unless ($env{'request.course.id'});
 7944:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7945:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7946:     }
 7947:     my %commblocks;
 7948:     my $hashid=$cdom.'_'.$cnum;
 7949:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7950:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7951:         %commblocks = %{$blocksref};
 7952:     } else {
 7953:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7954:         my $cachetime = 600;
 7955:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7956:     }
 7957:     return %commblocks;
 7958: }
 7959: 
 7960: sub get_commblock_resources {
 7961:     my ($blocks) = @_;
 7962:     my %blockers = ();
 7963:     return %blockers unless ($env{'request.course.id'});
 7964:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7965:     my %commblocks;
 7966:     if (ref($blocks) eq 'HASH') {
 7967:         %commblocks = %{$blocks};
 7968:     } else {
 7969:         %commblocks = &get_comm_blocks();
 7970:     }
 7971:     return %blockers unless (keys(%commblocks) > 0); 
 7972:     my $navmap = Apache::lonnavmaps::navmap->new();
 7973:     return %blockers unless (ref($navmap));
 7974:     my $now = time;
 7975:     foreach my $block (keys(%commblocks)) {
 7976:         if ($block =~ /^(\d+)____(\d+)$/) {
 7977:             my ($start,$end) = ($1,$2);
 7978:             if ($start <= $now && $end >= $now) {
 7979:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7980:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7981:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7982:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 7983:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 7984:                             }
 7985:                         }
 7986:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7987:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 7988:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 7989:                             }
 7990:                         }
 7991:                     }
 7992:                 }
 7993:             }
 7994:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7995:             my $item = $1;
 7996:             my @to_test;
 7997:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7998:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7999:                     my @interval;
 8000:                     my $type = 'map';
 8001:                     if ($item eq 'course') {
 8002:                         $type = 'course';
 8003:                         @interval=&EXT("resource.0.interval");
 8004:                     } else {
 8005:                         if ($item =~ /___\d+___/) {
 8006:                             $type = 'resource';
 8007:                             @interval=&EXT("resource.0.interval",$item);
 8008:                             if (ref($navmap)) {                        
 8009:                                 my $res = $navmap->getBySymb($item); 
 8010:                                 push(@to_test,$res);
 8011:                             }
 8012:                         } else {
 8013:                             my $mapsymb = &symbread($item,1);
 8014:                             if ($mapsymb) {
 8015:                                 if (ref($navmap)) {
 8016:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8017:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8018:                                     foreach my $res (@to_test) {
 8019:                                         my $symb = $res->symb();
 8020:                                         next if ($symb eq $mapsymb);
 8021:                                         if ($symb ne '') {
 8022:                                             @interval=&EXT("resource.0.interval",$symb);
 8023:                                             if ($interval[1] eq 'map') {
 8024:                                                 last;
 8025:                                             }
 8026:                                         }
 8027:                                     }
 8028:                                 }
 8029:                             }
 8030:                         }
 8031:                     }
 8032:                     if ($interval[0] =~ /^(\d+)/) {
 8033:                         my $timelimit = $1; 
 8034:                         my $first_access;
 8035:                         if ($type eq 'resource') {
 8036:                             $first_access=&get_first_access($interval[1],$item);
 8037:                         } elsif ($type eq 'map') {
 8038:                             $first_access=&get_first_access($interval[1],undef,$item);
 8039:                         } else {
 8040:                             $first_access=&get_first_access($interval[1]);
 8041:                         }
 8042:                         if ($first_access) {
 8043:                             my $timesup = $first_access+$timelimit;
 8044:                             if ($timesup > $now) {
 8045:                                 my $activeblock;
 8046:                                 foreach my $res (@to_test) {
 8047:                                     if ($res->answerable()) {
 8048:                                         $activeblock = 1;
 8049:                                         last;
 8050:                                     }
 8051:                                 }
 8052:                                 if ($activeblock) {
 8053:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8054:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8055:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8056:                                          }
 8057:                                     }
 8058:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8059:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8060:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8061:                                         }
 8062:                                     }
 8063:                                 }
 8064:                             }
 8065:                         }
 8066:                     }
 8067:                 }
 8068:             }
 8069:         }
 8070:     }
 8071:     return %blockers;
 8072: }
 8073: 
 8074: sub has_comm_blocking {
 8075:     my ($priv,$symb,$uri,$blocks) = @_;
 8076:     my @blockers;
 8077:     return unless ($env{'request.course.id'});
 8078:     return unless ($priv eq 'bre');
 8079:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8080:     return if ($env{'request.state'} eq 'construct');
 8081:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8082:     return unless (keys(%cachedblockers) > 0);
 8083:     my (%possibles,@symbs);
 8084:     if (!$symb) {
 8085:         $symb = &symbread($uri,1,1,1,\%possibles);
 8086:     }
 8087:     if ($symb) {
 8088:         @symbs = ($symb);
 8089:     } elsif (keys(%possibles)) { 
 8090:         @symbs = keys(%possibles);
 8091:     }
 8092:     my $noblock;
 8093:     foreach my $symb (@symbs) {
 8094:         last if ($noblock);
 8095:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8096:         foreach my $block (keys(%cachedblockers)) {
 8097:             if ($block =~ /^firstaccess____(.+)$/) {
 8098:                 my $item = $1;
 8099:                 if (($item eq $map) || ($item eq $symb)) {
 8100:                     $noblock = 1;
 8101:                     last;
 8102:                 }
 8103:             }
 8104:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8105:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8106:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8107:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8108:                             push(@blockers,$block);
 8109:                         }
 8110:                     }
 8111:                 }
 8112:             }
 8113:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8114:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8115:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8116:                         push(@blockers,$block);
 8117:                     }
 8118:                 }
 8119:             }
 8120:         }
 8121:     }
 8122:     return if ($noblock);
 8123:     return @blockers;
 8124: }
 8125: }
 8126: 
 8127: # -------------------------------- Deversion and split uri into path an filename   
 8128: 
 8129: #
 8130: #   Removes the version from a URI and
 8131: #   splits it in to its filename and path to the filename.
 8132: #   Seems like File::Basename could have done this more clearly.
 8133: #   Parameters:
 8134: #      $uri   - input URI
 8135: #   Returns:
 8136: #     Two element list consisting of 
 8137: #     $pathname  - the URI up to and excluding the trailing /
 8138: #     $filename  - The part of the URI following the last /
 8139: #  NOTE:
 8140: #    Another realization of this is simply:
 8141: #    use File::Basename;
 8142: #    ...
 8143: #    $uri = shift;
 8144: #    $filename = basename($uri);
 8145: #    $path     = dirname($uri);
 8146: #    return ($filename, $path);
 8147: #
 8148: #     The implementation below is probably faster however.
 8149: #
 8150: sub split_uri_for_cond {
 8151:     my $uri=&deversion(&declutter(shift));
 8152:     my @uriparts=split(/\//,$uri);
 8153:     my $filename=pop(@uriparts);
 8154:     my $pathname=join('/',@uriparts);
 8155:     return ($pathname,$filename);
 8156: }
 8157: # --------------------------------------------------- Is a resource on the map?
 8158: 
 8159: sub is_on_map {
 8160:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8161:     #Trying to find the conditional for the file
 8162:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8163: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8164:     if ($match) {
 8165: 	return (1,$1);
 8166:     } else {
 8167: 	return (0,0);
 8168:     }
 8169: }
 8170: 
 8171: # --------------------------------------------------------- Get symb from alias
 8172: 
 8173: sub get_symb_from_alias {
 8174:     my $symb=shift;
 8175:     my ($map,$resid,$url)=&decode_symb($symb);
 8176: # Already is a symb
 8177:     if ($url) { return $symb; }
 8178: # Must be an alias
 8179:     my $aliassymb='';
 8180:     my %bighash;
 8181:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8182:                             &GDBM_READER(),0640)) {
 8183:         my $rid=$bighash{'mapalias_'.$symb};
 8184: 	if ($rid) {
 8185: 	    my ($mapid,$resid)=split(/\./,$rid);
 8186: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8187: 				    $resid,$bighash{'src_'.$rid});
 8188: 	}
 8189:         untie %bighash;
 8190:     }
 8191:     return $aliassymb;
 8192: }
 8193: 
 8194: # ----------------------------------------------------------------- Define Role
 8195: 
 8196: sub definerole {
 8197:   if (allowed('mcr','/')) {
 8198:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8199:     foreach my $role (split(':',$sysrole)) {
 8200: 	my ($crole,$cqual)=split(/\&/,$role);
 8201:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8202:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8203: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8204:                return "refused:s:$crole&$cqual"; 
 8205:             }
 8206:         }
 8207:     }
 8208:     foreach my $role (split(':',$domrole)) {
 8209: 	my ($crole,$cqual)=split(/\&/,$role);
 8210:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8211:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8212: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8213:                return "refused:d:$crole&$cqual"; 
 8214:             }
 8215:         }
 8216:     }
 8217:     foreach my $role (split(':',$courole)) {
 8218: 	my ($crole,$cqual)=split(/\&/,$role);
 8219:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8220:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8221: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8222:                return "refused:c:$crole&$cqual"; 
 8223:             }
 8224:         }
 8225:     }
 8226:     my $uhome;
 8227:     if (($uname ne '') && ($udom ne '')) {
 8228:         $uhome = &homeserver($uname,$udom);
 8229:         return $uhome if ($uhome eq 'no_host');
 8230:     } else {
 8231:         $uname = $env{'user.name'};
 8232:         $udom = $env{'user.domain'};
 8233:         $uhome = $env{'user.home'};
 8234:     }
 8235:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8236:                 "$udom:$uname:rolesdef_$rolename=".
 8237:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8238:     return reply($command,$uhome);
 8239:   } else {
 8240:     return 'refused';
 8241:   }
 8242: }
 8243: 
 8244: # ---------------- Make a metadata query against the network of library servers
 8245: 
 8246: sub metadata_query {
 8247:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8248:     my %rhash;
 8249:     my %libserv = &all_library();
 8250:     my @server_list = (defined($server_array) ? @$server_array
 8251:                                               : keys(%libserv) );
 8252:     for my $server (@server_list) {
 8253:         my $domains = ''; 
 8254:         if (ref($domains_hash) eq 'HASH') {
 8255:             $domains = $domains_hash->{$server}; 
 8256:         }
 8257: 	unless ($custom or $customshow) {
 8258: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8259: 	    $rhash{$server}=$reply;
 8260: 	}
 8261: 	else {
 8262: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8263: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8264: 			     $server);
 8265: 	    $rhash{$server}=$reply;
 8266: 	}
 8267:     }
 8268:     return \%rhash;
 8269: }
 8270: 
 8271: # ----------------------------------------- Send log queries and wait for reply
 8272: 
 8273: sub log_query {
 8274:     my ($uname,$udom,$query,%filters)=@_;
 8275:     my $uhome=&homeserver($uname,$udom);
 8276:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8277:     my $uhost=&hostname($uhome);
 8278:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8279:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8280:                        $uhome);
 8281:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8282:     return get_query_reply($queryid);
 8283: }
 8284: 
 8285: # -------------------------- Update MySQL table for portfolio file
 8286: 
 8287: sub update_portfolio_table {
 8288:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8289:     if ($group ne '') {
 8290:         $file_name =~s /^\Q$group\E//;
 8291:     }
 8292:     my $homeserver = &homeserver($uname,$udom);
 8293:     my $queryid=
 8294:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8295:                ':'.&escape($file_name).':'.$action,$homeserver);
 8296:     my $reply = &get_query_reply($queryid);
 8297:     return $reply;
 8298: }
 8299: 
 8300: # -------------------------- Update MySQL allusers table
 8301: 
 8302: sub update_allusers_table {
 8303:     my ($uname,$udom,$names) = @_;
 8304:     my $homeserver = &homeserver($uname,$udom);
 8305:     my $queryid=
 8306:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8307:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8308:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8309:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8310:                'generation='.&escape($names->{'generation'}).'%%'.
 8311:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8312:                'id='.&escape($names->{'id'}),$homeserver);
 8313:     return;
 8314: }
 8315: 
 8316: # ------- Request retrieval of institutional classlists for course(s)
 8317: 
 8318: sub fetch_enrollment_query {
 8319:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8320:     my ($homeserver,$sleep,$loopmax);
 8321:     my $maxtries = 1;
 8322:     if ($context eq 'automated') {
 8323:         $homeserver = $perlvar{'lonHostID'};
 8324:         $sleep = 2;
 8325:         $loopmax = 100;
 8326:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8327:     } else {
 8328:         $homeserver = &homeserver($cnum,$dom);
 8329:     }
 8330:     my $host=&hostname($homeserver);
 8331:     my $cmd = '';
 8332:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8333:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8334:     }
 8335:     $cmd =~ s/%%$//;
 8336:     $cmd = &escape($cmd);
 8337:     my $query = 'fetchenrollment';
 8338:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8339:     unless ($queryid=~/^\Q$host\E\_/) { 
 8340:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8341:         return 'error: '.$queryid;
 8342:     }
 8343:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8344:     my $tries = 1;
 8345:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8346:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8347:         $tries ++;
 8348:     }
 8349:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8350:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8351:     } else {
 8352:         my @responses = split(/:/,$reply);
 8353:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8354:             foreach my $line (@responses) {
 8355:                 my ($key,$value) = split(/=/,$line,2);
 8356:                 $$replyref{$key} = $value;
 8357:             }
 8358:         } else {
 8359:             my $pathname = LONCAPA::tempdir();
 8360:             foreach my $line (@responses) {
 8361:                 my ($key,$value) = split(/=/,$line);
 8362:                 $$replyref{$key} = $value;
 8363:                 if ($value > 0) {
 8364:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8365:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8366:                         my $destname = $pathname.'/'.$filename;
 8367:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8368:                         if ($xml_classlist =~ /^error/) {
 8369:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8370:                         } else {
 8371:                             if ( open(FILE,">$destname") ) {
 8372:                                 print FILE &unescape($xml_classlist);
 8373:                                 close(FILE);
 8374:                             } else {
 8375:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8376:                             }
 8377:                         }
 8378:                     }
 8379:                 }
 8380:             }
 8381:         }
 8382:         return 'ok';
 8383:     }
 8384:     return 'error';
 8385: }
 8386: 
 8387: sub get_query_reply {
 8388:     my ($queryid,$sleep,$loopmax) = @_;;
 8389:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8390:         $sleep = 0.2;
 8391:     }
 8392:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8393:         $loopmax = 100;
 8394:     }
 8395:     my $replyfile=LONCAPA::tempdir().$queryid;
 8396:     my $reply='';
 8397:     for (1..$loopmax) {
 8398: 	sleep($sleep);
 8399:         if (-e $replyfile.'.end') {
 8400: 	    if (open(my $fh,$replyfile)) {
 8401: 		$reply = join('',<$fh>);
 8402: 		close($fh);
 8403: 	   } else { return 'error: reply_file_error'; }
 8404:            return &unescape($reply);
 8405: 	}
 8406:     }
 8407:     return 'timeout:'.$queryid;
 8408: }
 8409: 
 8410: sub courselog_query {
 8411: #
 8412: # possible filters:
 8413: # url: url or symb
 8414: # username
 8415: # domain
 8416: # action: view, submit, grade
 8417: # start: timestamp
 8418: # end: timestamp
 8419: #
 8420:     my (%filters)=@_;
 8421:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8422:     if ($filters{'url'}) {
 8423: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8424:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8425:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8426:     }
 8427:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8428:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8429:     return &log_query($cname,$cdom,'courselog',%filters);
 8430: }
 8431: 
 8432: sub userlog_query {
 8433: #
 8434: # possible filters:
 8435: # action: log check role
 8436: # start: timestamp
 8437: # end: timestamp
 8438: #
 8439:     my ($uname,$udom,%filters)=@_;
 8440:     return &log_query($uname,$udom,'userlog',%filters);
 8441: }
 8442: 
 8443: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8444: 
 8445: sub auto_run {
 8446:     my ($cnum,$cdom) = @_;
 8447:     my $response = 0;
 8448:     my $settings;
 8449:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8450:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8451:         $settings = $domconfig{'autoenroll'};
 8452:         if ($settings->{'run'} eq '1') {
 8453:             $response = 1;
 8454:         }
 8455:     } else {
 8456:         my $homeserver;
 8457:         if (&is_course($cdom,$cnum)) {
 8458:             $homeserver = &homeserver($cnum,$cdom);
 8459:         } else {
 8460:             $homeserver = &domain($cdom,'primary');
 8461:         }
 8462:         if ($homeserver ne 'no_host') {
 8463:             $response = &reply('autorun:'.$cdom,$homeserver);
 8464:         }
 8465:     }
 8466:     return $response;
 8467: }
 8468: 
 8469: sub auto_get_sections {
 8470:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8471:     my $homeserver;
 8472:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8473:         $homeserver = &homeserver($cnum,$cdom);
 8474:     }
 8475:     if (!defined($homeserver)) { 
 8476:         if ($cdom =~ /^$match_domain$/) {
 8477:             $homeserver = &domain($cdom,'primary');
 8478:         }
 8479:     }
 8480:     my @secs;
 8481:     if (defined($homeserver)) {
 8482:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8483:         unless ($response eq 'refused') {
 8484:             @secs = split(/:/,$response);
 8485:         }
 8486:     }
 8487:     return @secs;
 8488: }
 8489: 
 8490: sub auto_new_course {
 8491:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8492:     my $homeserver = &homeserver($cnum,$cdom);
 8493:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8494:     return $response;
 8495: }
 8496: 
 8497: sub auto_validate_courseID {
 8498:     my ($cnum,$cdom,$inst_course_id) = @_;
 8499:     my $homeserver = &homeserver($cnum,$cdom);
 8500:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8501:     return $response;
 8502: }
 8503: 
 8504: sub auto_validate_instcode {
 8505:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8506:     my ($homeserver,$response);
 8507:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8508:         $homeserver = &homeserver($cnum,$cdom);
 8509:     }
 8510:     if (!defined($homeserver)) {
 8511:         if ($cdom =~ /^$match_domain$/) {
 8512:             $homeserver = &domain($cdom,'primary');
 8513:         }
 8514:     }
 8515:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8516:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8517:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8518:     return ($outcome,$description,$defaultcredits);
 8519: }
 8520: 
 8521: sub auto_create_password {
 8522:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8523:     my ($homeserver,$response);
 8524:     my $create_passwd = 0;
 8525:     my $authchk = '';
 8526:     if ($udom =~ /^$match_domain$/) {
 8527:         $homeserver = &domain($udom,'primary');
 8528:     }
 8529:     if ($homeserver eq '') {
 8530:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8531:             $homeserver = &homeserver($cnum,$cdom);
 8532:         }
 8533:     }
 8534:     if ($homeserver eq '') {
 8535:         $authchk = 'nodomain';
 8536:     } else {
 8537:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8538:         if ($response eq 'refused') {
 8539:             $authchk = 'refused';
 8540:         } else {
 8541:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8542:         }
 8543:     }
 8544:     return ($authparam,$create_passwd,$authchk);
 8545: }
 8546: 
 8547: sub auto_photo_permission {
 8548:     my ($cnum,$cdom,$students) = @_;
 8549:     my $homeserver = &homeserver($cnum,$cdom);
 8550:     my ($outcome,$perm_reqd,$conditions) = 
 8551: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8552:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8553: 	return (undef,undef);
 8554:     }
 8555:     return ($outcome,$perm_reqd,$conditions);
 8556: }
 8557: 
 8558: sub auto_checkphotos {
 8559:     my ($uname,$udom,$pid) = @_;
 8560:     my $homeserver = &homeserver($uname,$udom);
 8561:     my ($result,$resulttype);
 8562:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8563: 				   &escape($uname).':'.&escape($pid),
 8564: 				   $homeserver));
 8565:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8566: 	return (undef,undef);
 8567:     }
 8568:     if ($outcome) {
 8569:         ($result,$resulttype) = split(/:/,$outcome);
 8570:     } 
 8571:     return ($result,$resulttype);
 8572: }
 8573: 
 8574: sub auto_photochoice {
 8575:     my ($cnum,$cdom) = @_;
 8576:     my $homeserver = &homeserver($cnum,$cdom);
 8577:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8578: 						       &escape($cdom),
 8579: 						       $homeserver)));
 8580:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8581: 	return (undef,undef);
 8582:     }
 8583:     return ($update,$comment);
 8584: }
 8585: 
 8586: sub auto_photoupdate {
 8587:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8588:     my $homeserver = &homeserver($cnum,$dom);
 8589:     my $host=&hostname($homeserver);
 8590:     my $cmd = '';
 8591:     my $maxtries = 1;
 8592:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8593:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8594:     }
 8595:     $cmd =~ s/%%$//;
 8596:     $cmd = &escape($cmd);
 8597:     my $query = 'institutionalphotos';
 8598:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8599:     unless ($queryid=~/^\Q$host\E\_/) {
 8600:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8601:         return 'error: '.$queryid;
 8602:     }
 8603:     my $reply = &get_query_reply($queryid);
 8604:     my $tries = 1;
 8605:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8606:         $reply = &get_query_reply($queryid);
 8607:         $tries ++;
 8608:     }
 8609:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8610:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8611:     } else {
 8612:         my @responses = split(/:/,$reply);
 8613:         my $outcome = shift(@responses); 
 8614:         foreach my $item (@responses) {
 8615:             my ($key,$value) = split(/=/,$item);
 8616:             $$photo{$key} = $value;
 8617:         }
 8618:         return $outcome;
 8619:     }
 8620:     return 'error';
 8621: }
 8622: 
 8623: sub auto_instcode_format {
 8624:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8625: 	$cat_order) = @_;
 8626:     my $courses = '';
 8627:     my @homeservers;
 8628:     if ($caller eq 'global') {
 8629: 	my %servers = &get_servers($codedom,'library');
 8630: 	foreach my $tryserver (keys(%servers)) {
 8631: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8632: 		push(@homeservers,$tryserver);
 8633: 	    }
 8634:         }
 8635:     } elsif ($caller eq 'requests') {
 8636:         if ($codedom =~ /^$match_domain$/) {
 8637:             my $chome = &domain($codedom,'primary');
 8638:             unless ($chome eq 'no_host') {
 8639:                 push(@homeservers,$chome);
 8640:             }
 8641:         }
 8642:     } else {
 8643:         push(@homeservers,&homeserver($caller,$codedom));
 8644:     }
 8645:     foreach my $code (keys(%{$instcodes})) {
 8646:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8647:     }
 8648:     chop($courses);
 8649:     my $ok_response = 0;
 8650:     my $response;
 8651:     while (@homeservers > 0 && $ok_response == 0) {
 8652:         my $server = shift(@homeservers); 
 8653:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8654:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8655:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8656: 		split(/:/,$response);
 8657:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8658:             push(@{$codetitles},&str2array($codetitles_str));
 8659:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8660:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8661:             $ok_response = 1;
 8662:         }
 8663:     }
 8664:     if ($ok_response) {
 8665:         return 'ok';
 8666:     } else {
 8667:         return $response;
 8668:     }
 8669: }
 8670: 
 8671: sub auto_instcode_defaults {
 8672:     my ($domain,$returnhash,$code_order) = @_;
 8673:     my @homeservers;
 8674: 
 8675:     my %servers = &get_servers($domain,'library');
 8676:     foreach my $tryserver (keys(%servers)) {
 8677: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8678: 	    push(@homeservers,$tryserver);
 8679: 	}
 8680:     }
 8681: 
 8682:     my $response;
 8683:     foreach my $server (@homeservers) {
 8684:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8685:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8686: 	
 8687: 	foreach my $pair (split(/\&/,$response)) {
 8688: 	    my ($name,$value)=split(/\=/,$pair);
 8689: 	    if ($name eq 'code_order') {
 8690: 		@{$code_order} = split(/\&/,&unescape($value));
 8691: 	    } else {
 8692: 		$returnhash->{&unescape($name)}=&unescape($value);
 8693: 	    }
 8694: 	}
 8695: 	return 'ok';
 8696:     }
 8697: 
 8698:     return $response;
 8699: }
 8700: 
 8701: sub auto_possible_instcodes {
 8702:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8703:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8704:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8705:         return;
 8706:     }
 8707:     my (@homeservers,$uhome);
 8708:     if (defined(&domain($domain,'primary'))) {
 8709:         $uhome=&domain($domain,'primary');
 8710:         push(@homeservers,&domain($domain,'primary'));
 8711:     } else {
 8712:         my %servers = &get_servers($domain,'library');
 8713:         foreach my $tryserver (keys(%servers)) {
 8714:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8715:                 push(@homeservers,$tryserver);
 8716:             }
 8717:         }
 8718:     }
 8719:     my $response;
 8720:     foreach my $server (@homeservers) {
 8721:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8722:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8723:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8724:             split(':',$response);
 8725:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8726:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8727:         foreach my $item (split('&',$cat_title)) {   
 8728:             my ($name,$value)=split('=',$item);
 8729:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8730:         }
 8731:         foreach my $item (split('&',$cat_order)) {
 8732:             my ($name,$value)=split('=',$item);
 8733:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8734:         }
 8735:         return 'ok';
 8736:     }
 8737:     return $response;
 8738: }
 8739: 
 8740: sub auto_courserequest_checks {
 8741:     my ($dom) = @_;
 8742:     my ($homeserver,%validations);
 8743:     if ($dom =~ /^$match_domain$/) {
 8744:         $homeserver = &domain($dom,'primary');
 8745:     }
 8746:     unless ($homeserver eq 'no_host') {
 8747:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8748:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8749:             my @items = split(/&/,$response);
 8750:             foreach my $item (@items) {
 8751:                 my ($key,$value) = split('=',$item);
 8752:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8753:             }
 8754:         }
 8755:     }
 8756:     return %validations; 
 8757: }
 8758: 
 8759: sub auto_courserequest_validation {
 8760:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8761:     my ($homeserver,$response);
 8762:     if ($dom =~ /^$match_domain$/) {
 8763:         $homeserver = &domain($dom,'primary');
 8764:     }
 8765:     unless ($homeserver eq 'no_host') {
 8766:         my $customdata;
 8767:         if (ref($custominfo) eq 'HASH') {
 8768:             $customdata = &freeze_escape($custominfo);
 8769:         }
 8770:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8771:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8772:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8773:                                     $customdata,$homeserver));
 8774:     }
 8775:     return $response;
 8776: }
 8777: 
 8778: sub auto_validate_class_sec {
 8779:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8780:     my $homeserver = &homeserver($cnum,$cdom);
 8781:     my $ownerlist;
 8782:     if (ref($owners) eq 'ARRAY') {
 8783:         $ownerlist = join(',',@{$owners});
 8784:     } else {
 8785:         $ownerlist = $owners;
 8786:     }
 8787:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8788:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8789:     return $response;
 8790: }
 8791: 
 8792: sub auto_crsreq_update {
 8793:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8794:         $code,$accessstart,$accessend,$inbound) = @_;
 8795:     my ($homeserver,%crsreqresponse);
 8796:     if ($cdom =~ /^$match_domain$/) {
 8797:         $homeserver = &domain($cdom,'primary');
 8798:     }
 8799:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8800:         my $info;
 8801:         if (ref($inbound) eq 'HASH') {
 8802:             $info = &freeze_escape($inbound);
 8803:         }
 8804:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8805:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8806:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8807:                             &escape($title).':'.&escape($code).':'.
 8808:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8809:                             $homeserver);
 8810:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8811:             my @items = split(/&/,$response);
 8812:             foreach my $item (@items) {
 8813:                 my ($key,$value) = split('=',$item);
 8814:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8815:             }
 8816:         }
 8817:     }
 8818:     return \%crsreqresponse;
 8819: }
 8820: 
 8821: sub auto_export_grades {
 8822:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 8823:     my ($homeserver,%exportresponse);
 8824:     if ($cdom =~ /^$match_domain$/) {
 8825:         $homeserver = &domain($cdom,'primary');
 8826:     }
 8827:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8828:         my $info;
 8829:         if (ref($inforef) eq 'HASH') {
 8830:             $info = &freeze_escape($inforef);
 8831:         }
 8832:         if (ref($gradesref) eq 'HASH') {
 8833:             my $grades = &freeze_escape($gradesref);
 8834:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 8835:                                 $info.':'.$grades,$homeserver);
 8836:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 8837:                 my @items = split(/&/,$response);
 8838:                 foreach my $item (@items) {
 8839:                     my ($key,$value) = split('=',$item);
 8840:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 8841:                 }
 8842:             }
 8843:         }
 8844:     }
 8845:     return \%exportresponse;
 8846: }
 8847: 
 8848: sub check_instcode_cloning {
 8849:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 8850:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8851:         return;
 8852:     }
 8853:     my $canclone;
 8854:     if (@{$code_order} > 0) {
 8855:         my $instcoderegexp ='^';
 8856:         my @clonecodes = split(/\&/,$cloner);
 8857:         foreach my $item (@{$code_order}) {
 8858:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 8859:                 foreach my $pair (@clonecodes) {
 8860:                     my ($key,$val) = split(/\=/,$pair,2);
 8861:                     $val = &unescape($val);
 8862:                     if ($key eq $item) {
 8863:                         $instcoderegexp .= '('.$val.')';
 8864:                         last;
 8865:                     }
 8866:                 }
 8867:             } else {
 8868:                 $instcoderegexp .= $codedefaults->{$item};
 8869:             }
 8870:         }
 8871:         $instcoderegexp .= '$';
 8872:         my (@from,@to);
 8873:         eval {
 8874:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8875:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 8876:         };
 8877:         if ((@from > 0) && (@to > 0)) {
 8878:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8879:             if (!@diffs) {
 8880:                 $canclone = 1;
 8881:             }
 8882:         }
 8883:     }
 8884:     return $canclone;
 8885: }
 8886: 
 8887: sub default_instcode_cloning {
 8888:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 8889:     my (%codedefaults,@code_order,$canclone);
 8890:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 8891:         %codedefaults = %{$codedefaultsref};
 8892:         @code_order = @{$codeorderref};
 8893:     } elsif ($clonedom) {
 8894:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 8895:     }
 8896:     if (($domdefclone) && (@code_order)) {
 8897:         my @clonecodes = split(/\+/,$domdefclone);
 8898:         my $instcoderegexp ='^';
 8899:         foreach my $item (@code_order) {
 8900:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 8901:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 8902:             } else {
 8903:                 $instcoderegexp .= $codedefaults{$item};
 8904:             }
 8905:         }
 8906:         $instcoderegexp .= '$';
 8907:         my (@from,@to);
 8908:         eval {
 8909:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8910:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 8911:         };
 8912:         if ((@from > 0) && (@to > 0)) {
 8913:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8914:             if (!@diffs) {
 8915:                 $canclone = 1;
 8916:             }
 8917:         }
 8918:     }
 8919:     return $canclone;
 8920: }
 8921: 
 8922: # ------------------------------------------------------- Course Group routines
 8923: 
 8924: sub get_coursegroups {
 8925:     my ($cdom,$cnum,$group,$namespace) = @_;
 8926:     return(&dump($namespace,$cdom,$cnum,$group));
 8927: }
 8928: 
 8929: sub modify_coursegroup {
 8930:     my ($cdom,$cnum,$groupsettings) = @_;
 8931:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 8932: }
 8933: 
 8934: sub toggle_coursegroup_status {
 8935:     my ($cdom,$cnum,$group,$action) = @_;
 8936:     my ($from_namespace,$to_namespace);
 8937:     if ($action eq 'delete') {
 8938:         $from_namespace = 'coursegroups';
 8939:         $to_namespace = 'deleted_groups';
 8940:     } else {
 8941:         $from_namespace = 'deleted_groups';
 8942:         $to_namespace = 'coursegroups';
 8943:     }
 8944:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 8945:     if (my $tmp = &error(%curr_group)) {
 8946:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 8947:         return ('read error',$tmp);
 8948:     } else {
 8949:         my %savedsettings = %curr_group; 
 8950:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 8951:         my $deloutcome;
 8952:         if ($result eq 'ok') {
 8953:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 8954:         } else {
 8955:             return ('write error',$result);
 8956:         }
 8957:         if ($deloutcome eq 'ok') {
 8958:             return 'ok';
 8959:         } else {
 8960:             return ('delete error',$deloutcome);
 8961:         }
 8962:     }
 8963: }
 8964: 
 8965: sub modify_group_roles {
 8966:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 8967:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 8968:     my $role = 'gr/'.&escape($userprivs);
 8969:     my ($uname,$udom) = split(/:/,$user);
 8970:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 8971:     if ($result eq 'ok') {
 8972:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 8973:     }
 8974:     return $result;
 8975: }
 8976: 
 8977: sub modify_coursegroup_membership {
 8978:     my ($cdom,$cnum,$membership) = @_;
 8979:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 8980:     return $result;
 8981: }
 8982: 
 8983: sub get_active_groups {
 8984:     my ($udom,$uname,$cdom,$cnum) = @_;
 8985:     my $now = time;
 8986:     my %groups = ();
 8987:     foreach my $key (keys(%env)) {
 8988:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 8989:             my ($start,$end) = split(/\./,$env{$key});
 8990:             if (($end!=0) && ($end<$now)) { next; }
 8991:             if (($start!=0) && ($start>$now)) { next; }
 8992:             if ($1 eq $cdom && $2 eq $cnum) {
 8993:                 $groups{$3} = $env{$key} ;
 8994:             }
 8995:         }
 8996:     }
 8997:     return %groups;
 8998: }
 8999: 
 9000: sub get_group_membership {
 9001:     my ($cdom,$cnum,$group) = @_;
 9002:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9003: }
 9004: 
 9005: sub get_users_groups {
 9006:     my ($udom,$uname,$courseid) = @_;
 9007:     my @usersgroups;
 9008:     my $cachetime=1800;
 9009: 
 9010:     my $hashid="$udom:$uname:$courseid";
 9011:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9012:     if (defined($cached)) {
 9013:         @usersgroups = split(/:/,$grouplist);
 9014:     } else {  
 9015:         $grouplist = '';
 9016:         my $courseurl = &courseid_to_courseurl($courseid);
 9017:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9018:         my $access_end = $env{'course.'.$courseid.
 9019:                               '.default_enrollment_end_date'};
 9020:         my $now = time;
 9021:         foreach my $key (keys(%roleshash)) {
 9022:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9023:                 my $group = $1;
 9024:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9025:                     my $start = $2;
 9026:                     my $end = $1;
 9027:                     if ($start == -1) { next; } # deleted from group
 9028:                     if (($start!=0) && ($start>$now)) { next; }
 9029:                     if (($end!=0) && ($end<$now)) {
 9030:                         if ($access_end && $access_end < $now) {
 9031:                             if ($access_end - $end < 86400) {
 9032:                                 push(@usersgroups,$group);
 9033:                             }
 9034:                         }
 9035:                         next;
 9036:                     }
 9037:                     push(@usersgroups,$group);
 9038:                 }
 9039:             }
 9040:         }
 9041:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9042:         $grouplist = join(':',@usersgroups);
 9043:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9044:     }
 9045:     return @usersgroups;
 9046: }
 9047: 
 9048: sub devalidate_getgroups_cache {
 9049:     my ($udom,$uname,$cdom,$cnum)=@_;
 9050:     my $courseid = $cdom.'_'.$cnum;
 9051: 
 9052:     my $hashid="$udom:$uname:$courseid";
 9053:     &devalidate_cache_new('getgroups',$hashid);
 9054: }
 9055: 
 9056: # ------------------------------------------------------------------ Plain Text
 9057: 
 9058: sub plaintext {
 9059:     my ($short,$type,$cid,$forcedefault) = @_;
 9060:     if ($short =~ m{^cr/}) {
 9061: 	return (split('/',$short))[-1];
 9062:     }
 9063:     if (!defined($cid)) {
 9064:         $cid = $env{'request.course.id'};
 9065:     }
 9066:     my %rolenames = (
 9067:                       Course    => 'std',
 9068:                       Community => 'alt1',
 9069:                       Placement => 'std',
 9070:                     );
 9071:     if ($cid ne '') {
 9072:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9073:             unless ($forcedefault) {
 9074:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9075:                 &Apache::lonlocal::mt_escape(\$roletext);
 9076:                 return &Apache::lonlocal::mt($roletext);
 9077:             }
 9078:         }
 9079:     }
 9080:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9081:         (defined($rolenames{$type})) && 
 9082:         (defined($prp{$short}{$rolenames{$type}}))) {
 9083:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9084:     } elsif ($cid ne '') {
 9085:         my $crstype = $env{'course.'.$cid.'.type'};
 9086:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9087:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9088:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9089:         }
 9090:     }
 9091:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9092: }
 9093: 
 9094: # ----------------------------------------------------------------- Assign Role
 9095: 
 9096: sub assignrole {
 9097:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9098:         $context)=@_;
 9099:     my $mrole;
 9100:     if ($role =~ /^cr\//) {
 9101:         my $cwosec=$url;
 9102:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9103: 	unless (&allowed('ccr',$cwosec)) {
 9104:            my $refused = 1;
 9105:            if ($context eq 'requestcourses') {
 9106:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9107:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9108:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9109:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9110:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9111:                            if ($crsenv{'internal.courseowner'} eq
 9112:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9113:                                $refused = '';
 9114:                            }
 9115:                        }
 9116:                    }
 9117:                }
 9118:            }
 9119:            if ($refused) {
 9120:                &logthis('Refused custom assignrole: '.
 9121:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9122:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9123:                return 'refused';
 9124:            }
 9125:         }
 9126:         $mrole='cr';
 9127:     } elsif ($role =~ /^gr\//) {
 9128:         my $cwogrp=$url;
 9129:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9130:         unless (&allowed('mdg',$cwogrp)) {
 9131:             &logthis('Refused group assignrole: '.
 9132:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9133:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9134:             return 'refused';
 9135:         }
 9136:         $mrole='gr';
 9137:     } else {
 9138:         my $cwosec=$url;
 9139:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9140:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9141:             my $refused;
 9142:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9143:                 if (!(&allowed('c'.$role,$url))) {
 9144:                     $refused = 1;
 9145:                 }
 9146:             } else {
 9147:                 $refused = 1;
 9148:             }
 9149:             if ($refused) {
 9150:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9151:                 if (!$selfenroll && $context eq 'course') {
 9152:                     my %crsenv;
 9153:                     if ($role eq 'cc' || $role eq 'co') {
 9154:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9155:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9156:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9157:                                 if ($crsenv{'internal.courseowner'} eq 
 9158:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9159:                                     $refused = '';
 9160:                                 }
 9161:                             }
 9162:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9163:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9164:                                 if ($crsenv{'internal.courseowner'} eq 
 9165:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9166:                                     $refused = '';
 9167:                                 }
 9168:                             }
 9169:                         }
 9170:                     }
 9171:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9172:                     $refused = '';
 9173:                 } elsif ($context eq 'requestcourses') {
 9174:                     my @possroles = ('st','ta','ep','in','cc','co');
 9175:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9176:                         my $wrongcc;
 9177:                         if ($cnum =~ /^$match_community$/) {
 9178:                             $wrongcc = 1 if ($role eq 'cc');
 9179:                         } else {
 9180:                             $wrongcc = 1 if ($role eq 'co');
 9181:                         }
 9182:                         unless ($wrongcc) {
 9183:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9184:                             if ($crsenv{'internal.courseowner'} eq 
 9185:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9186:                                 $refused = '';
 9187:                             }
 9188:                         }
 9189:                     }
 9190:                 } elsif ($context eq 'requestauthor') {
 9191:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9192:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9193:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9194:                             $refused = '';
 9195:                         } else {
 9196:                             my %domdefaults = &get_domain_defaults($udom);
 9197:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9198:                                 my $checkbystatus;
 9199:                                 if ($env{'user.adv'}) { 
 9200:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9201:                                     if ($disposition eq 'automatic') {
 9202:                                         $refused = '';
 9203:                                     } elsif ($disposition eq '') {
 9204:                                         $checkbystatus = 1;
 9205:                                     } 
 9206:                                 } else {
 9207:                                     $checkbystatus = 1;
 9208:                                 }
 9209:                                 if ($checkbystatus) {
 9210:                                     if ($env{'environment.inststatus'}) {
 9211:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9212:                                         foreach my $type (@inststatuses) {
 9213:                                             if (($type ne '') &&
 9214:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9215:                                                 $refused = '';
 9216:                                             }
 9217:                                         }
 9218:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9219:                                         $refused = '';
 9220:                                     }
 9221:                                 }
 9222:                             }
 9223:                         }
 9224:                     }
 9225:                 }
 9226:                 if ($refused) {
 9227:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9228:                              ' '.$role.' '.$end.' '.$start.' by '.
 9229: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9230:                     return 'refused';
 9231:                 }
 9232:             }
 9233:         } elsif ($role eq 'au') {
 9234:             if ($url ne '/'.$udom.'/') {
 9235:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9236:                          ' to assign author role for '.$uname.':'.$udom.
 9237:                          ' in domain: '.$url.' refused (wrong domain).');
 9238:                 return 'refused';
 9239:             }
 9240:         }
 9241:         $mrole=$role;
 9242:     }
 9243:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9244:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9245:     if ($end) { $command.='_'.$end; }
 9246:     if ($start) {
 9247: 	if ($end) { 
 9248:            $command.='_'.$start; 
 9249:         } else {
 9250:            $command.='_0_'.$start;
 9251:         }
 9252:     }
 9253:     my $origstart = $start;
 9254:     my $origend = $end;
 9255:     my $delflag;
 9256: # actually delete
 9257:     if ($deleteflag) {
 9258: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9259: # modify command to delete the role
 9260:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9261:                 "$udom:$uname:$url".'_'."$mrole";
 9262: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9263: # set start and finish to negative values for userrolelog
 9264:            $start=-1;
 9265:            $end=-1;
 9266:            $delflag = 1;
 9267:         }
 9268:     }
 9269: # send command
 9270:     my $answer=&reply($command,&homeserver($uname,$udom));
 9271: # log new user role if status is ok
 9272:     if ($answer eq 'ok') {
 9273: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9274:         if (($role eq 'cc') || ($role eq 'in') ||
 9275:             ($role eq 'ep') || ($role eq 'ad') ||
 9276:             ($role eq 'ta') || ($role eq 'st') ||
 9277:             ($role=~/^cr/) || ($role eq 'gr') ||
 9278:             ($role eq 'co')) {
 9279: # for course roles, perform group memberships changes triggered by role change.
 9280:             unless ($role =~ /^gr/) {
 9281:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9282:                                                  $origstart,$selfenroll,$context);
 9283:             }
 9284:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9285:                            $selfenroll,$context);
 9286:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9287:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9288:                  ($role eq 'da')) {
 9289:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9290:                            $context);
 9291:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9292:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9293:                              $context); 
 9294:         }
 9295:         if ($role eq 'cc') {
 9296:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9297:         }
 9298:     }
 9299:     return $answer;
 9300: }
 9301: 
 9302: sub autoupdate_coowners {
 9303:     my ($url,$end,$start,$uname,$udom) = @_;
 9304:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9305:     if (($cdom ne '') && ($cnum ne '')) {
 9306:         my $now = time;
 9307:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9308:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9309:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9310:             my $instcode = $coursehash{'internal.coursecode'};
 9311:             if ($instcode ne '') {
 9312:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9313:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9314:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9315:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9316:                         if ($result eq 'valid') {
 9317:                             if ($coursehash{'internal.co-owners'}) {
 9318:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9319:                                     push(@newcoowners,$coowner);
 9320:                                 }
 9321:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9322:                                     push(@newcoowners,$uname.':'.$udom);
 9323:                                 }
 9324:                                 @newcoowners = sort(@newcoowners);
 9325:                             } else {
 9326:                                 push(@newcoowners,$uname.':'.$udom);
 9327:                             }
 9328:                         } else {
 9329:                             if ($coursehash{'internal.co-owners'}) {
 9330:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9331:                                     unless ($coowner eq $uname.':'.$udom) {
 9332:                                         push(@newcoowners,$coowner);
 9333:                                     }
 9334:                                 }
 9335:                                 unless (@newcoowners > 0) {
 9336:                                     $delcoowners = 1;
 9337:                                     $coowners = '';
 9338:                                 }
 9339:                             }
 9340:                         }
 9341:                         if (@newcoowners || $delcoowners) {
 9342:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9343:                                             $delcoowners,@newcoowners);
 9344:                         }
 9345:                     }
 9346:                 }
 9347:             }
 9348:         }
 9349:     }
 9350: }
 9351: 
 9352: sub store_coowners {
 9353:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9354:     my $cid = $cdom.'_'.$cnum;
 9355:     my ($coowners,$delresult,$putresult);
 9356:     if (@newcoowners) {
 9357:         $coowners = join(',',@newcoowners);
 9358:         my %coownershash = (
 9359:                             'internal.co-owners' => $coowners,
 9360:                            );
 9361:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9362:         if ($putresult eq 'ok') {
 9363:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9364:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9365:             }
 9366:         }
 9367:     }
 9368:     if ($delcoowners) {
 9369:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9370:         if ($delresult eq 'ok') {
 9371:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9372:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9373:             }
 9374:         }
 9375:     }
 9376:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9377:         my %crsinfo =
 9378:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9379:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9380:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9381:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9382:         }
 9383:     }
 9384: }
 9385: 
 9386: # -------------------------------------------------- Modify user authentication
 9387: # Overrides without validation
 9388: 
 9389: sub modifyuserauth {
 9390:     my ($udom,$uname,$umode,$upass)=@_;
 9391:     my $uhome=&homeserver($uname,$udom);
 9392:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9393:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9394:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9395:              ' in domain '.$env{'request.role.domain'});  
 9396:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9397: 		     &escape($upass),$uhome);
 9398:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9399:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9400:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9401:     &log($udom,,$uname,$uhome,
 9402:         'Authentication changed by '.$env{'user.domain'}.', '.
 9403:                                      $env{'user.name'}.', '.$umode.
 9404:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9405:     unless ($reply eq 'ok') {
 9406:         &logthis('Authentication mode error: '.$reply);
 9407: 	return 'error: '.$reply;
 9408:     }   
 9409:     return 'ok';
 9410: }
 9411: 
 9412: # --------------------------------------------------------------- Modify a user
 9413: 
 9414: sub modifyuser {
 9415:     my ($udom,    $uname, $uid,
 9416:         $umode,   $upass, $first,
 9417:         $middle,  $last,  $gene,
 9418:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9419:     $udom= &LONCAPA::clean_domain($udom);
 9420:     $uname=&LONCAPA::clean_username($uname);
 9421:     my $showcandelete = 'none';
 9422:     if (ref($candelete) eq 'ARRAY') {
 9423:         if (@{$candelete} > 0) {
 9424:             $showcandelete = join(', ',@{$candelete});
 9425:         }
 9426:     }
 9427:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9428:              $umode.', '.$first.', '.$middle.', '.
 9429: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9430:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9431:                                      ' desiredhome not specified'). 
 9432:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9433:              ' in domain '.$env{'request.role.domain'});
 9434:     my $uhome=&homeserver($uname,$udom,'true');
 9435:     my $newuser;
 9436:     if ($uhome eq 'no_host') {
 9437:         $newuser = 1;
 9438:     }
 9439: # ----------------------------------------------------------------- Create User
 9440:     if (($uhome eq 'no_host') && 
 9441: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 9442:         my $unhome='';
 9443:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9444:             $unhome = $desiredhome;
 9445: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9446: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9447:         } else { # load balancing routine for determining $unhome
 9448:             my $loadm=10000000;
 9449: 	    my %servers = &get_servers($udom,'library');
 9450: 	    foreach my $tryserver (keys(%servers)) {
 9451: 		my $answer=reply('load',$tryserver);
 9452: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9453: 		    $loadm=$answer;
 9454: 		    $unhome=$tryserver;
 9455: 		}
 9456: 	    }
 9457:         }
 9458:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9459: 	    return 'error: unable to find a home server for '.$uname.
 9460:                    ' in domain '.$udom;
 9461:         }
 9462:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9463:                          &escape($upass),$unhome);
 9464: 	unless ($reply eq 'ok') {
 9465:             return 'error: '.$reply;
 9466:         }   
 9467:         $uhome=&homeserver($uname,$udom,'true');
 9468:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9469: 	    return 'error: unable verify users home machine.';
 9470:         }
 9471:     }   # End of creation of new user
 9472: # ---------------------------------------------------------------------- Add ID
 9473:     if ($uid) {
 9474:        $uid=~tr/A-Z/a-z/;
 9475:        my %uidhash=&idrget($udom,$uname);
 9476:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9477:          && (!$forceid)) {
 9478: 	  unless ($uid eq $uidhash{$uname}) {
 9479: 	      return 'error: user id "'.$uid.'" does not match '.
 9480:                   'current user id "'.$uidhash{$uname}.'".';
 9481:           }
 9482:        } else {
 9483: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9484:        }
 9485:     }
 9486: # -------------------------------------------------------------- Add names, etc
 9487:     my @tmp=&get('environment',
 9488: 		   ['firstname','middlename','lastname','generation','id',
 9489:                     'permanentemail','inststatus'],
 9490: 		   $udom,$uname);
 9491:     my (%names,%oldnames);
 9492:     if ($tmp[0] =~ m/^error:.*/) { 
 9493:         %names=(); 
 9494:     } else {
 9495:         %names = @tmp;
 9496:         %oldnames = %names;
 9497:     }
 9498: #
 9499: # If name, email and/or uid are blank (e.g., because an uploaded file
 9500: # of users did not contain them), do not overwrite existing values
 9501: # unless field is in $candelete array ref.  
 9502: #
 9503: 
 9504:     my @fields = ('firstname','middlename','lastname','generation',
 9505:                   'permanentemail','id');
 9506:     my %newvalues;
 9507:     if (ref($candelete) eq 'ARRAY') {
 9508:         foreach my $field (@fields) {
 9509:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9510:                 if ($field eq 'firstname') {
 9511:                     $names{$field} = $first;
 9512:                 } elsif ($field eq 'middlename') {
 9513:                     $names{$field} = $middle;
 9514:                 } elsif ($field eq 'lastname') {
 9515:                     $names{$field} = $last;
 9516:                 } elsif ($field eq 'generation') { 
 9517:                     $names{$field} = $gene;
 9518:                 } elsif ($field eq 'permanentemail') {
 9519:                     $names{$field} = $email;
 9520:                 } elsif ($field eq 'id') {
 9521:                     $names{$field}  = $uid;
 9522:                 }
 9523:             }
 9524:         }
 9525:     }
 9526:     if ($first)  { $names{'firstname'}  = $first; }
 9527:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9528:     if ($last)   { $names{'lastname'}   = $last; }
 9529:     if (defined($gene))   { $names{'generation'} = $gene; }
 9530:     if ($email) {
 9531:        $email=~s/[^\w\@\.\-\,]//gs;
 9532:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9533:     }
 9534:     if ($uid) { $names{'id'}  = $uid; }
 9535:     if (defined($inststatus)) {
 9536:         $names{'inststatus'} = '';
 9537:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9538:         if (ref($usertypes) eq 'HASH') {
 9539:             my @okstatuses; 
 9540:             foreach my $item (split(/:/,$inststatus)) {
 9541:                 if (defined($usertypes->{$item})) {
 9542:                     push(@okstatuses,$item);  
 9543:                 }
 9544:             }
 9545:             if (@okstatuses) {
 9546:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9547:             }
 9548:         }
 9549:     }
 9550:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9551:                  $umode.', '.$first.', '.$middle.', '.
 9552:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9553:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9554:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9555:     } else {
 9556:         $logmsg .= ' during self creation';
 9557:     }
 9558:     my $changed;
 9559:     if ($newuser) {
 9560:         $changed = 1;
 9561:     } else {
 9562:         foreach my $field (@fields) {
 9563:             if ($names{$field} ne $oldnames{$field}) {
 9564:                 $changed = 1;
 9565:                 last;
 9566:             }
 9567:         }
 9568:     }
 9569:     unless ($changed) {
 9570:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9571:         &logthis($logmsg);
 9572:         return 'ok';
 9573:     }
 9574:     my $reply = &put('environment', \%names, $udom,$uname);
 9575:     if ($reply ne 'ok') { 
 9576:         return 'error: '.$reply;
 9577:     }
 9578:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9579:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9580:     }
 9581:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9582:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9583:     $logmsg = 'Success modifying user '.$logmsg;
 9584:     &logthis($logmsg);
 9585:     return 'ok';
 9586: }
 9587: 
 9588: # -------------------------------------------------------------- Modify student
 9589: 
 9590: sub modifystudent {
 9591:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9592:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9593:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9594:     if (!$cid) {
 9595: 	unless ($cid=$env{'request.course.id'}) {
 9596: 	    return 'not_in_class';
 9597: 	}
 9598:     }
 9599: # --------------------------------------------------------------- Make the user
 9600:     my $reply=&modifyuser
 9601: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9602:          $desiredhome,$email,$inststatus);
 9603:     unless ($reply eq 'ok') { return $reply; }
 9604:     # This will cause &modify_student_enrollment to get the uid from the
 9605:     # student's environment
 9606:     $uid = undef if (!$forceid);
 9607:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9608:                                         $gene,$usec,$end,$start,$type,$locktype,
 9609:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9610:     return $reply;
 9611: }
 9612: 
 9613: sub modify_student_enrollment {
 9614:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9615:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9616:     my ($cdom,$cnum,$chome);
 9617:     if (!$cid) {
 9618: 	unless ($cid=$env{'request.course.id'}) {
 9619: 	    return 'not_in_class';
 9620: 	}
 9621: 	$cdom=$env{'course.'.$cid.'.domain'};
 9622: 	$cnum=$env{'course.'.$cid.'.num'};
 9623:     } else {
 9624: 	($cdom,$cnum)=split(/_/,$cid);
 9625:     }
 9626:     $chome=$env{'course.'.$cid.'.home'};
 9627:     if (!$chome) {
 9628: 	$chome=&homeserver($cnum,$cdom);
 9629:     }
 9630:     if (!$chome) { return 'unknown_course'; }
 9631:     # Make sure the user exists
 9632:     my $uhome=&homeserver($uname,$udom);
 9633:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9634: 	return 'error: no such user';
 9635:     }
 9636:     # Get student data if we were not given enough information
 9637:     if (!defined($first)  || $first  eq '' || 
 9638:         !defined($last)   || $last   eq '' || 
 9639:         !defined($uid)    || $uid    eq '' || 
 9640:         !defined($middle) || $middle eq '' || 
 9641:         !defined($gene)   || $gene   eq '') {
 9642:         # They did not supply us with enough data to enroll the student, so
 9643:         # we need to pick up more information.
 9644:         my %tmp = &get('environment',
 9645:                        ['firstname','middlename','lastname', 'generation','id']
 9646:                        ,$udom,$uname);
 9647: 
 9648:         #foreach my $key (keys(%tmp)) {
 9649:         #    &logthis("key $key = ".$tmp{$key});
 9650:         #}
 9651:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9652:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9653:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9654:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9655:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9656:     }
 9657:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9658:     my $user = "$uname:$udom";
 9659:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9660:     my $reply=cput('classlist',
 9661: 		   {$user => 
 9662: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9663: 		   $cdom,$cnum);
 9664:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9665:         &devalidate_getsection_cache($udom,$uname,$cid);
 9666:     } else { 
 9667: 	return 'error: '.$reply;
 9668:     }
 9669:     # Add student role to user
 9670:     my $uurl='/'.$cid;
 9671:     $uurl=~s/\_/\//g;
 9672:     if ($usec) {
 9673: 	$uurl.='/'.$usec;
 9674:     }
 9675:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9676:                              $selfenroll,$context);
 9677:     if ($result ne 'ok') {
 9678:         if ($old_entry{$user} ne '') {
 9679:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9680:         } else {
 9681:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9682:         }
 9683:     }
 9684:     return $result; 
 9685: }
 9686: 
 9687: sub format_name {
 9688:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9689:     my $name;
 9690:     if ($first ne 'lastname') {
 9691: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9692:     } else {
 9693: 	if ($lastname=~/\S/) {
 9694: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9695: 	    $name=~s/\s+,/,/;
 9696: 	} else {
 9697: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9698: 	}
 9699:     }
 9700:     $name=~s/^\s+//;
 9701:     $name=~s/\s+$//;
 9702:     $name=~s/\s+/ /g;
 9703:     return $name;
 9704: }
 9705: 
 9706: # ------------------------------------------------- Write to course preferences
 9707: 
 9708: sub writecoursepref {
 9709:     my ($courseid,%prefs)=@_;
 9710:     $courseid=~s/^\///;
 9711:     $courseid=~s/\_/\//g;
 9712:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9713:     my $chome=homeserver($cnum,$cdomain);
 9714:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9715: 	return 'error: no such course';
 9716:     }
 9717:     my $cstring='';
 9718:     foreach my $pref (keys(%prefs)) {
 9719: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9720:     }
 9721:     $cstring=~s/\&$//;
 9722:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9723: }
 9724: 
 9725: # ---------------------------------------------------------- Make/modify course
 9726: 
 9727: sub createcourse {
 9728:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9729:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9730:     $url=&declutter($url);
 9731:     my $cid='';
 9732:     if ($context eq 'requestcourses') {
 9733:         my $can_create = 0;
 9734:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9735:         if ($udom eq $ownerdom) {
 9736:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9737:                                   $context)) {
 9738:                 $can_create = 1;
 9739:             }
 9740:         } else {
 9741:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9742:                                            $category);
 9743:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9744:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9745:                 if (@curr > 0) {
 9746:                     my @options = qw(approval validate autolimit);
 9747:                     my $optregex = join('|',@options);
 9748:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9749:                         $can_create = 1;
 9750:                     }
 9751:                 }
 9752:             }
 9753:         }
 9754:         if ($can_create) {
 9755:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 9756:                 unless (&allowed('ccc',$udom)) {
 9757:                     return 'refused'; 
 9758:                 }
 9759:             }
 9760:         } else {
 9761:             return 'refused';
 9762:         }
 9763:     } elsif (!&allowed('ccc',$udom)) {
 9764:         return 'refused';
 9765:     }
 9766: # --------------------------------------------------------------- Get Unique ID
 9767:     my $uname;
 9768:     if ($cnum =~ /^$match_courseid$/) {
 9769:         my $chome=&homeserver($cnum,$udom,'true');
 9770:         if (($chome eq '') || ($chome eq 'no_host')) {
 9771:             $uname = $cnum;
 9772:         } else {
 9773:             $uname = &generate_coursenum($udom,$crstype);
 9774:         }
 9775:     } else {
 9776:         $uname = &generate_coursenum($udom,$crstype);
 9777:     }
 9778:     return $uname if ($uname =~ /^error/);
 9779: # -------------------------------------------------- Check supplied server name
 9780:     if (!defined($course_server)) {
 9781:         if (defined(&domain($udom,'primary'))) {
 9782:             $course_server = &domain($udom,'primary');
 9783:         } else {
 9784:             $course_server = $env{'user.home'}; 
 9785:         }
 9786:     }
 9787:     my %host_servers =
 9788:         &Apache::lonnet::get_servers($udom,'library');
 9789:     unless ($host_servers{$course_server}) {
 9790:         return 'error: invalid home server for course: '.$course_server;
 9791:     }
 9792: # ------------------------------------------------------------- Make the course
 9793:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 9794:                       $course_server);
 9795:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 9796:     my $uhome=&homeserver($uname,$udom,'true');
 9797:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9798: 	return 'error: no such course';
 9799:     }
 9800: # ----------------------------------------------------------------- Course made
 9801: # log existence
 9802:     my $now = time;
 9803:     my $newcourse = {
 9804:                     $udom.'_'.$uname => {
 9805:                                      description => $description,
 9806:                                      inst_code   => $inst_code,
 9807:                                      owner       => $course_owner,
 9808:                                      type        => $crstype,
 9809:                                      creator     => $env{'user.name'}.':'.
 9810:                                                     $env{'user.domain'},
 9811:                                      created     => $now,
 9812:                                      context     => $context,
 9813:                                                 },
 9814:                     };
 9815:     &courseidput($udom,$newcourse,$uhome,'notime');
 9816: # set toplevel url
 9817:     my $topurl=$url;
 9818:     unless ($nonstandard) {
 9819: # ------------------------------------------ For standard courses, make top url
 9820:         my $mapurl=&clutter($url);
 9821:         if ($mapurl eq '/res/') { $mapurl=''; }
 9822:         $env{'form.initmap'}=(<<ENDINITMAP);
 9823: <map>
 9824: <resource id="1" type="start"></resource>
 9825: <resource id="2" src="$mapurl"></resource>
 9826: <resource id="3" type="finish"></resource>
 9827: <link index="1" from="1" to="2"></link>
 9828: <link index="2" from="2" to="3"></link>
 9829: </map>
 9830: ENDINITMAP
 9831:         $topurl=&declutter(
 9832:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 9833:                           );
 9834:     }
 9835: # ----------------------------------------------------------- Write preferences
 9836:     &writecoursepref($udom.'_'.$uname,
 9837:                      ('description'              => $description,
 9838:                       'url'                      => $topurl,
 9839:                       'internal.creator'         => $env{'user.name'}.':'.
 9840:                                                     $env{'user.domain'},
 9841:                       'internal.created'         => $now,
 9842:                       'internal.creationcontext' => $context)
 9843:                     );
 9844:     return '/'.$udom.'/'.$uname;
 9845: }
 9846: 
 9847: # ------------------------------------------------------------------- Create ID
 9848: sub generate_coursenum {
 9849:     my ($udom,$crstype) = @_;
 9850:     my $domdesc = &domain($udom);
 9851:     return 'error: invalid domain' if ($domdesc eq '');
 9852:     my $first;
 9853:     if ($crstype eq 'Community') {
 9854:         $first = '0';
 9855:     } else {
 9856:         $first = int(1+rand(9)); 
 9857:     } 
 9858:     my $uname=$first.
 9859:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9860:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9861:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9862: # ----------------------------------------------- Make sure that does not exist
 9863:     my $uhome=&homeserver($uname,$udom,'true');
 9864:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9865:         if ($crstype eq 'Community') {
 9866:             $first = '0';
 9867:         } else {
 9868:             $first = int(1+rand(9));
 9869:         }
 9870:         $uname=$first.
 9871:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9872:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9873:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9874:         $uhome=&homeserver($uname,$udom,'true');
 9875:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9876:             return 'error: unable to generate unique course-ID';
 9877:         }
 9878:     }
 9879:     return $uname;
 9880: }
 9881: 
 9882: sub is_course {
 9883:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 9884:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 9885: 
 9886:     return unless $cdom and $cnum;
 9887: 
 9888:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 9889:         '.');
 9890: 
 9891:     return unless(exists($courses{$cdom.'_'.$cnum}));
 9892:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 9893: }
 9894: 
 9895: sub store_userdata {
 9896:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 9897:     my $result;
 9898:     if ($datakey ne '') {
 9899:         if (ref($storehash) eq 'HASH') {
 9900:             if ($udom eq '' || $uname eq '') {
 9901:                 $udom = $env{'user.domain'};
 9902:                 $uname = $env{'user.name'};
 9903:             }
 9904:             my $uhome=&homeserver($uname,$udom);
 9905:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 9906:                 $result = 'error: no_host';
 9907:             } else {
 9908:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 9909:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 9910: 
 9911:                 my $namevalue='';
 9912:                 foreach my $key (keys(%{$storehash})) {
 9913:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 9914:                 }
 9915:                 $namevalue=~s/\&$//;
 9916:                 unless ($namespace eq 'courserequests') {
 9917:                     $datakey = &escape($datakey);
 9918:                 }
 9919:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 9920:                                   $namevalue,$uhome);
 9921:             }
 9922:         } else {
 9923:             $result = 'error: data to store was not a hash reference'; 
 9924:         }
 9925:     } else {
 9926:         $result= 'error: invalid requestkey'; 
 9927:     }
 9928:     return $result;
 9929: }
 9930: 
 9931: # ---------------------------------------------------------- Assign Custom Role
 9932: 
 9933: sub assigncustomrole {
 9934:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 9935:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 9936:                        $end,$start,$deleteflag,$selfenroll,$context);
 9937: }
 9938: 
 9939: # ----------------------------------------------------------------- Revoke Role
 9940: 
 9941: sub revokerole {
 9942:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 9943:     my $now=time;
 9944:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 9945: }
 9946: 
 9947: # ---------------------------------------------------------- Revoke Custom Role
 9948: 
 9949: sub revokecustomrole {
 9950:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 9951:     my $now=time;
 9952:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 9953:            $deleteflag,$selfenroll,$context);
 9954: }
 9955: 
 9956: # ------------------------------------------------------------ Disk usage
 9957: sub diskusage {
 9958:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 9959:     $directorypath =~ s/\/$//;
 9960:     my $listing=&reply('du2:'.&escape($directorypath).':'
 9961:                        .&escape($getpropath).':'.&escape($uname).':'
 9962:                        .&escape($udom),homeserver($uname,$udom));
 9963:     if ($listing eq 'unknown_cmd') {
 9964:         if ($getpropath) {
 9965:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 9966:         }
 9967:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 9968:     }
 9969:     return $listing;
 9970: }
 9971: 
 9972: sub is_locked {
 9973:     my ($file_name, $domain, $user, $which) = @_;
 9974:     my @check;
 9975:     my $is_locked;
 9976:     push (@check,$file_name);
 9977:     my %locked = &get('file_permissions',\@check,
 9978: 		      $env{'user.domain'},$env{'user.name'});
 9979:     my ($tmp)=keys(%locked);
 9980:     if ($tmp=~/^error:/) { undef(%locked); }
 9981:     
 9982:     if (ref($locked{$file_name}) eq 'ARRAY') {
 9983:         $is_locked = 'false';
 9984:         foreach my $entry (@{$locked{$file_name}}) {
 9985:            if (ref($entry) eq 'ARRAY') {
 9986:                $is_locked = 'true';
 9987:                if (ref($which) eq 'ARRAY') {
 9988:                    push(@{$which},$entry);
 9989:                } else {
 9990:                    last;
 9991:                }
 9992:            }
 9993:        }
 9994:     } else {
 9995:         $is_locked = 'false';
 9996:     }
 9997:     return $is_locked;
 9998: }
 9999: 
10000: sub declutter_portfile {
10001:     my ($file) = @_;
10002:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10003:     return $file;
10004: }
10005: 
10006: # ------------------------------------------------------------- Mark as Read Only
10007: 
10008: sub mark_as_readonly {
10009:     my ($domain,$user,$files,$what) = @_;
10010:     my %current_permissions = &dump('file_permissions',$domain,$user);
10011:     my ($tmp)=keys(%current_permissions);
10012:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10013:     foreach my $file (@{$files}) {
10014: 	$file = &declutter_portfile($file);
10015:         push(@{$current_permissions{$file}},$what);
10016:     }
10017:     &put('file_permissions',\%current_permissions,$domain,$user);
10018:     return;
10019: }
10020: 
10021: # ------------------------------------------------------------Save Selected Files
10022: 
10023: sub save_selected_files {
10024:     my ($user, $path, @files) = @_;
10025:     my $filename = $user."savedfiles";
10026:     my @other_files = &files_not_in_path($user, $path);
10027:     open (OUT, '>'.$tmpdir.$filename);
10028:     foreach my $file (@files) {
10029:         print (OUT $env{'form.currentpath'}.$file."\n");
10030:     }
10031:     foreach my $file (@other_files) {
10032:         print (OUT $file."\n");
10033:     }
10034:     close (OUT);
10035:     return 'ok';
10036: }
10037: 
10038: sub clear_selected_files {
10039:     my ($user) = @_;
10040:     my $filename = $user."savedfiles";
10041:     open (OUT, '>'.LONCAPA::tempdir().$filename);
10042:     print (OUT undef);
10043:     close (OUT);
10044:     return ("ok");    
10045: }
10046: 
10047: sub files_in_path {
10048:     my ($user, $path) = @_;
10049:     my $filename = $user."savedfiles";
10050:     my %return_files;
10051:     open (IN, '<'.LONCAPA::tempdir().$filename);
10052:     while (my $line_in = <IN>) {
10053:         chomp ($line_in);
10054:         my @paths_and_file = split (m!/!, $line_in);
10055:         my $file_part = pop (@paths_and_file);
10056:         my $path_part = join ('/', @paths_and_file);
10057:         $path_part.='/';
10058:         my $path_and_file = $path_part.$file_part;
10059:         if ($path_part eq $path) {
10060:             $return_files{$file_part}= 'selected';
10061:         }
10062:     }
10063:     close (IN);
10064:     return (\%return_files);
10065: }
10066: 
10067: # called in portfolio select mode, to show files selected NOT in current directory
10068: sub files_not_in_path {
10069:     my ($user, $path) = @_;
10070:     my $filename = $user."savedfiles";
10071:     my @return_files;
10072:     my $path_part;
10073:     open(IN, '<'.LONCAPA::.$filename);
10074:     while (my $line = <IN>) {
10075:         #ok, I know it's clunky, but I want it to work
10076:         my @paths_and_file = split(m|/|, $line);
10077:         my $file_part = pop(@paths_and_file);
10078:         chomp($file_part);
10079:         my $path_part = join('/', @paths_and_file);
10080:         $path_part .= '/';
10081:         my $path_and_file = $path_part.$file_part;
10082:         if ($path_part ne $path) {
10083:             push(@return_files, ($path_and_file));
10084:         }
10085:     }
10086:     close(OUT);
10087:     return (@return_files);
10088: }
10089: 
10090: #------------------------------Submitted/Handedback Portfolio Files Versioning
10091:  
10092: sub portfiles_versioning {
10093:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10094:     my $portfolio_root = '/userfiles/portfolio';
10095:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10096:     foreach my $file (@{$portfiles}) {
10097:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10098:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10099:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10100:         my $getpropath = 1;
10101:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10102:                                              $stu_name,$getpropath);
10103:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10104:         my $new_answer = 
10105:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10106:         if ($new_answer ne 'problem getting file') {
10107:             push(@{$versioned_portfiles}, $directory.$new_answer);
10108:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10109:                               [$symb,$env{'request.course.id'},'graded']);
10110:         }
10111:     }
10112: }
10113: 
10114: sub get_next_version {
10115:     my ($answer_name, $answer_ext, $dir_list) = @_;
10116:     my $version;
10117:     if (ref($dir_list) eq 'ARRAY') {
10118:         foreach my $row (@{$dir_list}) {
10119:             my ($file) = split(/\&/,$row,2);
10120:             my ($file_name,$file_version,$file_ext) =
10121:                 &file_name_version_ext($file);
10122:             if (($file_name eq $answer_name) &&
10123:                 ($file_ext eq $answer_ext)) {
10124:                      # gets here if filename and extension match,
10125:                      # regardless of version
10126:                 if ($file_version ne '') {
10127:                     # a versioned file is found  so save it for later
10128:                     if ($file_version > $version) {
10129:                         $version = $file_version;
10130:                     }
10131:                 }
10132:             }
10133:         }
10134:     }
10135:     $version ++;
10136:     return($version);
10137: }
10138: 
10139: sub version_selected_portfile {
10140:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10141:     my ($answer_name,$answer_ver,$answer_ext) =
10142:         &file_name_version_ext($file_name);
10143:     my $new_answer;
10144:     $env{'form.copy'} =
10145:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10146:     if($env{'form.copy'} eq '-1') {
10147:         $new_answer = 'problem getting file';
10148:     } else {
10149:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10150:         my $copy_result = 
10151:             &finishuserfileupload($stu_name,$domain,'copy',
10152:                                   '/portfolio'.$directory.$new_answer);
10153:     }
10154:     undef($env{'form.copy'});
10155:     return ($new_answer);
10156: }
10157: 
10158: sub file_name_version_ext {
10159:     my ($file)=@_;
10160:     my @file_parts = split(/\./, $file);
10161:     my ($name,$version,$ext);
10162:     if (@file_parts > 1) {
10163:         $ext=pop(@file_parts);
10164:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10165:             $version=pop(@file_parts);
10166:         }
10167:         $name=join('.',@file_parts);
10168:     } else {
10169:         $name=join('.',@file_parts);
10170:     }
10171:     return($name,$version,$ext);
10172: }
10173: 
10174: #----------------------------------------------Get portfolio file permissions
10175: 
10176: sub get_portfile_permissions {
10177:     my ($domain,$user) = @_;
10178:     my %current_permissions = &dump('file_permissions',$domain,$user);
10179:     my ($tmp)=keys(%current_permissions);
10180:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10181:     return \%current_permissions;
10182: }
10183: 
10184: #---------------------------------------------Get portfolio file access controls
10185: 
10186: sub get_access_controls {
10187:     my ($current_permissions,$group,$file) = @_;
10188:     my %access;
10189:     my $real_file = $file;
10190:     $file =~ s/\.meta$//;
10191:     if (defined($file)) {
10192:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10193:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10194:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10195:             }
10196:         }
10197:     } else {
10198:         foreach my $key (keys(%{$current_permissions})) {
10199:             if ($key =~ /\0accesscontrol$/) {
10200:                 if (defined($group)) {
10201:                     if ($key !~ m-^\Q$group\E/-) {
10202:                         next;
10203:                     }
10204:                 }
10205:                 my ($fullpath) = split(/\0/,$key);
10206:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10207:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10208:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10209:                     }
10210:                 }
10211:             }
10212:         }
10213:     }
10214:     return %access;
10215: }
10216: 
10217: sub modify_access_controls {
10218:     my ($file_name,$changes,$domain,$user)=@_;
10219:     my ($outcome,$deloutcome);
10220:     my %store_permissions;
10221:     my %new_values;
10222:     my %new_control;
10223:     my %translation;
10224:     my @deletions = ();
10225:     my $now = time;
10226:     if (exists($$changes{'activate'})) {
10227:         if (ref($$changes{'activate'}) eq 'HASH') {
10228:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10229:             my $numnew = scalar(@newitems);
10230:             for (my $i=0; $i<$numnew; $i++) {
10231:                 my $newkey = $newitems[$i];
10232:                 my $newid = &Apache::loncommon::get_cgi_id();
10233:                 if ($newkey =~ /^\d+:/) { 
10234:                     $newkey =~ s/^(\d+)/$newid/;
10235:                     $translation{$1} = $newid;
10236:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10237:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10238:                     $translation{$1} = $newid;
10239:                 }
10240:                 $new_values{$file_name."\0".$newkey} = 
10241:                                           $$changes{'activate'}{$newitems[$i]};
10242:                 $new_control{$newkey} = $now;
10243:             }
10244:         }
10245:     }
10246:     my %todelete;
10247:     my %changed_items;
10248:     foreach my $action ('delete','update') {
10249:         if (exists($$changes{$action})) {
10250:             if (ref($$changes{$action}) eq 'HASH') {
10251:                 foreach my $key (keys(%{$$changes{$action}})) {
10252:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10253:                     if ($action eq 'delete') { 
10254:                         $todelete{$itemnum} = 1;
10255:                     } else {
10256:                         $changed_items{$itemnum} = $key;
10257:                     }
10258:                 }
10259:             }
10260:         }
10261:     }
10262:     # get lock on access controls for file.
10263:     my $lockhash = {
10264:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10265:                                                        ':'.$env{'user.domain'},
10266:                    }; 
10267:     my $tries = 0;
10268:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10269:    
10270:     while (($gotlock ne 'ok') && $tries < 10) {
10271:         $tries ++;
10272:         sleep(0.1);
10273:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10274:     }
10275:     if ($gotlock eq 'ok') {
10276:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10277:         my ($tmp)=keys(%curr_permissions);
10278:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10279:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10280:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10281:             if (ref($curr_controls) eq 'HASH') {
10282:                 foreach my $control_item (keys(%{$curr_controls})) {
10283:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10284:                     if (defined($todelete{$itemnum})) {
10285:                         push(@deletions,$file_name."\0".$control_item);
10286:                     } else {
10287:                         if (defined($changed_items{$itemnum})) {
10288:                             $new_control{$changed_items{$itemnum}} = $now;
10289:                             push(@deletions,$file_name."\0".$control_item);
10290:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10291:                         } else {
10292:                             $new_control{$control_item} = $$curr_controls{$control_item};
10293:                         }
10294:                     }
10295:                 }
10296:             }
10297:         }
10298:         my ($group);
10299:         if (&is_course($domain,$user)) {
10300:             ($group,my $file) = split(/\//,$file_name,2);
10301:         }
10302:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10303:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10304:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10305:         #  remove lock
10306:         my @del_lock = ($file_name."\0".'locked_access_records');
10307:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10308:         my $sqlresult =
10309:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10310:                                     $group);
10311:     } else {
10312:         $outcome = "error: could not obtain lockfile\n";  
10313:     }
10314:     return ($outcome,$deloutcome,\%new_values,\%translation);
10315: }
10316: 
10317: sub make_public_indefinitely {
10318:     my (@requrl) = @_;
10319:     return &automated_portfile_access('public',\@requrl);
10320: }
10321: 
10322: sub automated_portfile_access {
10323:     my ($accesstype,$addsref,$delsref,$info) = @_;
10324:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10325:         return 'invalid';
10326:     }
10327:     my %urls;
10328:     if (ref($addsref) eq 'ARRAY') {
10329:         foreach my $requrl (@{$addsref}) {
10330:             if (&is_portfolio_url($requrl)) {
10331:                 unless (exists($urls{$requrl})) {
10332:                     $urls{$requrl} = 'add';
10333:                 }
10334:             }
10335:         }
10336:     }
10337:     if (ref($delsref) eq 'ARRAY') {
10338:         foreach my $requrl (@{$delsref}) { 
10339:             if (&is_portfolio_url($requrl)) {
10340:                 unless (exists($urls{$requrl})) {
10341:                     $urls{$requrl} = 'delete'; 
10342:                 }
10343:             }
10344:         }
10345:     }
10346:     unless (keys(%urls)) {
10347:         return 'invalid';
10348:     }
10349:     my $ip;
10350:     if ($accesstype eq 'ip') {
10351:         if (ref($info) eq 'HASH') {
10352:             if ($info->{'ip'} ne '') {
10353:                 $ip = $info->{'ip'};
10354:             }
10355:         }
10356:         if ($ip eq '') {
10357:             return 'invalid';
10358:         }
10359:     }
10360:     my $errors;
10361:     my $now = time;
10362:     my %current_perms;
10363:     foreach my $requrl (sort(keys(%urls))) {
10364:         my $action;
10365:         if ($urls{$requrl} eq 'add') {
10366:             $action = 'activate';
10367:         } else {
10368:             $action = 'none';
10369:         }
10370:         my $aclnum = 0;
10371:         my (undef,$udom,$unum,$file_name,$group) =
10372:             &parse_portfolio_url($requrl);
10373:         unless (exists($current_perms{$unum.':'.$udom})) {
10374:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10375:         }
10376:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10377:                                                    $group,$file_name);
10378:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10379:             my ($num,$scope,$end,$start) = 
10380:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10381:             if ($scope eq $accesstype) {
10382:                 if (($start <= $now) && ($end == 0)) {
10383:                     if ($accesstype eq 'ip') {
10384:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10385:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10386:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10387:                                     if ($urls{$requrl} eq 'add') {
10388:                                         $action = 'none';
10389:                                         last;
10390:                                     } else {
10391:                                         $action = 'delete';
10392:                                         $aclnum = $num;
10393:                                         last;
10394:                                     }
10395:                                 }
10396:                             }
10397:                         }
10398:                     } elsif ($accesstype eq 'public') {
10399:                         if ($urls{$requrl} eq 'add') {
10400:                             $action = 'none';
10401:                             last;
10402:                         } else {
10403:                             $action = 'delete';
10404:                             $aclnum = $num;
10405:                             last;
10406:                         }
10407:                     }
10408:                 } elsif ($accesstype eq 'public') {
10409:                     $action = 'update';
10410:                     $aclnum = $num;
10411:                     last;
10412:                 }
10413:             }
10414:         }
10415:         if ($action eq 'none') {
10416:             next;
10417:         } else {
10418:             my %changes;
10419:             my $newend = 0;
10420:             my $newstart = $now;
10421:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10422:             $changes{$action}{$newkey} = {
10423:                 type => $accesstype,
10424:                 time => {
10425:                     start => $newstart,
10426:                     end   => $newend,
10427:                 },
10428:             };
10429:             if ($accesstype eq 'ip') {
10430:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10431:             }
10432:             my ($outcome,$deloutcome,$new_values,$translation) =
10433:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10434:             unless ($outcome eq 'ok') {
10435:                 $errors .= $outcome.' ';
10436:             }
10437:         }
10438:     }
10439:     if ($errors) {
10440:         $errors =~ s/\s$//;
10441:         return $errors;
10442:     } else {
10443:         return 'ok';
10444:     }
10445: }
10446: 
10447: #------------------------------------------------------Get Marked as Read Only
10448: 
10449: sub get_marked_as_readonly {
10450:     my ($domain,$user,$what,$group) = @_;
10451:     my $current_permissions = &get_portfile_permissions($domain,$user);
10452:     my @readonly_files;
10453:     my $cmp1=$what;
10454:     if (ref($what)) { $cmp1=join('',@{$what}) };
10455:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10456:         if (defined($group)) {
10457:             if ($file_name !~ m-^\Q$group\E/-) {
10458:                 next;
10459:             }
10460:         }
10461:         if (ref($value) eq "ARRAY"){
10462:             foreach my $stored_what (@{$value}) {
10463:                 my $cmp2=$stored_what;
10464:                 if (ref($stored_what) eq 'ARRAY') {
10465:                     $cmp2=join('',@{$stored_what});
10466:                 }
10467:                 if ($cmp1 eq $cmp2) {
10468:                     push(@readonly_files, $file_name);
10469:                     last;
10470:                 } elsif (!defined($what)) {
10471:                     push(@readonly_files, $file_name);
10472:                     last;
10473:                 }
10474:             }
10475:         }
10476:     }
10477:     return @readonly_files;
10478: }
10479: #-----------------------------------------------------------Get Marked as Read Only Hash
10480: 
10481: sub get_marked_as_readonly_hash {
10482:     my ($current_permissions,$group,$what) = @_;
10483:     my %readonly_files;
10484:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10485:         if (defined($group)) {
10486:             if ($file_name !~ m-^\Q$group\E/-) {
10487:                 next;
10488:             }
10489:         }
10490:         if (ref($value) eq "ARRAY"){
10491:             foreach my $stored_what (@{$value}) {
10492:                 if (ref($stored_what) eq 'ARRAY') {
10493:                     foreach my $lock_descriptor(@{$stored_what}) {
10494:                         if ($lock_descriptor eq 'graded') {
10495:                             $readonly_files{$file_name} = 'graded';
10496:                         } elsif ($lock_descriptor eq 'handback') {
10497:                             $readonly_files{$file_name} = 'handback';
10498:                         } else {
10499:                             if (!exists($readonly_files{$file_name})) {
10500:                                 $readonly_files{$file_name} = 'locked';
10501:                             }
10502:                         }
10503:                     }
10504:                 } 
10505:             }
10506:         } 
10507:     }
10508:     return %readonly_files;
10509: }
10510: # ------------------------------------------------------------ Unmark as Read Only
10511: 
10512: sub unmark_as_readonly {
10513:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10514:     # for portfolio submissions, $what contains [$symb,$crsid] 
10515:     my ($domain,$user,$what,$file_name,$group) = @_;
10516:     $file_name = &declutter_portfile($file_name);
10517:     my $symb_crs = $what;
10518:     if (ref($what)) { $symb_crs=join('',@$what); }
10519:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10520:     my ($tmp)=keys(%current_permissions);
10521:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10522:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10523:     foreach my $file (@readonly_files) {
10524: 	my $clean_file = &declutter_portfile($file);
10525: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10526: 	my $current_locks = $current_permissions{$file};
10527:         my @new_locks;
10528:         my @del_keys;
10529:         if (ref($current_locks) eq "ARRAY"){
10530:             foreach my $locker (@{$current_locks}) {
10531:                 my $compare=$locker;
10532:                 if (ref($locker) eq 'ARRAY') {
10533:                     $compare=join('',@{$locker});
10534:                     if ($compare ne $symb_crs) {
10535:                         push(@new_locks, $locker);
10536:                     }
10537:                 }
10538:             }
10539:             if (scalar(@new_locks) > 0) {
10540:                 $current_permissions{$file} = \@new_locks;
10541:             } else {
10542:                 push(@del_keys, $file);
10543:                 &del('file_permissions',\@del_keys, $domain, $user);
10544:                 delete($current_permissions{$file});
10545:             }
10546:         }
10547:     }
10548:     &put('file_permissions',\%current_permissions,$domain,$user);
10549:     return;
10550: }
10551: 
10552: # ------------------------------------------------------------ Directory lister
10553: 
10554: sub dirlist {
10555:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10556:     $uri=~s/^\///;
10557:     $uri=~s/\/$//;
10558:     my ($udom, $uname);
10559:     if ($getuserdir) {
10560:         $udom = $userdomain;
10561:         $uname = $username;
10562:     } else {
10563:         (undef,$udom,$uname)=split(/\//,$uri);
10564:         if(defined($userdomain)) {
10565:             $udom = $userdomain;
10566:         }
10567:         if(defined($username)) {
10568:             $uname = $username;
10569:         }
10570:     }
10571:     my ($dirRoot,$listing,@listing_results);
10572: 
10573:     $dirRoot = $perlvar{'lonDocRoot'};
10574:     if (defined($getpropath)) {
10575:         $dirRoot = &propath($udom,$uname);
10576:         $dirRoot =~ s/\/$//;
10577:     } elsif (defined($getuserdir)) {
10578:         my $subdir=$uname.'__';
10579:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10580:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10581:                    ."/$udom/$subdir/$uname";
10582:     } elsif (defined($alternateRoot)) {
10583:         $dirRoot = $alternateRoot;
10584:     }
10585: 
10586:     if($udom) {
10587:         if($uname) {
10588:             my $uhome = &homeserver($uname,$udom);
10589:             if ($uhome eq 'no_host') {
10590:                 return ([],'no_host');
10591:             }
10592:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10593:                               .$getuserdir.':'.&escape($dirRoot)
10594:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10595:             if ($listing eq 'unknown_cmd') {
10596:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10597:             } else {
10598:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10599:             }
10600:             if ($listing eq 'unknown_cmd') {
10601:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10602:                 @listing_results = split(/:/,$listing);
10603:             } else {
10604:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10605:             }
10606:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10607:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10608:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10609:                 return ([],$listing);
10610:             } else {
10611:                 return (\@listing_results);
10612:             }
10613:         } elsif(!$alternateRoot) {
10614:             my (%allusers,%listerror);
10615: 	    my %servers = &get_servers($udom,'library');
10616:  	    foreach my $tryserver (keys(%servers)) {
10617:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10618:                                   &escape($udom),$tryserver);
10619:                 if ($listing eq 'unknown_cmd') {
10620: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10621: 				      $udom, $tryserver);
10622:                 } else {
10623:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10624:                 }
10625: 		if ($listing eq 'unknown_cmd') {
10626: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10627: 				      $udom, $tryserver);
10628: 		    @listing_results = split(/:/,$listing);
10629: 		} else {
10630: 		    @listing_results =
10631: 			map { &unescape($_); } split(/:/,$listing);
10632: 		}
10633:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10634:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10635:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10636:                     $listerror{$tryserver} = $listing;
10637:                 } else {
10638: 		    foreach my $line (@listing_results) {
10639: 			my ($entry) = split(/&/,$line,2);
10640: 			$allusers{$entry} = 1;
10641: 		    }
10642: 		}
10643:             }
10644:             my @alluserslist=();
10645:             foreach my $user (sort(keys(%allusers))) {
10646:                 push(@alluserslist,$user.'&user');
10647:             }
10648: 
10649:             if (!%listerror) {
10650:                 # no errors
10651:                 return (\@alluserslist);
10652:             } elsif (scalar(keys(%servers)) == 1) {
10653:                 # one library server, one error 
10654:                 my ($key) = keys(%listerror);
10655:                 return (\@alluserslist, $listerror{$key});
10656:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10657:                 # con_lost indicates that we might miss data from at least one
10658:                 # library server
10659:                 return (\@alluserslist, 'con_lost');
10660:             } else {
10661:                 # multiple library servers and no con_lost -> data should be
10662:                 # complete. 
10663:                 return (\@alluserslist);
10664:             }
10665: 
10666:         } else {
10667:             return ([],'missing username');
10668:         }
10669:     } elsif(!defined($getpropath)) {
10670:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10671:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10672:         return (\@all_domains);
10673:     } else {
10674:         return ([],'missing domain');
10675:     }
10676: }
10677: 
10678: # --------------------------------------------- GetFileTimestamp
10679: # This function utilizes dirlist and returns the date stamp for
10680: # when it was last modified.  It will also return an error of -1
10681: # if an error occurs
10682: 
10683: sub GetFileTimestamp {
10684:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10685:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10686:     $studentName   = &LONCAPA::clean_username($studentName);
10687:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10688:                                     undef,$getuserdir);
10689:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10690:         return -1;
10691:     }
10692:     if (ref($fileref) eq 'ARRAY') {
10693:         my @stats = split('&',$fileref->[0]);
10694:         # @stats contains first the filename, then the stat output
10695:         return $stats[10]; # so this is 10 instead of 9.
10696:     } else {
10697:         return -1;
10698:     }
10699: }
10700: 
10701: sub stat_file {
10702:     my ($uri) = @_;
10703:     $uri = &clutter_with_no_wrapper($uri);
10704: 
10705:     my ($udom,$uname,$file);
10706:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10707: 	($udom,$uname,$file) =
10708: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10709: 	$file = 'userfiles/'.$file;
10710:     }
10711:     if ($uri =~ m-^/res/-) {
10712: 	($udom,$uname) = 
10713: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10714: 	$file = $uri;
10715:     }
10716: 
10717:     if (!$udom || !$uname || !$file) {
10718: 	# unable to handle the uri
10719: 	return ();
10720:     }
10721:     my $getpropath;
10722:     if ($file =~ /^userfiles\//) {
10723:         $getpropath = 1;
10724:     }
10725:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10726:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10727:         return ();
10728:     } else {
10729:         if (ref($listref) eq 'ARRAY') {
10730:             my @stats = split('&',$listref->[0]);
10731: 	    shift(@stats); #filename is first
10732: 	    return @stats;
10733:         }
10734:     }
10735:     return ();
10736: }
10737: 
10738: # --------------------------------------------------------- recursedirs
10739: # Recursive function to traverse either a specific user's Authoring Space
10740: # or corresponding Published Resource Space, and populate the hash ref:
10741: # $dirhashref with URLs of all directories, and if $filehashref hash
10742: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10743: # or .rights files in resource space, and .meta, .save, .log, and .bak
10744: # files in Authoring Space.
10745: #
10746: # Inputs:
10747: #
10748: # $is_home - true if current server is home server for user's space
10749: # $context - either: priv, or res respectively for Authoring or Resource Space.
10750: # $docroot - Document root (i.e., /home/httpd/html
10751: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10752: # $relpath - Current path (relative to top level).
10753: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10754: # $filehashref - reference to hash to populate with URLs of files (Optional)
10755: #
10756: # Returns: nothing
10757: #
10758: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10759: #
10760: # Currently used by interface/londocs.pm to create linked select boxes for
10761: # directory and filename to import a Course "Author" resource into a course, and
10762: # also to create linked select boxes for Authoring Space and Directory to choose
10763: # save location for creation of a new "standard" problem from the Course Editor.
10764: #
10765: 
10766: sub recursedirs {
10767:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10768:     return unless (ref($dirhashref) eq 'HASH');
10769:     my $currpath = $docroot.$toppath;
10770:     if ($relpath) {
10771:         $currpath .= "/$relpath";
10772:     }
10773:     my $savefile;
10774:     if (ref($filehashref)) {
10775:         $savefile = 1;
10776:     }
10777:     if ($is_home) {
10778:         if (opendir(my $dirh,$currpath)) {
10779:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10780:                 next if ($item eq '');
10781:                 if (-d "$currpath/$item") {
10782:                     my $newpath;
10783:                     if ($relpath) {
10784:                         $newpath = "$relpath/$item";
10785:                     } else {
10786:                         $newpath = $item;
10787:                     }
10788:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10789:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10790:                 } elsif ($savefile) {
10791:                     if ($context eq 'priv') {
10792:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10793:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10794:                         }
10795:                     } else {
10796:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10797:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10798:                         }
10799:                     }
10800:                 }
10801:             }
10802:             closedir($dirh);
10803:         }
10804:     } else {
10805:         my ($dirlistref,$listerror) =
10806:             &dirlist($toppath.$relpath);
10807:         my @dir_lines;
10808:         my $dirptr=16384;
10809:         if (ref($dirlistref) eq 'ARRAY') {
10810:             foreach my $dir_line (sort
10811:                               {
10812:                                   my ($afile)=split('&',$a,2);
10813:                                   my ($bfile)=split('&',$b,2);
10814:                                   return (lc($afile) cmp lc($bfile));
10815:                               } (@{$dirlistref})) {
10816:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10817:                     split(/\&/,$dir_line,16);
10818:                 $item =~ s/\s+$//;
10819:                 next if (($item =~ /^\.\.?$/) || ($obs));
10820:                 if ($dirptr&$testdir) {
10821:                     my $newpath;
10822:                     if ($relpath) {
10823:                         $newpath = "$relpath/$item";
10824:                     } else {
10825:                         $relpath = '/';
10826:                         $newpath = $item;
10827:                     }
10828:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10829:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10830:                 } elsif ($savefile) {
10831:                     if ($context eq 'priv') {
10832:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10833:                             $filehashref->{$relpath}{$item} = 1;
10834:                         }
10835:                     } else {
10836:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10837:                             $filehashref->{$relpath}{$item} = 1;
10838:                         }
10839:                     }
10840:                 }
10841:             }
10842:         }
10843:     }
10844:     return;
10845: }
10846: 
10847: # -------------------------------------------------------- Value of a Condition
10848: 
10849: # gets the value of a specific preevaluated condition
10850: #    stored in the string  $env{user.state.<cid>}
10851: # or looks up a condition reference in the bighash and if if hasn't
10852: # already been evaluated recurses into docondval to get the value of
10853: # the condition, then memoizing it to 
10854: #   $env{user.state.<cid>.<condition>}
10855: sub directcondval {
10856:     my $number=shift;
10857:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
10858: 	&Apache::lonuserstate::evalstate();
10859:     }
10860:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10861: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10862:     } elsif ($number =~ /^_/) {
10863: 	my $sub_condition;
10864: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10865: 		&GDBM_READER(),0640)) {
10866: 	    $sub_condition=$bighash{'conditions'.$number};
10867: 	    untie(%bighash);
10868: 	}
10869: 	my $value = &docondval($sub_condition);
10870: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
10871: 	return $value;
10872:     }
10873:     if ($env{'user.state.'.$env{'request.course.id'}}) {
10874:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
10875:     } else {
10876:        return 2;
10877:     }
10878: }
10879: 
10880: # get the collection of conditions for this resource
10881: sub condval {
10882:     my $condidx=shift;
10883:     my $allpathcond='';
10884:     foreach my $cond (split(/\|/,$condidx)) {
10885: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10886: 	    $allpathcond.=
10887: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10888: 	}
10889:     }
10890:     $allpathcond=~s/\|$//;
10891:     return &docondval($allpathcond);
10892: }
10893: 
10894: #evaluates an expression of conditions
10895: sub docondval {
10896:     my ($allpathcond) = @_;
10897:     my $result=0;
10898:     if ($env{'request.course.id'}
10899: 	&& defined($allpathcond)) {
10900: 	my $operand='|';
10901: 	my @stack;
10902: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10903: 	    if ($chunk eq '(') {
10904: 		push @stack,($operand,$result);
10905: 	    } elsif ($chunk eq ')') {
10906: 		my $before=pop @stack;
10907: 		if (pop @stack eq '&') {
10908: 		    $result=$result>$before?$before:$result;
10909: 		} else {
10910: 		    $result=$result>$before?$result:$before;
10911: 		}
10912: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
10913: 		$operand=$chunk;
10914: 	    } else {
10915: 		my $new=directcondval($chunk);
10916: 		if ($operand eq '&') {
10917: 		    $result=$result>$new?$new:$result;
10918: 		} else {
10919: 		    $result=$result>$new?$result:$new;
10920: 		}
10921: 	    }
10922: 	}
10923:     }
10924:     return $result;
10925: }
10926: 
10927: # ---------------------------------------------------- Devalidate courseresdata
10928: 
10929: sub devalidatecourseresdata {
10930:     my ($coursenum,$coursedomain)=@_;
10931:     my $hashid=$coursenum.':'.$coursedomain;
10932:     &devalidate_cache_new('courseres',$hashid);
10933: }
10934: 
10935: 
10936: # --------------------------------------------------- Course Resourcedata Query
10937: #
10938: #  Parameters:
10939: #      $coursenum    - Number of the course.
10940: #      $coursedomain - Domain at which the course was created.
10941: #  Returns:
10942: #     A hash of the course parameters along (I think) with timestamps
10943: #     and version info.
10944: 
10945: sub get_courseresdata {
10946:     my ($coursenum,$coursedomain)=@_;
10947:     my $coursehom=&homeserver($coursenum,$coursedomain);
10948:     my $hashid=$coursenum.':'.$coursedomain;
10949:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
10950:     my %dumpreply;
10951:     unless (defined($cached)) {
10952: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
10953: 	$result=\%dumpreply;
10954: 	my ($tmp) = keys(%dumpreply);
10955: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10956: 	    &do_cache_new('courseres',$hashid,$result,600);
10957: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10958: 	    return $tmp;
10959: 	} elsif ($tmp =~ /^(error)/) {
10960: 	    $result=undef;
10961: 	    &do_cache_new('courseres',$hashid,$result,600);
10962: 	}
10963:     }
10964:     return $result;
10965: }
10966: 
10967: sub devalidateuserresdata {
10968:     my ($uname,$udom)=@_;
10969:     my $hashid="$udom:$uname";
10970:     &devalidate_cache_new('userres',$hashid);
10971: }
10972: 
10973: sub get_userresdata {
10974:     my ($uname,$udom)=@_;
10975:     #most student don\'t have any data set, check if there is some data
10976:     if (&EXT_cache_status($udom,$uname)) { return undef; }
10977: 
10978:     my $hashid="$udom:$uname";
10979:     my ($result,$cached)=&is_cached_new('userres',$hashid);
10980:     if (!defined($cached)) {
10981: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
10982: 	$result=\%resourcedata;
10983: 	&do_cache_new('userres',$hashid,$result,600);
10984:     }
10985:     my ($tmp)=keys(%$result);
10986:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10987: 	return $result;
10988:     }
10989:     #error 2 occurs when the .db doesn't exist
10990:     if ($tmp!~/error: 2 /) {
10991:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10992: 	    &logthis("<font color=\"blue\">WARNING:".
10993: 		     " Trying to get resource data for ".
10994: 		     $uname." at ".$udom.": ".
10995: 		     $tmp."</font>");
10996:         }
10997:     } elsif ($tmp=~/error: 2 /) {
10998: 	#&EXT_cache_set($udom,$uname);
10999: 	&do_cache_new('userres',$hashid,undef,600);
11000: 	undef($tmp); # not really an error so don't send it back
11001:     }
11002:     return $tmp;
11003: }
11004: #----------------------------------------------- resdata - return resource data
11005: #  Purpose:
11006: #    Return resource data for either users or for a course.
11007: #  Parameters:
11008: #     $name      - Course/user name.
11009: #     $domain    - Name of the domain the user/course is registered on.
11010: #     $type      - Type of thing $name is (must be 'course' or 'user')
11011: #     $mapp      - decluttered URL of enclosing map  
11012: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11013: #     $recurseup - Ref to array of map URLs, starting with map containing
11014: #                  $mapp up through hierarchy of nested maps to top level map.  
11015: #     $courseid  - CourseID (first part of param identifier).
11016: #     $modifier  - Middle part of param identifier.
11017: #     $what      - Last part of param identifier.
11018: #     @which     - Array of names of resources desired.
11019: #  Returns:
11020: #     The value of the first reasource in @which that is found in the
11021: #     resource hash.
11022: #  Exceptional Conditions:
11023: #     If the $type passed in is not valid (not the string 'course' or 
11024: #     'user', an undefined  reference is returned.
11025: #     If none of the resources are found, an undef is returned
11026: sub resdata {
11027:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11028:         $modifier,$what,@which)=@_;
11029:     my $result;
11030:     if ($type eq 'course') {
11031: 	$result=&get_courseresdata($name,$domain);
11032:     } elsif ($type eq 'user') {
11033: 	$result=&get_userresdata($name,$domain);
11034:     }
11035:     if (!ref($result)) { return $result; }    
11036:     foreach my $item (@which) {
11037:         if ($item->[1] eq 'course') {
11038:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11039:                 unless ($$recursed) {
11040:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11041:                     $$recursed = 1;
11042:                 }
11043:                 foreach my $item (@${recurseup}) {
11044:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11045:                     last if (defined($result->{$norecursechk}));
11046:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11047:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11048:                 }
11049:             }
11050:         }
11051:         if (defined($result->{$item->[0]})) {
11052: 	    return [$result->{$item->[0]},$item->[1]];
11053: 	}
11054:     }
11055:     return undef;
11056: }
11057: 
11058: sub get_domain_ltitools {
11059:     my ($cdom) = @_;
11060:     my %ltitools;
11061:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
11062:     if (defined($cached)) {
11063:         if (ref($result) eq 'HASH') {
11064:             %ltitools = %{$result};
11065:         }
11066:     } else {
11067:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
11068:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
11069:             %ltitools = %{$domconfig{'ltitools'}};
11070:             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
11071:             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
11072:                 foreach my $id (keys(%ltitools)) {
11073:                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
11074:                         foreach my $item ('key','secret') {
11075:                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
11076:                         }
11077:                     }
11078:                 }
11079:             }
11080:         }
11081:         my $cachetime = 24*60*60;
11082:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
11083:     }
11084:     return %ltitools;
11085: }
11086: 
11087: sub get_numsuppfiles {
11088:     my ($cnum,$cdom,$ignorecache)=@_;
11089:     my $hashid=$cnum.':'.$cdom;
11090:     my ($suppcount,$cached);
11091:     unless ($ignorecache) {
11092:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11093:     }
11094:     unless (defined($cached)) {
11095:         my $chome=&homeserver($cnum,$cdom);
11096:         unless ($chome eq 'no_host') {
11097:             ($suppcount,my $errors) = (0,0);
11098:             my $suppmap = 'supplemental.sequence';
11099:             ($suppcount,$errors) = 
11100:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11101:         }
11102:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11103:     }
11104:     return $suppcount;
11105: }
11106: 
11107: #
11108: # EXT resource caching routines
11109: #
11110: 
11111: {
11112: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11113: #
11114: # The course for which we cache
11115: my $cachedmapkey='';
11116: # The cached recursive maps for this course
11117: my %cachedmaps=();
11118: # When this was last done
11119: my $cachedmaptime='';
11120: 
11121: sub clear_EXT_cache_status {
11122:     &delenv('cache.EXT.');
11123: }
11124: 
11125: sub EXT_cache_status {
11126:     my ($target_domain,$target_user) = @_;
11127:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11128:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11129:         # We know already the user has no data
11130:         return 1;
11131:     } else {
11132:         return 0;
11133:     }
11134: }
11135: 
11136: sub EXT_cache_set {
11137:     my ($target_domain,$target_user) = @_;
11138:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11139:     #&appenv({$cachename => time});
11140: }
11141: 
11142: # --------------------------------------------------------- Value of a Variable
11143: sub EXT {
11144: 
11145:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11146:     unless ($varname) { return ''; }
11147:     #get real user name/domain, courseid and symb
11148:     my $courseid;
11149:     my $publicuser;
11150:     if ($symbparm) {
11151: 	$symbparm=&get_symb_from_alias($symbparm);
11152:     }
11153:     if (!($uname && $udom)) {
11154:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11155:       if (!$symbparm) {	$symbparm=$cursymb; }
11156:     } else {
11157: 	$courseid=$env{'request.course.id'};
11158:     }
11159:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11160:     my $rest;
11161:     if (defined($therest[0])) {
11162:        $rest=join('.',@therest);
11163:     } else {
11164:        $rest='';
11165:     }
11166: 
11167:     my $qualifierrest=$qualifier;
11168:     if ($rest) { $qualifierrest.='.'.$rest; }
11169:     my $spacequalifierrest=$space;
11170:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11171:     if ($realm eq 'user') {
11172: # --------------------------------------------------------------- user.resource
11173: 	if ($space eq 'resource') {
11174: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11175: 		  || defined($Apache::lonhomework::parsing_a_task))
11176: 		 &&
11177: 		 ($symbparm eq &symbread()) ) {	
11178: 		# if we are in the middle of processing the resource the
11179: 		# get the value we are planning on committing
11180:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11181:                     return $Apache::lonhomework::results{$qualifierrest};
11182:                 } else {
11183:                     return $Apache::lonhomework::history{$qualifierrest};
11184:                 }
11185: 	    } else {
11186: 		my %restored;
11187: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11188: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11189: 		} else {
11190: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11191: 		}
11192: 		return $restored{$qualifierrest};
11193: 	    }
11194: # ----------------------------------------------------------------- user.access
11195:         } elsif ($space eq 'access') {
11196: 	    # FIXME - not supporting calls for a specific user
11197:             return &allowed($qualifier,$rest);
11198: # ------------------------------------------ user.preferences, user.environment
11199:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11200: 	    if (($uname eq $env{'user.name'}) &&
11201: 		($udom eq $env{'user.domain'})) {
11202: 		return $env{join('.',('environment',$qualifierrest))};
11203: 	    } else {
11204: 		my %returnhash;
11205: 		if (!$publicuser) {
11206: 		    %returnhash=&userenvironment($udom,$uname,
11207: 						 $qualifierrest);
11208: 		}
11209: 		return $returnhash{$qualifierrest};
11210: 	    }
11211: # ----------------------------------------------------------------- user.course
11212:         } elsif ($space eq 'course') {
11213: 	    # FIXME - not supporting calls for a specific user
11214:             return $env{join('.',('request.course',$qualifier))};
11215: # ------------------------------------------------------------------- user.role
11216:         } elsif ($space eq 'role') {
11217: 	    # FIXME - not supporting calls for a specific user
11218:             my ($role,$where)=split(/\./,$env{'request.role'});
11219:             if ($qualifier eq 'value') {
11220: 		return $role;
11221:             } elsif ($qualifier eq 'extent') {
11222:                 return $where;
11223:             }
11224: # ----------------------------------------------------------------- user.domain
11225:         } elsif ($space eq 'domain') {
11226:             return $udom;
11227: # ------------------------------------------------------------------- user.name
11228:         } elsif ($space eq 'name') {
11229:             return $uname;
11230: # ---------------------------------------------------- Any other user namespace
11231:         } else {
11232: 	    my %reply;
11233: 	    if (!$publicuser) {
11234: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11235: 	    }
11236: 	    return $reply{$qualifierrest};
11237:         }
11238:     } elsif ($realm eq 'query') {
11239: # ---------------------------------------------- pull stuff out of query string
11240:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11241: 						[$spacequalifierrest]);
11242: 	return $env{'form.'.$spacequalifierrest}; 
11243:    } elsif ($realm eq 'request') {
11244: # ------------------------------------------------------------- request.browser
11245:         if ($space eq 'browser') {
11246:             return $env{'browser.'.$qualifier};
11247: # ------------------------------------------------------------ request.filename
11248:         } else {
11249:             return $env{'request.'.$spacequalifierrest};
11250:         }
11251:     } elsif ($realm eq 'course') {
11252: # ---------------------------------------------------------- course.description
11253:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11254:     } elsif ($realm eq 'resource') {
11255: 
11256: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11257: 	    if (!$symbparm) { $symbparm=&symbread(); }
11258: 	}
11259: 
11260:         if ($qualifier eq '') {
11261: 	    if ($space eq 'title') {
11262: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11263: 	        return &gettitle($symbparm);
11264: 	    }
11265: 	
11266: 	    if ($space eq 'map') {
11267: 	        my ($map) = &decode_symb($symbparm);
11268: 	        return &symbread($map);
11269: 	    }
11270:             if ($space eq 'maptitle') {
11271:                 my ($map) = &decode_symb($symbparm);
11272:                 return &gettitle($map);
11273:             }
11274: 	    if ($space eq 'filename') {
11275: 	        if ($symbparm) {
11276: 		    return &clutter((&decode_symb($symbparm))[2]);
11277: 	        }
11278: 	        return &hreflocation('',$env{'request.filename'});
11279: 	    }
11280: 
11281:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11282:                 if ($space eq 'visibleparts') {
11283:                     my $navmap = Apache::lonnavmaps::navmap->new();
11284:                     my $item;
11285:                     if (ref($navmap)) {
11286:                         my $res = $navmap->getBySymb($symbparm);
11287:                         my $parts = $res->parts();
11288:                         if (ref($parts) eq 'ARRAY') {
11289:                             $item = join(',',@{$parts});
11290:                         }
11291:                         undef($navmap);
11292:                     }
11293:                     return $item;
11294:                 }
11295:             }
11296:         }
11297: 
11298: 	my ($section, $group, @groups, @recurseup, $recursed);
11299: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11300:         if (($courseid eq '') && ($cid)) {
11301:             $courseid = $cid;
11302:         }
11303: 	if (($symbparm && $courseid) && 
11304: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11305: 
11306: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11307: 
11308: # ----------------------------------------------------- Cascading lookup scheme
11309: 	    my $symbp=$symbparm;
11310: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11311: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11312:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11313: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11314: 	    if (($env{'user.name'} eq $uname) &&
11315: 		($env{'user.domain'} eq $udom)) {
11316: 		$section=$env{'request.course.sec'};
11317:                 @groups = split(/:/,$env{'request.course.groups'});  
11318:                 @groups=&sort_course_groups($courseid,@groups); 
11319: 	    } else {
11320: 		if (! defined($usection)) {
11321: 		    $section=&getsection($udom,$uname,$courseid);
11322: 		} else {
11323: 		    $section = $usection;
11324: 		}
11325:                 @groups = &get_users_groups($udom,$uname,$courseid);
11326: 	    }
11327: 
11328: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11329: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11330:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11331: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11332: 
11333: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11334: 	    my $courselevelr=$courseid.'.'.$symbparm;
11335:             $courseleveli=$courseid.'.'.$recurseparm;
11336: 	    $courselevelm=$courseid.'.'.$mapparm;
11337: 
11338: # ----------------------------------------------------------- first, check user
11339: 
11340: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11341:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11342: 				       ([$courselevelr,'resource'],
11343: 					[$courselevelm,'map'     ],
11344:                                         [$courseleveli,'map'     ],
11345: 					[$courselevel, 'course'  ]));
11346: 	    if (defined($userreply)) { return &get_reply($userreply); }
11347: 
11348: # ------------------------------------------------ second, check some of course
11349:             my $coursereply;
11350:             if (@groups > 0) {
11351:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11352:                                        $recurseparm,$mapparm,$spacequalifierrest,
11353:                                        $mapp,\$recursed,\@recurseup);
11354:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11355:             }
11356: 
11357: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11358: 				  $env{'course.'.$courseid.'.domain'},
11359: 				  'course',$mapp,\$recursed,\@recurseup,
11360:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11361: 				  ([$seclevelr,   'resource'],
11362: 				   [$seclevelm,   'map'     ],
11363:                                    [$secleveli,   'map'     ],
11364: 				   [$seclevel,    'course'  ],
11365: 				   [$courselevelr,'resource']));
11366: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11367: 
11368: # ------------------------------------------------------ third, check map parms
11369: 	    my %parmhash=();
11370: 	    my $thisparm='';
11371: 	    if (tie(%parmhash,'GDBM_File',
11372: 		    $env{'request.course.fn'}.'_parms.db',
11373: 		    &GDBM_READER(),0640)) {
11374: 		$thisparm=$parmhash{$symbparm};
11375: 		untie(%parmhash);
11376: 	    }
11377: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11378: 	}
11379: # ------------------------------------------ fourth, look in resource metadata
11380:  
11381:         my $what = $spacequalifierrest;
11382: 	$what=~s/\./\_/;
11383: 	my $filename;
11384: 	if (!$symbparm) { $symbparm=&symbread(); }
11385: 	if ($symbparm) {
11386: 	    $filename=(&decode_symb($symbparm))[2];
11387: 	} else {
11388: 	    $filename=$env{'request.filename'};
11389: 	}
11390: 	my $metadata=&metadata($filename,$what);
11391: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11392: 	$metadata=&metadata($filename,'parameter_'.$what);
11393: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11394: 
11395: # ----------------------------------------------- fifth, look in rest of course
11396: 	if ($symbparm && defined($courseid) && 
11397: 	    $courseid eq $env{'request.course.id'}) {
11398: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11399: 				     $env{'course.'.$courseid.'.domain'},
11400: 				     'course',$mapp,\$recursed,\@recurseup,
11401:                                      $courseid,'.',$spacequalifierrest,
11402: 				     ([$courselevelm,'map'   ],
11403:                                       [$courseleveli,'map'   ],
11404: 				      [$courselevel, 'course']));
11405: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11406: 	}
11407: # ------------------------------------------------------------------ Cascade up
11408: 	unless ($space eq '0') {
11409: 	    my @parts=split(/_/,$space);
11410: 	    my $id=pop(@parts);
11411: 	    my $part=join('_',@parts);
11412: 	    if ($part eq '') { $part='0'; }
11413: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11414: 				 $symbparm,$udom,$uname,$section,1);
11415: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11416: 	}
11417: 	if ($recurse) { return undef; }
11418: 	my $pack_def=&packages_tab_default($filename,$varname);
11419: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11420: # ---------------------------------------------------- Any other user namespace
11421:     } elsif ($realm eq 'environment') {
11422: # ----------------------------------------------------------------- environment
11423: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11424: 	    return $env{'environment.'.$spacequalifierrest};
11425: 	} else {
11426: 	    if ($uname eq 'anonymous' && $udom eq '') {
11427: 		return '';
11428: 	    }
11429: 	    my %returnhash=&userenvironment($udom,$uname,
11430: 					    $spacequalifierrest);
11431: 	    return $returnhash{$spacequalifierrest};
11432: 	}
11433:     } elsif ($realm eq 'system') {
11434: # ----------------------------------------------------------------- system.time
11435: 	if ($space eq 'time') {
11436: 	    return time;
11437:         }
11438:     } elsif ($realm eq 'server') {
11439: # ----------------------------------------------------------------- system.time
11440: 	if ($space eq 'name') {
11441: 	    return $ENV{'SERVER_NAME'};
11442:         }
11443:     }
11444:     return '';
11445: }
11446: 
11447: sub get_reply {
11448:     my ($reply_value) = @_;
11449:     if (ref($reply_value) eq 'ARRAY') {
11450:         if (wantarray) {
11451: 	    return @$reply_value;
11452:         }
11453:         return $reply_value->[0];
11454:     } else {
11455:         return $reply_value;
11456:     }
11457: }
11458: 
11459: sub check_group_parms {
11460:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11461:         $recursed,$recurseupref) = @_;
11462:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11463:                   [$what,'course']);
11464:     my $coursereply;
11465:     foreach my $group (@{$groups}) {
11466:         my @groupitems = ();
11467:         foreach my $level (@levels) {
11468:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11469:              push(@groupitems,[$item,$level->[1]]);
11470:         }
11471:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11472:                                    $env{'course.'.$courseid.'.domain'},
11473:                                    'course',$mapp,$recursed,$recurseupref,
11474:                                    $courseid,'.['.$group.'].',$what,
11475:                                    @groupitems);
11476:         last if (defined($coursereply));
11477:     }
11478:     return $coursereply;
11479: }
11480: 
11481: sub get_map_hierarchy {
11482:     my ($mapname,$courseid) = @_;
11483:     my @recurseup = ();
11484:     if ($mapname) {
11485:         if (($cachedmapkey eq $courseid) &&
11486:             (abs($cachedmaptime-time)<5)) {
11487:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11488:                 return @{$cachedmaps{$mapname}};
11489:             }
11490:         }
11491:         my $navmap = Apache::lonnavmaps::navmap->new();
11492:         if (ref($navmap)) {
11493:             @recurseup = $navmap->recurseup_maps($mapname);
11494:             undef($navmap);
11495:             $cachedmaps{$mapname} = \@recurseup;
11496:             $cachedmaptime=time;
11497:             $cachedmapkey=$courseid;
11498:         }
11499:     }
11500:     return @recurseup;
11501: }
11502: 
11503: }
11504: 
11505: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11506:     my ($courseid,@groups) = @_;
11507:     @groups = sort(@groups);
11508:     return @groups;
11509: }
11510: 
11511: sub packages_tab_default {
11512:     my ($uri,$varname)=@_;
11513:     my (undef,$part,$name)=split(/\./,$varname);
11514: 
11515:     my (@extension,@specifics,$do_default);
11516:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11517: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11518: 	if ($pack_type eq 'default') {
11519: 	    $do_default=1;
11520: 	} elsif ($pack_type eq 'extension') {
11521: 	    push(@extension,[$package,$pack_type,$pack_part]);
11522: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11523: 	    # only look at packages defaults for packages that this id is
11524: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11525: 	}
11526:     }
11527:     # first look for a package that matches the requested part id
11528:     foreach my $package (@specifics) {
11529: 	my (undef,$pack_type,$pack_part)=@{$package};
11530: 	next if ($pack_part ne $part);
11531: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11532: 	    return $packagetab{"$pack_type&$name&default"};
11533: 	}
11534:     }
11535:     # look for any possible matching non extension_ package
11536:     foreach my $package (@specifics) {
11537: 	my (undef,$pack_type,$pack_part)=@{$package};
11538: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11539: 	    return $packagetab{"$pack_type&$name&default"};
11540: 	}
11541: 	if ($pack_type eq 'part') { $pack_part='0'; }
11542: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11543: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11544: 	}
11545:     }
11546:     # look for any posible extension_ match
11547:     foreach my $package (@extension) {
11548: 	my ($package,$pack_type)=@{$package};
11549: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11550: 	    return $packagetab{"$pack_type&$name&default"};
11551: 	}
11552: 	if (defined($packagetab{$package."&$name&default"})) {
11553: 	    return $packagetab{$package."&$name&default"};
11554: 	}
11555:     }
11556:     # look for a global default setting
11557:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11558: 	return $packagetab{"default&$name&default"};
11559:     }
11560:     return undef;
11561: }
11562: 
11563: sub add_prefix_and_part {
11564:     my ($prefix,$part)=@_;
11565:     my $keyroot;
11566:     if (defined($prefix) && $prefix !~ /^__/) {
11567: 	# prefix that has a part already
11568: 	$keyroot=$prefix;
11569:     } elsif (defined($prefix)) {
11570: 	# prefix that is missing a part
11571: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11572:     } else {
11573: 	# no prefix at all
11574: 	if (defined($part)) { $keyroot='_'.$part; }
11575:     }
11576:     return $keyroot;
11577: }
11578: 
11579: # ---------------------------------------------------------------- Get metadata
11580: 
11581: my %metaentry;
11582: my %importedpartids;
11583: sub metadata {
11584:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11585:     $uri=&declutter($uri);
11586:     # if it is a non metadata possible uri return quickly
11587:     if (($uri eq '') || 
11588: 	(($uri =~ m|^/*adm/|) && 
11589: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11590:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11591: 	return undef;
11592:     }
11593:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11594: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11595: 	return undef;
11596:     }
11597:     my $filename=$uri;
11598:     $uri=~s/\.meta$//;
11599: #
11600: # Is the metadata already cached?
11601: # Look at timestamp of caching
11602: # Everything is cached by the main uri, libraries are never directly cached
11603: #
11604:     if (!defined($liburi)) {
11605: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11606: 	if (defined($cached)) { return $result->{':'.$what}; }
11607:     }
11608:     {
11609: # Imported parts would go here
11610:         my %importedids=();
11611:         my @origfileimportpartids=();
11612:         my $importedparts=0;
11613: #
11614: # Is this a recursive call for a library?
11615: #
11616: #	if (! exists($metacache{$uri})) {
11617: #	    $metacache{$uri}={};
11618: #	}
11619: 	my $cachetime = 60*60;
11620:         if ($liburi) {
11621: 	    $liburi=&declutter($liburi);
11622:             $filename=$liburi;
11623:         } else {
11624: 	    &devalidate_cache_new('meta',$uri);
11625: 	    undef(%metaentry);
11626: 	}
11627:         my %metathesekeys=();
11628:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11629: 	my $metastring;
11630: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11631: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11632: 	    $metastring = 
11633: 		&Apache::lonnet::ssi_body($which,
11634: 					  ('grade_target' => 'meta'));
11635: 	    $cachetime = 1; # only want this cached in the child not long term
11636: 	} elsif (($uri !~ m -^(editupload)/-) && 
11637:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11638: 	    my $file=&filelocation('',&clutter($filename));
11639: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11640: 	    $metastring=&getfile($file);
11641: 	}
11642:         my $parser=HTML::LCParser->new(\$metastring);
11643:         my $token;
11644:         undef %metathesekeys;
11645:         while ($token=$parser->get_token) {
11646: 	    if ($token->[0] eq 'S') {
11647: 		if (defined($token->[2]->{'package'})) {
11648: #
11649: # This is a package - get package info
11650: #
11651: 		    my $package=$token->[2]->{'package'};
11652: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11653: 		    if (defined($token->[2]->{'id'})) { 
11654: 			$keyroot.='_'.$token->[2]->{'id'}; 
11655: 		    }
11656: 		    if ($metaentry{':packages'}) {
11657: 			$metaentry{':packages'}.=','.$package.$keyroot;
11658: 		    } else {
11659: 			$metaentry{':packages'}=$package.$keyroot;
11660: 		    }
11661: 		    foreach my $pack_entry (keys(%packagetab)) {
11662: 			my $part=$keyroot;
11663: 			$part=~s/^\_//;
11664: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11665: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11666: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11667: 			    # ignore package.tab specified default values
11668:                             # here &package_tab_default() will fetch those
11669: 			    if ($subp eq 'default') { next; }
11670: 			    my $value=$packagetab{$pack_entry};
11671: 			    my $unikey;
11672: 			    if ($pack =~ /_0$/) {
11673: 				$unikey='parameter_0_'.$name;
11674: 				$part=0;
11675: 			    } else {
11676: 				$unikey='parameter'.$keyroot.'_'.$name;
11677: 			    }
11678: 			    if ($subp eq 'display') {
11679: 				$value.=' [Part: '.$part.']';
11680: 			    }
11681: 			    $metaentry{':'.$unikey.'.part'}=$part;
11682: 			    $metathesekeys{$unikey}=1;
11683: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11684: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11685: 			    }
11686: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11687: 				$metaentry{':'.$unikey}=
11688: 				    $metaentry{':'.$unikey.'.default'};
11689: 			    }
11690: 			}
11691: 		    }
11692: 		} else {
11693: #
11694: # This is not a package - some other kind of start tag
11695: #
11696: 		    my $entry=$token->[1];
11697: 		    my $unikey='';
11698: 
11699: 		    if ($entry eq 'import') {
11700: #
11701: # Importing a library here
11702: #
11703:                         my $location=$parser->get_text('/import');
11704:                         my $dir=$filename;
11705:                         $dir=~s|[^/]*$||;
11706:                         $location=&filelocation($dir,$location);
11707:                        
11708:                         my $importmode=$token->[2]->{'importmode'};
11709:                         if ($importmode eq 'problem') {
11710: # Import as problem/response
11711:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11712:                         } elsif ($importmode eq 'part') {
11713: # Import as part(s)
11714:                            $importedparts=1;
11715: # We need to get the original file and the imported file to get the part order correct
11716: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11717: # Load and inspect original file
11718:                            if ($#origfileimportpartids<0) {
11719:                               undef(%importedpartids);
11720:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11721:                               my $origfile=&getfile($origfilelocation);
11722:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11723:                            }
11724: 
11725: # Load and inspect imported file
11726:                            my $impfile=&getfile($location);
11727:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11728:                            if ($#impfilepartids>=0) {
11729: # This problem had parts
11730:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11731:                            } else {
11732: # Importing by turning a single problem into a problem part
11733: # It gets the import-tags ID as part-ID
11734:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11735:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11736:                            }
11737:                         } else {
11738: # Normal import
11739:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11740:                            if (defined($token->[2]->{'id'})) {
11741:                               $unikey.='_'.$token->[2]->{'id'};
11742:                            }
11743:                         }
11744: 
11745: 			if ($depthcount<20) {
11746: 			    my $metadata = 
11747: 				&metadata($uri,'keys', $location,$unikey,
11748: 					  $depthcount+1);
11749: 			    foreach my $meta (split(',',$metadata)) {
11750: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
11751: 				$metathesekeys{$meta}=1;
11752: 			    }
11753: 			
11754:                         }
11755: 		    } else {
11756: #
11757: # Not importing, some other kind of non-package, non-library start tag
11758: # 
11759:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11760:                         if (defined($token->[2]->{'id'})) {
11761:                             $unikey.='_'.$token->[2]->{'id'};
11762:                         }
11763: 			if (defined($token->[2]->{'name'})) { 
11764: 			    $unikey.='_'.$token->[2]->{'name'}; 
11765: 			}
11766: 			$metathesekeys{$unikey}=1;
11767: 			foreach my $param (@{$token->[3]}) {
11768: 			    $metaentry{':'.$unikey.'.'.$param} =
11769: 				$token->[2]->{$param};
11770: 			}
11771: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
11772: 			my $default=$metaentry{':'.$unikey.'.default'};
11773: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11774: 		 # only ws inside the tag, and not in default, so use default
11775: 		 # as value
11776: 			    $metaentry{':'.$unikey}=$default;
11777: 			} elsif ( $internaltext =~ /\S/ ) {
11778: 		  # something interesting inside the tag
11779: 			    $metaentry{':'.$unikey}=$internaltext;
11780: 			} else {
11781: 		  # no interesting values, don't set a default
11782: 			}
11783: # end of not-a-package not-a-library import
11784: 		    }
11785: # end of not-a-package start tag
11786: 		}
11787: # the next is the end of "start tag"
11788: 	    }
11789: 	}
11790: 	my ($extension) = ($uri =~ /\.(\w+)$/);
11791: 	$extension = lc($extension);
11792: 	if ($extension eq 'htm') { $extension='html'; }
11793: 
11794: 	foreach my $key (keys(%packagetab)) {
11795: 	    #no specific packages #how's our extension
11796: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
11797: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
11798: 					 \%metathesekeys);
11799: 	}
11800: 
11801: 	if (!exists($metaentry{':packages'})
11802: 	    || $packagetab{"import_defaults&extension_$extension"}) {
11803: 	    foreach my $key (keys(%packagetab)) {
11804: 		#no specific packages well let's get default then
11805: 		if ($key!~/^default&/) { next; }
11806: 		&metadata_create_package_def($uri,$key,'default',
11807: 					     \%metathesekeys);
11808: 	    }
11809: 	}
11810: # are there custom rights to evaluate
11811: 	if ($metaentry{':copyright'} eq 'custom') {
11812: 
11813:     #
11814:     # Importing a rights file here
11815:     #
11816: 	    unless ($depthcount) {
11817: 		my $location=$metaentry{':customdistributionfile'};
11818: 		my $dir=$filename;
11819: 		$dir=~s|[^/]*$||;
11820: 		$location=&filelocation($dir,$location);
11821: 		my $rights_metadata =
11822: 		    &metadata($uri,'keys',$location,'_rights',
11823: 			      $depthcount+1);
11824: 		foreach my $rights (split(',',$rights_metadata)) {
11825: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11826: 		    $metathesekeys{$rights}=1;
11827: 		}
11828: 	    }
11829: 	}
11830: 	# uniqifiy package listing
11831: 	my %seen;
11832: 	my @uniq_packages =
11833: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11834: 	$metaentry{':packages'} = join(',',@uniq_packages);
11835: 
11836:         if ($importedparts) {
11837: # We had imported parts and need to rebuild partorder
11838:            $metaentry{':partorder'}='';
11839:            $metathesekeys{'partorder'}=1;
11840:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11841:                if ($origfileimportpartids[$index] eq 'part') {
11842: # original part, part of the problem
11843:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11844:                } else {
11845: # we have imported parts at this position
11846:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11847:                }
11848:            }
11849:            $metaentry{':partorder'}=~s/^\,//;
11850:         }
11851: 
11852: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
11853: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
11854: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
11855: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
11856: # this is the end of "was not already recently cached
11857:     }
11858:     return $metaentry{':'.$what};
11859: }
11860: 
11861: sub metadata_create_package_def {
11862:     my ($uri,$key,$package,$metathesekeys)=@_;
11863:     my ($pack,$name,$subp)=split(/\&/,$key);
11864:     if ($subp eq 'default') { next; }
11865:     
11866:     if (defined($metaentry{':packages'})) {
11867: 	$metaentry{':packages'}.=','.$package;
11868:     } else {
11869: 	$metaentry{':packages'}=$package;
11870:     }
11871:     my $value=$packagetab{$key};
11872:     my $unikey;
11873:     $unikey='parameter_0_'.$name;
11874:     $metaentry{':'.$unikey.'.part'}=0;
11875:     $$metathesekeys{$unikey}=1;
11876:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11877: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
11878:     }
11879:     if (defined($metaentry{':'.$unikey.'.default'})) {
11880: 	$metaentry{':'.$unikey}=
11881: 	    $metaentry{':'.$unikey.'.default'};
11882:     }
11883: }
11884: 
11885: sub metadata_generate_part0 {
11886:     my ($metadata,$metacache,$uri) = @_;
11887:     my %allnames;
11888:     foreach my $metakey (keys(%$metadata)) {
11889: 	if ($metakey=~/^parameter\_(.*)/) {
11890: 	  my $part=$$metacache{':'.$metakey.'.part'};
11891: 	  my $name=$$metacache{':'.$metakey.'.name'};
11892: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
11893: 	    $allnames{$name}=$part;
11894: 	  }
11895: 	}
11896:     }
11897:     foreach my $name (keys(%allnames)) {
11898:       $$metadata{"parameter_0_$name"}=1;
11899:       my $key=":parameter_0_$name";
11900:       $$metacache{"$key.part"}='0';
11901:       $$metacache{"$key.name"}=$name;
11902:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
11903: 					   $allnames{$name}.'_'.$name.
11904: 					   '.type'};
11905:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
11906: 			     '.display'};
11907:       my $expr='[Part: '.$allnames{$name}.']';
11908:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
11909:       $$metacache{"$key.display"}=$olddis;
11910:     }
11911: }
11912: 
11913: # ------------------------------------------------------ Devalidate title cache
11914: 
11915: sub devalidate_title_cache {
11916:     my ($url)=@_;
11917:     if (!$env{'request.course.id'}) { return; }
11918:     my $symb=&symbread($url);
11919:     if (!$symb) { return; }
11920:     my $key=$env{'request.course.id'}."\0".$symb;
11921:     &devalidate_cache_new('title',$key);
11922: }
11923: 
11924: # ------------------------------------------------- Get the title of a course
11925: 
11926: sub current_course_title {
11927:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11928: }
11929: # ------------------------------------------------- Get the title of a resource
11930: 
11931: sub gettitle {
11932:     my $urlsymb=shift;
11933:     my $symb=&symbread($urlsymb);
11934:     if ($symb) {
11935: 	my $key=$env{'request.course.id'}."\0".$symb;
11936: 	my ($result,$cached)=&is_cached_new('title',$key);
11937: 	if (defined($cached)) { 
11938: 	    return $result;
11939: 	}
11940: 	my ($map,$resid,$url)=&decode_symb($symb);
11941: 	my $title='';
11942: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11943: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11944: 	} else {
11945: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11946: 		    &GDBM_READER(),0640)) {
11947: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
11948: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
11949: 		untie(%bighash);
11950: 	    }
11951: 	}
11952: 	$title=~s/\&colon\;/\:/gs;
11953: 	if ($title) {
11954: # Remember both $symb and $title for dynamic metadata
11955:             $accesshash{$symb.'___crstitle'}=$title;
11956:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
11957: # Cache this title and then return it
11958: 	    return &do_cache_new('title',$key,$title,600);
11959: 	}
11960: 	$urlsymb=$url;
11961:     }
11962:     my $title=&metadata($urlsymb,'title');
11963:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
11964:     return $title;
11965: }
11966: 
11967: sub get_slot {
11968:     my ($which,$cnum,$cdom)=@_;
11969:     if (!$cnum || !$cdom) {
11970: 	(undef,my $courseid)=&whichuser();
11971: 	$cdom=$env{'course.'.$courseid.'.domain'};
11972: 	$cnum=$env{'course.'.$courseid.'.num'};
11973:     }
11974:     my $key=join("\0",'slots',$cdom,$cnum,$which);
11975:     my %slotinfo;
11976:     if (exists($remembered{$key})) {
11977: 	$slotinfo{$which} = $remembered{$key};
11978:     } else {
11979: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
11980: 	&Apache::lonhomework::showhash(%slotinfo);
11981: 	my ($tmp)=keys(%slotinfo);
11982: 	if ($tmp=~/^error:/) { return (); }
11983: 	$remembered{$key} = $slotinfo{$which};
11984:     }
11985:     if (ref($slotinfo{$which}) eq 'HASH') {
11986: 	return %{$slotinfo{$which}};
11987:     }
11988:     return $slotinfo{$which};
11989: }
11990: 
11991: sub get_reservable_slots {
11992:     my ($cnum,$cdom,$uname,$udom) = @_;
11993:     my $now = time;
11994:     my $reservable_info;
11995:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11996:     if (exists($remembered{$key})) {
11997:         $reservable_info = $remembered{$key};
11998:     } else {
11999:         my %resv;
12000:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12001:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12002:         $reservable_info = \%resv;
12003:         $remembered{$key} = $reservable_info;
12004:     }
12005:     return $reservable_info;
12006: }
12007: 
12008: sub get_course_slots {
12009:     my ($cnum,$cdom) = @_;
12010:     my $hashid=$cnum.':'.$cdom;
12011:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12012:     if (defined($cached)) {
12013:         if (ref($result) eq 'HASH') {
12014:             return %{$result};
12015:         }
12016:     } else {
12017:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12018:         my ($tmp) = keys(%slots);
12019:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12020:             &do_cache_new('allslots',$hashid,\%slots,600);
12021:             return %slots;
12022:         }
12023:     }
12024:     return;
12025: }
12026: 
12027: sub devalidate_slots_cache {
12028:     my ($cnum,$cdom)=@_;
12029:     my $hashid=$cnum.':'.$cdom;
12030:     &devalidate_cache_new('allslots',$hashid);
12031: }
12032: 
12033: sub get_coursechange {
12034:     my ($cdom,$cnum) = @_;
12035:     if ($cdom eq '' || $cnum eq '') {
12036:         return unless ($env{'request.course.id'});
12037:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12038:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12039:     }
12040:     my $hashid=$cdom.'_'.$cnum;
12041:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12042:     if ((defined($cached)) && ($change ne '')) {
12043:         return $change;
12044:     } else {
12045:         my %crshash;
12046:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12047:         if ($crshash{'internal.contentchange'} eq '') {
12048:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12049:             if ($change eq '') {
12050:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12051:                 $change = $crshash{'internal.created'};
12052:             }
12053:         } else {
12054:             $change = $crshash{'internal.contentchange'};
12055:         }
12056:         my $cachetime = 600;
12057:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12058:     }
12059:     return $change;
12060: }
12061: 
12062: sub devalidate_coursechange_cache {
12063:     my ($cnum,$cdom)=@_;
12064:     my $hashid=$cnum.':'.$cdom;
12065:     &devalidate_cache_new('crschange',$hashid);
12066: }
12067: 
12068: # ------------------------------------------------- Update symbolic store links
12069: 
12070: sub symblist {
12071:     my ($mapname,%newhash)=@_;
12072:     $mapname=&deversion(&declutter($mapname));
12073:     my %hash;
12074:     if (($env{'request.course.fn'}) && (%newhash)) {
12075:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12076:                       &GDBM_WRCREAT(),0640)) {
12077: 	    foreach my $url (keys(%newhash)) {
12078: 		next if ($url eq 'last_known'
12079: 			 && $env{'form.no_update_last_known'});
12080: 		$hash{declutter($url)}=&encode_symb($mapname,
12081: 						    $newhash{$url}->[1],
12082: 						    $newhash{$url}->[0]);
12083:             }
12084:             if (untie(%hash)) {
12085: 		return 'ok';
12086:             }
12087:         }
12088:     }
12089:     return 'error';
12090: }
12091: 
12092: # --------------------------------------------------------------- Verify a symb
12093: 
12094: sub symbverify {
12095:     my ($symb,$thisurl,$encstate)=@_;
12096:     my $thisfn=$thisurl;
12097:     $thisfn=&declutter($thisfn);
12098: # direct jump to resource in page or to a sequence - will construct own symbs
12099:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12100: # check URL part
12101:     my ($map,$resid,$url)=&decode_symb($symb);
12102: 
12103:     unless ($url eq $thisfn) { return 0; }
12104: 
12105:     $symb=&symbclean($symb);
12106:     $thisurl=&deversion($thisurl);
12107:     $thisfn=&deversion($thisfn);
12108: 
12109:     my %bighash;
12110:     my $okay=0;
12111: 
12112:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12113:                             &GDBM_READER(),0640)) {
12114:         my $noclutter;
12115:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12116:             $thisurl =~ s/\?.+$//;
12117:             if ($map =~ m{^uploaded/.+\.page$}) {
12118:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12119:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12120:                 $noclutter = 1;
12121:             }
12122:         }
12123:         my $ids;
12124:         if ($noclutter) {
12125:             $ids=$bighash{'ids_'.$thisurl};
12126:         } else {
12127:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12128:         }
12129:         unless ($ids) {
12130:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12131:             $ids=$bighash{$idkey};
12132:         }
12133:         if ($ids) {
12134: # ------------------------------------------------------------------- Has ID(s)
12135:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12136:                 $symb =~ s/\?.+$//;
12137:             }
12138: 	    foreach my $id (split(/\,/,$ids)) {
12139: 	       my ($mapid,$resid)=split(/\./,$id);
12140:                if (
12141:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12142:    eq $symb) {
12143:                    if (ref($encstate)) {
12144:                        $$encstate = $bighash{'encrypted_'.$id};
12145:                    }
12146: 		   if (($env{'request.role.adv'}) ||
12147: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12148:                        ($thisurl eq '/adm/navmaps')) {
12149: 		       $okay=1;
12150:                        last;
12151: 		   }
12152: 	       }
12153: 	   }
12154:         }
12155: 	untie(%bighash);
12156:     }
12157:     return $okay;
12158: }
12159: 
12160: # --------------------------------------------------------------- Clean-up symb
12161: 
12162: sub symbclean {
12163:     my $symb=shift;
12164:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12165: # remove version from map
12166:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12167: 
12168: # remove version from URL
12169:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12170: 
12171: # remove wrapper
12172: 
12173:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12174:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12175:     return $symb;
12176: }
12177: 
12178: # ---------------------------------------------- Split symb to find map and url
12179: 
12180: sub encode_symb {
12181:     my ($map,$resid,$url)=@_;
12182:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12183: }
12184: 
12185: sub decode_symb {
12186:     my $symb=shift;
12187:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12188:     my ($map,$resid,$url)=split(/___/,$symb);
12189:     return (&fixversion($map),$resid,&fixversion($url));
12190: }
12191: 
12192: sub fixversion {
12193:     my $fn=shift;
12194:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12195:     my %bighash;
12196:     my $uri=&clutter($fn);
12197:     my $key=$env{'request.course.id'}.'_'.$uri;
12198: # is this cached?
12199:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12200:     if (defined($cached)) { return $result; }
12201: # unfortunately not cached, or expired
12202:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12203: 	    &GDBM_READER(),0640)) {
12204:  	if ($bighash{'version_'.$uri}) {
12205:  	    my $version=$bighash{'version_'.$uri};
12206:  	    unless (($version eq 'mostrecent') || 
12207: 		    ($version==&getversion($uri))) {
12208:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12209:  	    }
12210:  	}
12211:  	untie %bighash;
12212:     }
12213:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12214: }
12215: 
12216: sub deversion {
12217:     my $url=shift;
12218:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12219:     return $url;
12220: }
12221: 
12222: # ------------------------------------------------------ Return symb list entry
12223: 
12224: sub symbread {
12225:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12226:     my $cache_str='request.symbread.cached.'.$thisfn;
12227:     if (defined($env{$cache_str})) {
12228:         if ($ignorecachednull) {
12229:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12230:         } else {
12231:             return $env{$cache_str};
12232:         }
12233:     }
12234: # no filename provided? try from environment
12235:     unless ($thisfn) {
12236:         if ($env{'request.symb'}) {
12237: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12238: 	}
12239: 	$thisfn=$env{'request.filename'};
12240:     }
12241:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12242: # is that filename actually a symb? Verify, clean, and return
12243:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12244: 	if (&symbverify($thisfn,$1)) {
12245: 	    return $env{$cache_str}=&symbclean($thisfn);
12246: 	}
12247:     }
12248:     $thisfn=declutter($thisfn);
12249:     my %hash;
12250:     my %bighash;
12251:     my $syval='';
12252:     if (($env{'request.course.fn'}) && ($thisfn)) {
12253:         my $targetfn = $thisfn;
12254:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12255:             $targetfn = 'adm/wrapper/'.$thisfn;
12256:         }
12257: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12258: 	    $targetfn=$1;
12259: 	}
12260:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12261:                       &GDBM_READER(),0640)) {
12262: 	    $syval=$hash{$targetfn};
12263:             untie(%hash);
12264:         }
12265: # ---------------------------------------------------------- There was an entry
12266:         if ($syval) {
12267: 	    #unless ($syval=~/\_\d+$/) {
12268: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12269: 		    #&appenv({'request.ambiguous' => $thisfn});
12270: 		    #return $env{$cache_str}='';
12271: 		#}    
12272: 		#$syval.=$1;
12273: 	    #}
12274:         } else {
12275: # ------------------------------------------------------- Was not in symb table
12276:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12277:                             &GDBM_READER(),0640)) {
12278: # ---------------------------------------------- Get ID(s) for current resource
12279:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12280:               unless ($ids) { 
12281:                  $ids=$bighash{'ids_/'.$thisfn};
12282:               }
12283:               unless ($ids) {
12284: # alias?
12285: 		  $ids=$bighash{'mapalias_'.$thisfn};
12286:               }
12287:               if ($ids) {
12288: # ------------------------------------------------------------------- Has ID(s)
12289:                  my @possibilities=split(/\,/,$ids);
12290:                  if ($#possibilities==0) {
12291: # ----------------------------------------------- There is only one possibility
12292: 		     my ($mapid,$resid)=split(/\./,$ids);
12293: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12294: 						    $resid,$thisfn);
12295:                      if (ref($possibles) eq 'HASH') {
12296:                          $possibles->{$syval} = 1;    
12297:                      }
12298:                      if ($checkforblock) {
12299:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12300:                          if (@blockers) {
12301:                              $syval = '';
12302:                              return;
12303:                          }
12304:                      }
12305:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12306: # ------------------------------------------ There is more than one possibility
12307:                      my $realpossible=0;
12308:                      foreach my $id (@possibilities) {
12309: 			 my $file=$bighash{'src_'.$id};
12310:                          my $canaccess;
12311:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12312:                              $canaccess = 1;
12313:                          } else { 
12314:                              $canaccess = &allowed('bre',$file);
12315:                          }
12316:                          if ($canaccess) {
12317:          		     my ($mapid,$resid)=split(/\./,$id);
12318:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12319:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12320: 						             $resid,$thisfn);
12321:                                  if (ref($possibles) eq 'HASH') {
12322:                                      $possibles->{$syval} = 1;
12323:                                  }
12324:                                  if ($checkforblock) {
12325:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12326:                                      unless (@blockers > 0) {
12327:                                          $syval = $poss_syval;
12328:                                          $realpossible++;
12329:                                      }
12330:                                  } else {
12331:                                      $syval = $poss_syval;
12332:                                      $realpossible++;
12333:                                  }
12334:                              }
12335: 			 }
12336:                      }
12337: 		     if ($realpossible!=1) { $syval=''; }
12338:                  } else {
12339:                      $syval='';
12340:                  }
12341: 	      }
12342:               untie(%bighash);
12343:            }
12344:         }
12345:         if ($syval) {
12346: 	    return $env{$cache_str}=$syval;
12347:         }
12348:     }
12349:     &appenv({'request.ambiguous' => $thisfn});
12350:     return $env{$cache_str}='';
12351: }
12352: 
12353: # ---------------------------------------------------------- Return random seed
12354: 
12355: sub numval {
12356:     my $txt=shift;
12357:     $txt=~tr/A-J/0-9/;
12358:     $txt=~tr/a-j/0-9/;
12359:     $txt=~tr/K-T/0-9/;
12360:     $txt=~tr/k-t/0-9/;
12361:     $txt=~tr/U-Z/0-5/;
12362:     $txt=~tr/u-z/0-5/;
12363:     $txt=~s/\D//g;
12364:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12365:     return int($txt);
12366: }
12367: 
12368: sub numval2 {
12369:     my $txt=shift;
12370:     $txt=~tr/A-J/0-9/;
12371:     $txt=~tr/a-j/0-9/;
12372:     $txt=~tr/K-T/0-9/;
12373:     $txt=~tr/k-t/0-9/;
12374:     $txt=~tr/U-Z/0-5/;
12375:     $txt=~tr/u-z/0-5/;
12376:     $txt=~s/\D//g;
12377:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12378:     my $total;
12379:     foreach my $val (@txts) { $total+=$val; }
12380:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12381:     return int($total);
12382: }
12383: 
12384: sub numval3 {
12385:     use integer;
12386:     my $txt=shift;
12387:     $txt=~tr/A-J/0-9/;
12388:     $txt=~tr/a-j/0-9/;
12389:     $txt=~tr/K-T/0-9/;
12390:     $txt=~tr/k-t/0-9/;
12391:     $txt=~tr/U-Z/0-5/;
12392:     $txt=~tr/u-z/0-5/;
12393:     $txt=~s/\D//g;
12394:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12395:     my $total;
12396:     foreach my $val (@txts) { $total+=$val; }
12397:     if ($_64bit) { $total=(($total<<32)>>32); }
12398:     return $total;
12399: }
12400: 
12401: sub digest {
12402:     my ($data)=@_;
12403:     my $digest=&Digest::MD5::md5($data);
12404:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12405:     my ($e,$f);
12406:     {
12407:         use integer;
12408:         $e=($a+$b);
12409:         $f=($c+$d);
12410:         if ($_64bit) {
12411:             $e=(($e<<32)>>32);
12412:             $f=(($f<<32)>>32);
12413:         }
12414:     }
12415:     if (wantarray) {
12416: 	return ($e,$f);
12417:     } else {
12418: 	my $g;
12419: 	{
12420: 	    use integer;
12421: 	    $g=($e+$f);
12422: 	    if ($_64bit) {
12423: 		$g=(($g<<32)>>32);
12424: 	    }
12425: 	}
12426: 	return $g;
12427:     }
12428: }
12429: 
12430: sub latest_rnd_algorithm_id {
12431:     return '64bit5';
12432: }
12433: 
12434: sub get_rand_alg {
12435:     my ($courseid)=@_;
12436:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12437:     if ($courseid) {
12438: 	return $env{"course.$courseid.rndseed"};
12439:     }
12440:     return &latest_rnd_algorithm_id();
12441: }
12442: 
12443: sub validCODE {
12444:     my ($CODE)=@_;
12445:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12446:     return 0;
12447: }
12448: 
12449: sub getCODE {
12450:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12451:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12452: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12453: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12454: 	return $Apache::lonhomework::history{'resource.CODE'};
12455:     }
12456:     return undef;
12457: }
12458: #
12459: #  Determines the random seed for a specific context:
12460: #
12461: # parameters:
12462: #   symb      - in course context the symb for the seed.
12463: #   course_id - The course id of the form domain_coursenum.
12464: #   domain    - Domain for the user.
12465: #   course    - Course for the user.
12466: #   cenv      - environment of the course.
12467: #
12468: # NOTE:
12469: #   All parameters are picked out of the environment if missing
12470: #   or not defined.
12471: #   If a symb cannot be determined the current time is used instead.
12472: #
12473: #  For a given well defined symb, courside, domain, username,
12474: #  and course environment, the seed is reproducible.
12475: #
12476: sub rndseed {
12477:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12478:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12479:     if (!defined($symb)) {
12480: 	unless ($symb=$wsymb) { return time; }
12481:     }
12482:     if (!defined $courseid) { 
12483: 	$courseid=$wcourseid; 
12484:     }
12485:     if (!defined $domain) { $domain=$wdomain; }
12486:     if (!defined $username) { $username=$wusername }
12487: 
12488:     my $which;
12489:     if (defined($cenv->{'rndseed'})) {
12490: 	$which = $cenv->{'rndseed'};
12491:     } else {
12492: 	$which =&get_rand_alg($courseid);
12493:     }
12494:     if (defined(&getCODE())) {
12495: 
12496: 	if ($which eq '64bit5') {
12497: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12498: 	} elsif ($which eq '64bit4') {
12499: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12500: 	} else {
12501: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12502: 	}
12503:     } elsif ($which eq '64bit5') {
12504: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12505:     } elsif ($which eq '64bit4') {
12506: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12507:     } elsif ($which eq '64bit3') {
12508: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12509:     } elsif ($which eq '64bit2') {
12510: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12511:     } elsif ($which eq '64bit') {
12512: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12513:     }
12514:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12515: }
12516: 
12517: sub rndseed_32bit {
12518:     my ($symb,$courseid,$domain,$username)=@_;
12519:     {
12520: 	use integer;
12521: 	my $symbchck=unpack("%32C*",$symb) << 27;
12522: 	my $symbseed=numval($symb) << 22;
12523: 	my $namechck=unpack("%32C*",$username) << 17;
12524: 	my $nameseed=numval($username) << 12;
12525: 	my $domainseed=unpack("%32C*",$domain) << 7;
12526: 	my $courseseed=unpack("%32C*",$courseid);
12527: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12528: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12529: 	#&logthis("rndseed :$num:$symb");
12530: 	if ($_64bit) { $num=(($num<<32)>>32); }
12531: 	return $num;
12532:     }
12533: }
12534: 
12535: sub rndseed_64bit {
12536:     my ($symb,$courseid,$domain,$username)=@_;
12537:     {
12538: 	use integer;
12539: 	my $symbchck=unpack("%32S*",$symb) << 21;
12540: 	my $symbseed=numval($symb) << 10;
12541: 	my $namechck=unpack("%32S*",$username);
12542: 	
12543: 	my $nameseed=numval($username) << 21;
12544: 	my $domainseed=unpack("%32S*",$domain) << 10;
12545: 	my $courseseed=unpack("%32S*",$courseid);
12546: 	
12547: 	my $num1=$symbchck+$symbseed+$namechck;
12548: 	my $num2=$nameseed+$domainseed+$courseseed;
12549: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12550: 	#&logthis("rndseed :$num:$symb");
12551: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12552: 	return "$num1,$num2";
12553:     }
12554: }
12555: 
12556: sub rndseed_64bit2 {
12557:     my ($symb,$courseid,$domain,$username)=@_;
12558:     {
12559: 	use integer;
12560: 	# strings need to be an even # of cahracters long, it it is odd the
12561:         # last characters gets thrown away
12562: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12563: 	my $symbseed=numval($symb) << 10;
12564: 	my $namechck=unpack("%32S*",$username.' ');
12565: 	
12566: 	my $nameseed=numval($username) << 21;
12567: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12568: 	my $courseseed=unpack("%32S*",$courseid.' ');
12569: 	
12570: 	my $num1=$symbchck+$symbseed+$namechck;
12571: 	my $num2=$nameseed+$domainseed+$courseseed;
12572: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12573: 	#&logthis("rndseed :$num:$symb");
12574: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12575: 	return "$num1,$num2";
12576:     }
12577: }
12578: 
12579: sub rndseed_64bit3 {
12580:     my ($symb,$courseid,$domain,$username)=@_;
12581:     {
12582: 	use integer;
12583: 	# strings need to be an even # of cahracters long, it it is odd the
12584:         # last characters gets thrown away
12585: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12586: 	my $symbseed=numval2($symb) << 10;
12587: 	my $namechck=unpack("%32S*",$username.' ');
12588: 	
12589: 	my $nameseed=numval2($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 :$num1:$num2:$_64bit");
12597: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12598: 	
12599: 	return "$num1:$num2";
12600:     }
12601: }
12602: 
12603: sub rndseed_64bit4 {
12604:     my ($symb,$courseid,$domain,$username)=@_;
12605:     {
12606: 	use integer;
12607: 	# strings need to be an even # of cahracters long, it it is odd the
12608:         # last characters gets thrown away
12609: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12610: 	my $symbseed=numval3($symb) << 10;
12611: 	my $namechck=unpack("%32S*",$username.' ');
12612: 	
12613: 	my $nameseed=numval3($username) << 21;
12614: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12615: 	my $courseseed=unpack("%32S*",$courseid.' ');
12616: 	
12617: 	my $num1=$symbchck+$symbseed+$namechck;
12618: 	my $num2=$nameseed+$domainseed+$courseseed;
12619: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12620: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12621: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12622: 	
12623: 	return "$num1:$num2";
12624:     }
12625: }
12626: 
12627: sub rndseed_64bit5 {
12628:     my ($symb,$courseid,$domain,$username)=@_;
12629:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12630:     return "$num1:$num2";
12631: }
12632: 
12633: sub rndseed_CODE_64bit {
12634:     my ($symb,$courseid,$domain,$username)=@_;
12635:     {
12636: 	use integer;
12637: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12638: 	my $symbseed=numval2($symb);
12639: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12640: 	my $CODEseed=numval(&getCODE());
12641: 	my $courseseed=unpack("%32S*",$courseid.' ');
12642: 	my $num1=$symbseed+$CODEchck;
12643: 	my $num2=$CODEseed+$courseseed+$symbchck;
12644: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12645: 	#&logthis("rndseed :$num1:$num2:$symb");
12646: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12647: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12648: 	return "$num1:$num2";
12649:     }
12650: }
12651: 
12652: sub rndseed_CODE_64bit4 {
12653:     my ($symb,$courseid,$domain,$username)=@_;
12654:     {
12655: 	use integer;
12656: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12657: 	my $symbseed=numval3($symb);
12658: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12659: 	my $CODEseed=numval3(&getCODE());
12660: 	my $courseseed=unpack("%32S*",$courseid.' ');
12661: 	my $num1=$symbseed+$CODEchck;
12662: 	my $num2=$CODEseed+$courseseed+$symbchck;
12663: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12664: 	#&logthis("rndseed :$num1:$num2:$symb");
12665: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12666: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12667: 	return "$num1:$num2";
12668:     }
12669: }
12670: 
12671: sub rndseed_CODE_64bit5 {
12672:     my ($symb,$courseid,$domain,$username)=@_;
12673:     my $code = &getCODE();
12674:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
12675:     return "$num1:$num2";
12676: }
12677: 
12678: sub setup_random_from_rndseed {
12679:     my ($rndseed)=@_;
12680:     if ($rndseed =~/([,:])/) {
12681:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12682:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12683:             &Math::Random::random_set_seed_from_phrase($rndseed);
12684:         } else {
12685:             &Math::Random::random_set_seed($num1,$num2);
12686:         }
12687:     } else {
12688: 	&Math::Random::random_set_seed_from_phrase($rndseed);
12689:     }
12690: }
12691: 
12692: sub latest_receipt_algorithm_id {
12693:     return 'receipt3';
12694: }
12695: 
12696: sub recunique {
12697:     my $fucourseid=shift;
12698:     my $unique;
12699:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12700: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12701: 	$unique=$env{"course.$fucourseid.internal.encseed"};
12702:     } else {
12703: 	$unique=$perlvar{'lonReceipt'};
12704:     }
12705:     return unpack("%32C*",$unique);
12706: }
12707: 
12708: sub recprefix {
12709:     my $fucourseid=shift;
12710:     my $prefix;
12711:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12712: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12713: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
12714:     } else {
12715: 	$prefix=$perlvar{'lonHostID'};
12716:     }
12717:     return unpack("%32C*",$prefix);
12718: }
12719: 
12720: sub ireceipt {
12721:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
12722: 
12723:     my $return =&recprefix($fucourseid).'-';
12724: 
12725:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12726: 	$env{'request.state'} eq 'construct') {
12727: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12728: 	return $return;
12729:     }
12730: 
12731:     my $cuname=unpack("%32C*",$funame);
12732:     my $cudom=unpack("%32C*",$fudom);
12733:     my $cucourseid=unpack("%32C*",$fucourseid);
12734:     my $cusymb=unpack("%32C*",$fusymb);
12735:     my $cunique=&recunique($fucourseid);
12736:     my $cpart=unpack("%32S*",$part);
12737:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12738: 
12739: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
12740: 			       
12741: 	$return.= ($cunique%$cuname+
12742: 		   $cunique%$cudom+
12743: 		   $cusymb%$cuname+
12744: 		   $cusymb%$cudom+
12745: 		   $cucourseid%$cuname+
12746: 		   $cucourseid%$cudom+
12747: 		   $cpart%$cuname+
12748: 		   $cpart%$cudom);
12749:     } else {
12750: 	$return.= ($cunique%$cuname+
12751: 		   $cunique%$cudom+
12752: 		   $cusymb%$cuname+
12753: 		   $cusymb%$cudom+
12754: 		   $cucourseid%$cuname+
12755: 		   $cucourseid%$cudom);
12756:     }
12757:     return $return;
12758: }
12759: 
12760: sub receipt {
12761:     my ($part)=@_;
12762:     my ($symb,$courseid,$domain,$name) = &whichuser();
12763:     return &ireceipt($name,$domain,$courseid,$symb,$part);
12764: }
12765: 
12766: sub whichuser {
12767:     my ($passedsymb)=@_;
12768:     my ($symb,$courseid,$domain,$name,$publicuser);
12769:     if (defined($env{'form.grade_symb'})) {
12770: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12771: 	my $allowed=&allowed('vgr',$tmp_courseid);
12772: 	if (!$allowed &&
12773: 	    exists($env{'request.course.sec'}) &&
12774: 	    $env{'request.course.sec'} !~ /^\s*$/) {
12775: 	    $allowed=&allowed('vgr',$tmp_courseid.
12776: 			      '/'.$env{'request.course.sec'});
12777: 	}
12778: 	if ($allowed) {
12779: 	    ($symb)=&get_env_multiple('form.grade_symb');
12780: 	    $courseid=$tmp_courseid;
12781: 	    ($domain)=&get_env_multiple('form.grade_domain');
12782: 	    ($name)=&get_env_multiple('form.grade_username');
12783: 	    return ($symb,$courseid,$domain,$name,$publicuser);
12784: 	}
12785:     }
12786:     if (!$passedsymb) {
12787: 	$symb=&symbread();
12788:     } else {
12789: 	$symb=$passedsymb;
12790:     }
12791:     $courseid=$env{'request.course.id'};
12792:     $domain=$env{'user.domain'};
12793:     $name=$env{'user.name'};
12794:     if ($name eq 'public' && $domain eq 'public') {
12795: 	if (!defined($env{'form.username'})) {
12796: 	    $env{'form.username'}.=time.rand(10000000);
12797: 	}
12798: 	$name.=$env{'form.username'};
12799:     }
12800:     return ($symb,$courseid,$domain,$name,$publicuser);
12801: 
12802: }
12803: 
12804: # ------------------------------------------------------------ Serves up a file
12805: # returns either the contents of the file or 
12806: # -1 if the file doesn't exist
12807: #
12808: # if the target is a file that was uploaded via DOCS, 
12809: # a check will be made to see if a current copy exists on the local server,
12810: # if it does this will be served, otherwise a copy will be retrieved from
12811: # the home server for the course and stored in /home/httpd/html/userfiles on
12812: # the local server.   
12813: 
12814: sub getfile {
12815:     my ($file) = @_;
12816:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
12817:     &repcopy($file);
12818:     return &readfile($file);
12819: }
12820: 
12821: sub repcopy_userfile {
12822:     my ($file)=@_;
12823:     my $londocroot = $perlvar{'lonDocRoot'};
12824:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
12825:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
12826:     my ($cdom,$cnum,$filename) = 
12827: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
12828:     my $uri="/uploaded/$cdom/$cnum/$filename";
12829:     if (-e "$file") {
12830: # we already have a local copy, check it out
12831: 	my @fileinfo = stat($file);
12832: 	my $rtncode;
12833: 	my $info;
12834: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
12835: 	if ($lwpresp ne 'ok') {
12836: # there is no such file anymore, even though we had a local copy
12837: 	    if ($rtncode eq '404') {
12838: 		unlink($file);
12839: 	    }
12840: 	    return -1;
12841: 	}
12842: 	if ($info < $fileinfo[9]) {
12843: # nice, the file we have is up-to-date, just say okay
12844: 	    return 'ok';
12845: 	} else {
12846: # the file is outdated, get rid of it
12847: 	    unlink($file);
12848: 	}
12849:     }
12850: # one way or the other, at this point, we don't have the file
12851: # construct the correct path for the file
12852:     my @parts = ($cdom,$cnum); 
12853:     if ($filename =~ m|^(.+)/[^/]+$|) {
12854: 	push @parts, split(/\//,$1);
12855:     }
12856:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12857:     foreach my $part (@parts) {
12858: 	$path .= '/'.$part;
12859: 	if (!-e $path) {
12860: 	    mkdir($path,0770);
12861: 	}
12862:     }
12863: # now the path exists for sure
12864: # get a user agent
12865:     my $transferfile=$file.'.in.transfer';
12866: # FIXME: this should flock
12867:     if (-e $transferfile) { return 'ok'; }
12868:     my $request;
12869:     $uri=~s/^\///;
12870:     my $homeserver = &homeserver($cnum,$cdom);
12871:     my $protocol = $protocol{$homeserver};
12872:     $protocol = 'http' if ($protocol ne 'https');
12873:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
12874:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
12875: # did it work?
12876:     if ($response->is_error()) {
12877: 	unlink($transferfile);
12878: 	&logthis("Userfile repcopy failed for $uri");
12879: 	return -1;
12880:     }
12881: # worked, rename the transfer file
12882:     rename($transferfile,$file);
12883:     return 'ok';
12884: }
12885: 
12886: sub tokenwrapper {
12887:     my $uri=shift;
12888:     $uri=~s|^https?\://([^/]+)||;
12889:     $uri=~s|^/||;
12890:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
12891:     my $token=$1;
12892:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
12893:     if ($udom && $uname && $file) {
12894: 	$file=~s|(\?\.*)*$||;
12895:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
12896:         my $homeserver = &homeserver($uname,$udom);
12897:         my $protocol = $protocol{$homeserver};
12898:         $protocol = 'http' if ($protocol ne 'https');
12899:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
12900:                (($uri=~/\?/)?'&':'?').'token='.$token.
12901:                                '&tokenissued='.$perlvar{'lonHostID'};
12902:     } else {
12903:         return '/adm/notfound.html';
12904:     }
12905: }
12906: 
12907: # call with reqtype HEAD: get last modification time
12908: # call with reqtype GET: get the file contents
12909: # Do not call this with reqtype GET for large files! It loads everything into memory
12910: #
12911: sub getuploaded {
12912:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12913:     $uri=~s/^\///;
12914:     my $homeserver = &homeserver($cnum,$cdom);
12915:     my $protocol = $protocol{$homeserver};
12916:     $protocol = 'http' if ($protocol ne 'https');
12917:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
12918:     my $request=new HTTP::Request($reqtype,$uri);
12919:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
12920:     $$rtncode = $response->code;
12921:     if (! $response->is_success()) {
12922: 	return 'failed';
12923:     }      
12924:     if ($reqtype eq 'HEAD') {
12925: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
12926:     } elsif ($reqtype eq 'GET') {
12927: 	$$info = $response->content;
12928:     }
12929:     return 'ok';
12930: }
12931: 
12932: sub readfile {
12933:     my $file = shift;
12934:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
12935:     my $fh;
12936:     open($fh,"<$file");
12937:     my $a='';
12938:     while (my $line = <$fh>) { $a .= $line; }
12939:     return $a;
12940: }
12941: 
12942: sub filelocation {
12943:     my ($dir,$file) = @_;
12944:     my $location;
12945:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
12946: 
12947:     if ($file =~ m-^/adm/-) {
12948: 	$file=~s-^/adm/wrapper/-/-;
12949: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
12950:     }
12951: 
12952:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
12953:         $location = $file;
12954:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
12955:         my ($udom,$uname,$filename)=
12956:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
12957:         my $home=&homeserver($uname,$udom);
12958:         my $is_me=0;
12959:         my @ids=&current_machine_ids();
12960:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12961:         if ($is_me) {
12962:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
12963:         } else {
12964:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12965:   	      $udom.'/'.$uname.'/'.$filename;
12966:         }
12967:     } elsif ($file =~ m-^/adm/-) {
12968: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
12969:     } else {
12970:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
12971:         $file=~s:^/(res|priv)/:/:;
12972:         my $space=$1;
12973:         if ( !( $file =~ m:^/:) ) {
12974:             $location = $dir. '/'.$file;
12975:         } else {
12976:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
12977:         }
12978:     }
12979:     $location=~s://+:/:g; # remove duplicate /
12980:     while ($location=~m{/\.\./}) {
12981: 	if ($location =~ m{/[^/]+/\.\./}) {
12982: 	    $location=~ s{/[^/]+/\.\./}{/}g;
12983: 	} else {
12984: 	    $location=~ s{/\.\./}{/}g;
12985: 	}
12986:     } #remove dir/..
12987:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12988:     return $location;
12989: }
12990: 
12991: sub hreflocation {
12992:     my ($dir,$file)=@_;
12993:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
12994: 	$file=filelocation($dir,$file);
12995:     } elsif ($file=~m-^/adm/-) {
12996: 	$file=~s-^/adm/wrapper/-/-;
12997: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
12998:     }
12999:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13000: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13001:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13002: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13003: 	        {/uploaded/$1/$2/}x;
13004:     }
13005:     if ($file=~ m{^/userfiles/}) {
13006: 	$file =~ s{^/userfiles/}{/uploaded/};
13007:     }
13008:     return $file;
13009: }
13010: 
13011: 
13012: 
13013: 
13014: 
13015: sub current_machine_domains {
13016:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13017: }
13018: 
13019: sub machine_domains {
13020:     my ($hostname) = @_;
13021:     my @domains;
13022:     my %hostname = &all_hostnames();
13023:     while( my($id, $name) = each(%hostname)) {
13024: #	&logthis("-$id-$name-$hostname-");
13025: 	if ($hostname eq $name) {
13026: 	    push(@domains,&host_domain($id));
13027: 	}
13028:     }
13029:     return @domains;
13030: }
13031: 
13032: sub current_machine_ids {
13033:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13034: }
13035: 
13036: sub machine_ids {
13037:     my ($hostname) = @_;
13038:     $hostname ||= &hostname($perlvar{'lonHostID'});
13039:     my @ids;
13040:     my %name_to_host = &all_names();
13041:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13042: 	return @{ $name_to_host{$hostname} };
13043:     }
13044:     return;
13045: }
13046: 
13047: sub additional_machine_domains {
13048:     my @domains;
13049:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
13050:     while( my $line = <$fh>) {
13051:         $line =~ s/\s//g;
13052:         push(@domains,$line);
13053:     }
13054:     return @domains;
13055: }
13056: 
13057: sub default_login_domain {
13058:     my $domain = $perlvar{'lonDefDomain'};
13059:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13060:     foreach my $posdom (&current_machine_domains(),
13061:                         &additional_machine_domains()) {
13062:         if (lc($posdom) eq lc($testdomain)) {
13063:             $domain=$posdom;
13064:             last;
13065:         }
13066:     }
13067:     return $domain;
13068: }
13069: 
13070: # ------------------------------------------------------------- Declutters URLs
13071: 
13072: sub declutter {
13073:     my $thisfn=shift;
13074:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13075:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13076:         $thisfn=~s{^/home/httpd/html}{};
13077:     }
13078:     $thisfn=~s/^\///;
13079:     $thisfn=~s|^adm/wrapper/||;
13080:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13081:     $thisfn=~s/^res\///;
13082:     $thisfn=~s/^priv\///;
13083:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13084:         $thisfn=~s/\?.+$//;
13085:     }
13086:     return $thisfn;
13087: }
13088: 
13089: # ------------------------------------------------------------- Clutter up URLs
13090: 
13091: sub clutter {
13092:     my $thisfn='/'.&declutter(shift);
13093:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13094: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13095:        $thisfn='/res'.$thisfn; 
13096:     }
13097:     if ($thisfn !~m|^/adm|) {
13098: 	if ($thisfn =~ m|^/ext/|) {
13099: 	    $thisfn='/adm/wrapper'.$thisfn;
13100: 	} else {
13101: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13102: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13103: 	    if ($embstyle eq 'ssi'
13104: 		|| ($embstyle eq 'hdn')
13105: 		|| ($embstyle eq 'rat')
13106: 		|| ($embstyle eq 'prv')
13107: 		|| ($embstyle eq 'ign')) {
13108: 		#do nothing with these
13109: 	    } elsif (($embstyle eq 'img') 
13110: 		|| ($embstyle eq 'emb')
13111: 		|| ($embstyle eq 'wrp')) {
13112: 		$thisfn='/adm/wrapper'.$thisfn;
13113: 	    } elsif ($embstyle eq 'unk'
13114: 		     && $thisfn!~/\.(sequence|page)$/) {
13115: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13116: 	    } else {
13117: #		&logthis("Got a blank emb style");
13118: 	    }
13119: 	}
13120:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13121:         $thisfn='/adm/wrapper'.$thisfn;
13122:     }
13123:     return $thisfn;
13124: }
13125: 
13126: sub clutter_with_no_wrapper {
13127:     my $uri = &clutter(shift);
13128:     if ($uri =~ m-^/adm/-) {
13129: 	$uri =~ s-^/adm/wrapper/-/-;
13130: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13131:     }
13132:     return $uri;
13133: }
13134: 
13135: sub freeze_escape {
13136:     my ($value)=@_;
13137:     if (ref($value)) {
13138: 	$value=&nfreeze($value);
13139: 	return '__FROZEN__'.&escape($value);
13140:     }
13141:     return &escape($value);
13142: }
13143: 
13144: 
13145: sub thaw_unescape {
13146:     my ($value)=@_;
13147:     if ($value =~ /^__FROZEN__/) {
13148: 	substr($value,0,10,undef);
13149: 	$value=&unescape($value);
13150: 	return &thaw($value);
13151:     }
13152:     return &unescape($value);
13153: }
13154: 
13155: sub correct_line_ends {
13156:     my ($result)=@_;
13157:     $$result =~s/\r\n/\n/mg;
13158:     $$result =~s/\r/\n/mg;
13159: }
13160: # ================================================================ Main Program
13161: 
13162: sub goodbye {
13163:    &logthis("Starting Shut down");
13164: #not converted to using infrastruture and probably shouldn't be
13165:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13166: #converted
13167: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13168:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13169: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13170: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13171: #1.1 only
13172: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13173: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13174: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13175: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13176:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13177:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13178:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13179:    &flushcourselogs();
13180:    &logthis("Shutting down");
13181: }
13182: 
13183: sub get_dns {
13184:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13185:     if (!$ignore_cache) {
13186: 	my ($content,$cached)=
13187: 	    &Apache::lonnet::is_cached_new('dns',$url);
13188: 	if ($cached) {
13189: 	    &$func($content,$hashref);
13190: 	    return;
13191: 	}
13192:     }
13193: 
13194:     my %alldns;
13195:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13196:     foreach my $dns (<$config>) {
13197: 	next if ($dns !~ /^\^(\S*)/x);
13198:         my $line = $1;
13199:         my ($host,$protocol) = split(/:/,$line);
13200:         if ($protocol ne 'https') {
13201:             $protocol = 'http';
13202:         }
13203: 	$alldns{$host} = $protocol;
13204:     }
13205:     while (%alldns) {
13206: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13207: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13208:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13209:         delete($alldns{$dns});
13210: 	next if ($response->is_error());
13211: 	my @content = split("\n",$response->content);
13212: 	unless ($nocache) {
13213: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
13214: 	}
13215: 	&$func(\@content,$hashref);
13216: 	return;
13217:     }
13218:     close($config);
13219:     my $which = (split('/',$url))[3];
13220:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13221:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
13222:     my @content = <$config>;
13223:     &$func(\@content,$hashref);
13224:     return;
13225: }
13226: 
13227: # ------------------------------------------------------Get DNS checksums file
13228: sub parse_dns_checksums_tab {
13229:     my ($lines,$hashref) = @_;
13230:     my $lonhost = $perlvar{'lonHostID'};
13231:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13232:     my $loncaparev = &get_server_loncaparev($machine_dom);
13233:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13234:     my $webconfdir = '/etc/httpd/conf';
13235:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13236:         $webconfdir = '/etc/apache2';
13237:     } elsif ($distro =~ /^sles(\d+)$/) {
13238:         if ($1 >= 10) {
13239:             $webconfdir = '/etc/apache2';
13240:         }
13241:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13242:         if ($1 >= 10.0) {
13243:             $webconfdir = '/etc/apache2';
13244:         }
13245:     }
13246:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13247:     my (%chksum,%revnum);
13248:     if (ref($lines) eq 'ARRAY') {
13249:         chomp(@{$lines});
13250:         my $version = shift(@{$lines});
13251:         if ($version eq $release) {  
13252:             foreach my $line (@{$lines}) {
13253:                 my ($file,$version,$shasum) = split(/,/,$line);
13254:                 if ($file =~ m{^/etc/httpd/conf}) {
13255:                     if ($webconfdir eq '/etc/apache2') {
13256:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13257:                     }
13258:                 }
13259:                 $chksum{$file} = $shasum;
13260:                 $revnum{$file} = $version;
13261:             }
13262:             if (ref($hashref) eq 'HASH') {
13263:                 %{$hashref} = (
13264:                                 sums     => \%chksum,
13265:                                 versions => \%revnum,
13266:                               );
13267:             }
13268:         }
13269:     }
13270:     return;
13271: }
13272: 
13273: sub fetch_dns_checksums {
13274:     my %checksums;
13275:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13276:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13277:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13278:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13279:              \%checksums);
13280:     return \%checksums;
13281: }
13282: 
13283: # ------------------------------------------------------------ Read domain file
13284: {
13285:     my $loaded;
13286:     my %domain;
13287: 
13288:     sub parse_domain_tab {
13289: 	my ($lines) = @_;
13290: 	foreach my $line (@$lines) {
13291: 	    next if ($line =~ /^(\#|\s*$ )/x);
13292: 
13293: 	    chomp($line);
13294: 	    my ($name,@elements) = split(/:/,$line,9);
13295: 	    my %this_domain;
13296: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13297: 			       'lang_def', 'city', 'longi', 'lati',
13298: 			       'primary') {
13299: 		$this_domain{$field} = shift(@elements);
13300: 	    }
13301: 	    $domain{$name} = \%this_domain;
13302: 	}
13303:     }
13304: 
13305:     sub reset_domain_info {
13306: 	undef($loaded);
13307: 	undef(%domain);
13308:     }
13309: 
13310:     sub load_domain_tab {
13311: 	my ($ignore_cache,$nocache) = @_;
13312: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13313: 	my $fh;
13314: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
13315: 	    my @lines = <$fh>;
13316: 	    &parse_domain_tab(\@lines);
13317: 	}
13318: 	close($fh);
13319: 	$loaded = 1;
13320:     }
13321: 
13322:     sub domain {
13323: 	&load_domain_tab() if (!$loaded);
13324: 
13325: 	my ($name,$what) = @_;
13326: 	return if ( !exists($domain{$name}) );
13327: 
13328: 	if (!$what) {
13329: 	    return $domain{$name}{'description'};
13330: 	}
13331: 	return $domain{$name}{$what};
13332:     }
13333: 
13334:     sub domain_info {
13335:         &load_domain_tab() if (!$loaded);
13336:         return %domain;
13337:     }
13338: 
13339: }
13340: 
13341: 
13342: # ------------------------------------------------------------- Read hosts file
13343: {
13344:     my %hostname;
13345:     my %hostdom;
13346:     my %libserv;
13347:     my $loaded;
13348:     my %name_to_host;
13349:     my %internetdom;
13350:     my %LC_dns_serv;
13351: 
13352:     sub parse_hosts_tab {
13353: 	my ($file) = @_;
13354: 	foreach my $configline (@$file) {
13355: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13356:             chomp($configline);
13357: 	    if ($configline =~ /^\^/) {
13358:                 if ($configline =~ /^\^([\w.\-]+)/) {
13359:                     $LC_dns_serv{$1} = 1;
13360:                 }
13361:                 next;
13362:             }
13363: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13364: 	    $name=~s/\s//g;
13365: 	    if ($id && $domain && $role && $name) {
13366: 		$hostname{$id}=$name;
13367: 		push(@{$name_to_host{$name}}, $id);
13368: 		$hostdom{$id}=$domain;
13369: 		if ($role eq 'library') { $libserv{$id}=$name; }
13370:                 if (defined($protocol)) {
13371:                     if ($protocol eq 'https') {
13372:                         $protocol{$id} = $protocol;
13373:                     } else {
13374:                         $protocol{$id} = 'http'; 
13375:                     }
13376:                 } else {
13377:                     $protocol{$id} = 'http';
13378:                 }
13379:                 if (defined($intdom)) {
13380:                     $internetdom{$id} = $intdom;
13381:                 }
13382: 	    }
13383: 	}
13384:     }
13385:     
13386:     sub reset_hosts_info {
13387: 	&purge_remembered();
13388: 	&reset_domain_info();
13389: 	&reset_hosts_ip_info();
13390:         undef(%internetdom);
13391: 	undef(%name_to_host);
13392: 	undef(%hostname);
13393: 	undef(%hostdom);
13394: 	undef(%libserv);
13395: 	undef($loaded);
13396:     }
13397: 
13398:     sub load_hosts_tab {
13399: 	my ($ignore_cache,$nocache) = @_;
13400: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13401: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13402: 	my @config = <$config>;
13403: 	&parse_hosts_tab(\@config);
13404: 	close($config);
13405: 	$loaded=1;
13406:     }
13407: 
13408:     sub hostname {
13409: 	&load_hosts_tab() if (!$loaded);
13410: 
13411: 	my ($lonid) = @_;
13412: 	return $hostname{$lonid};
13413:     }
13414: 
13415:     sub all_hostnames {
13416: 	&load_hosts_tab() if (!$loaded);
13417: 
13418: 	return %hostname;
13419:     }
13420: 
13421:     sub all_names {
13422:         my ($ignore_cache,$nocache) = @_;
13423: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13424: 
13425: 	return %name_to_host;
13426:     }
13427: 
13428:     sub all_host_domain {
13429:         &load_hosts_tab() if (!$loaded);
13430:         return %hostdom;
13431:     }
13432: 
13433:     sub all_host_intdom {
13434:         &load_hosts_tab() if (!$loaded);
13435:         return %internetdom;
13436:     }
13437: 
13438:     sub is_library {
13439: 	&load_hosts_tab() if (!$loaded);
13440: 
13441: 	return exists($libserv{$_[0]});
13442:     }
13443: 
13444:     sub all_library {
13445: 	&load_hosts_tab() if (!$loaded);
13446: 
13447: 	return %libserv;
13448:     }
13449: 
13450:     sub unique_library {
13451: 	#2x reverse removes all hostnames that appear more than once
13452:         my %unique = reverse &all_library();
13453:         return reverse %unique;
13454:     }
13455: 
13456:     sub get_servers {
13457: 	&load_hosts_tab() if (!$loaded);
13458: 
13459: 	my ($domain,$type) = @_;
13460: 	my %possible_hosts = ($type eq 'library') ? %libserv
13461: 	                                          : %hostname;
13462: 	my %result;
13463: 	if (ref($domain) eq 'ARRAY') {
13464: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13465: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13466: 		    $result{$host} = $hostname;
13467: 		}
13468: 	    }
13469: 	} else {
13470: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13471: 		if ($hostdom{$host} eq $domain) {
13472: 		    $result{$host} = $hostname;
13473: 		}
13474: 	    }
13475: 	}
13476: 	return %result;
13477:     }
13478: 
13479:     sub get_unique_servers {
13480:         my %unique = reverse &get_servers(@_);
13481: 	return reverse %unique;
13482:     }
13483: 
13484:     sub host_domain {
13485: 	&load_hosts_tab() if (!$loaded);
13486: 
13487: 	my ($lonid) = @_;
13488: 	return $hostdom{$lonid};
13489:     }
13490: 
13491:     sub all_domains {
13492: 	&load_hosts_tab() if (!$loaded);
13493: 
13494: 	my %seen;
13495: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13496: 	return @uniq;
13497:     }
13498: 
13499:     sub internet_dom {
13500:         &load_hosts_tab() if (!$loaded);
13501: 
13502:         my ($lonid) = @_;
13503:         return $internetdom{$lonid};
13504:     }
13505: 
13506:     sub is_LC_dns {
13507:         &load_hosts_tab() if (!$loaded);
13508: 
13509:         my ($hostname) = @_;
13510:         return exists($LC_dns_serv{$hostname});
13511:     }
13512: 
13513: }
13514: 
13515: { 
13516:     my %iphost;
13517:     my %name_to_ip;
13518:     my %lonid_to_ip;
13519: 
13520:     sub get_hosts_from_ip {
13521: 	my ($ip) = @_;
13522: 	my %iphosts = &get_iphost();
13523: 	if (ref($iphosts{$ip})) {
13524: 	    return @{$iphosts{$ip}};
13525: 	}
13526: 	return;
13527:     }
13528:     
13529:     sub reset_hosts_ip_info {
13530: 	undef(%iphost);
13531: 	undef(%name_to_ip);
13532: 	undef(%lonid_to_ip);
13533:     }
13534: 
13535:     sub get_host_ip {
13536: 	my ($lonid) = @_;
13537: 	if (exists($lonid_to_ip{$lonid})) {
13538: 	    return $lonid_to_ip{$lonid};
13539: 	}
13540: 	my $name=&hostname($lonid);
13541:    	my $ip = gethostbyname($name);
13542: 	return if (!$ip || length($ip) ne 4);
13543: 	$ip=inet_ntoa($ip);
13544: 	$name_to_ip{$name}   = $ip;
13545: 	$lonid_to_ip{$lonid} = $ip;
13546: 	return $ip;
13547:     }
13548:     
13549:     sub get_iphost {
13550: 	my ($ignore_cache,$nocache) = @_;
13551: 
13552: 	if (!$ignore_cache) {
13553: 	    if (%iphost) {
13554: 		return %iphost;
13555: 	    }
13556: 	    my ($ip_info,$cached)=
13557: 		&Apache::lonnet::is_cached_new('iphost','iphost');
13558: 	    if ($cached) {
13559: 		%iphost      = %{$ip_info->[0]};
13560: 		%name_to_ip  = %{$ip_info->[1]};
13561: 		%lonid_to_ip = %{$ip_info->[2]};
13562: 		return %iphost;
13563: 	    }
13564: 	}
13565: 
13566: 	# get yesterday's info for fallback
13567: 	my %old_name_to_ip;
13568: 	my ($ip_info,$cached)=
13569: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
13570: 	if ($cached) {
13571: 	    %old_name_to_ip = %{$ip_info->[1]};
13572: 	}
13573: 
13574: 	my %name_to_host = &all_names($ignore_cache,$nocache);
13575: 	foreach my $name (keys(%name_to_host)) {
13576: 	    my $ip;
13577: 	    if (!exists($name_to_ip{$name})) {
13578: 		$ip = gethostbyname($name);
13579: 		if (!$ip || length($ip) ne 4) {
13580: 		    if (defined($old_name_to_ip{$name})) {
13581: 			$ip = $old_name_to_ip{$name};
13582: 			&logthis("Can't find $name defaulting to old $ip");
13583: 		    } else {
13584: 			&logthis("Name $name no IP found");
13585: 			next;
13586: 		    }
13587: 		} else {
13588: 		    $ip=inet_ntoa($ip);
13589: 		}
13590: 		$name_to_ip{$name} = $ip;
13591: 	    } else {
13592: 		$ip = $name_to_ip{$name};
13593: 	    }
13594: 	    foreach my $id (@{ $name_to_host{$name} }) {
13595: 		$lonid_to_ip{$id} = $ip;
13596: 	    }
13597: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
13598: 	}
13599:         unless ($nocache) {
13600: 	    &do_cache_new('iphost','iphost',
13601: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
13602: 		          48*60*60);
13603:         }
13604: 
13605: 	return %iphost;
13606:     }
13607: 
13608:     #
13609:     #  Given a DNS returns the loncapa host name for that DNS 
13610:     # 
13611:     sub host_from_dns {
13612:         my ($dns) = @_;
13613:         my @hosts;
13614:         my $ip;
13615: 
13616:         if (exists($name_to_ip{$dns})) {
13617:             $ip = $name_to_ip{$dns};
13618:         }
13619:         if (!$ip) {
13620:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13621:             if (length($ip) == 4) { 
13622: 	        $ip   = &IO::Socket::inet_ntoa($ip);
13623:             }
13624:         }
13625:         if ($ip) {
13626: 	    @hosts = get_hosts_from_ip($ip);
13627: 	    return $hosts[0];
13628:         }
13629:         return undef;
13630:     }
13631: 
13632:     sub get_internet_names {
13633:         my ($lonid) = @_;
13634:         return if ($lonid eq '');
13635:         my ($idnref,$cached)=
13636:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
13637:         if ($cached) {
13638:             return $idnref;
13639:         }
13640:         my $ip = &get_host_ip($lonid);
13641:         my @hosts = &get_hosts_from_ip($ip);
13642:         my %iphost = &get_iphost();
13643:         my (@idns,%seen);
13644:         foreach my $id (@hosts) {
13645:             my $dom = &host_domain($id);
13646:             my $prim_id = &domain($dom,'primary');
13647:             my $prim_ip = &get_host_ip($prim_id);
13648:             next if ($seen{$prim_ip});
13649:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13650:                 foreach my $id (@{$iphost{$prim_ip}}) {
13651:                     my $intdom = &internet_dom($id);
13652:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
13653:                         push(@idns,$intdom);
13654:                     }
13655:                 }
13656:             }
13657:             $seen{$prim_ip} = 1;
13658:         }
13659:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
13660:     }
13661: 
13662: }
13663: 
13664: sub all_loncaparevs {
13665:     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);
13666: }
13667: 
13668: # ---------------------------------------------------------- Read loncaparev table
13669: {
13670:     sub load_loncaparevs { 
13671:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13672:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13673:                 while (my $configline=<$config>) {
13674:                     chomp($configline);
13675:                     my ($hostid,$loncaparev)=split(/:/,$configline);
13676:                     $loncaparevs{$hostid}=$loncaparev;
13677:                 }
13678:                 close($config);
13679:             }
13680:         }
13681:     }
13682: }
13683: 
13684: # ---------------------------------------------------------- Read serverhostID table
13685: {
13686:     sub load_serverhomeIDs {
13687:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13688:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13689:                 while (my $configline=<$config>) {
13690:                     chomp($configline);
13691:                     my ($name,$id)=split(/:/,$configline);
13692:                     $serverhomeIDs{$name}=$id;
13693:                 }
13694:                 close($config);
13695:             }
13696:         }
13697:     }
13698: }
13699: 
13700: 
13701: BEGIN {
13702: 
13703: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13704:     unless ($readit) {
13705: {
13706:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13707:     %perlvar = (%perlvar,%{$configvars});
13708: }
13709: 
13710: 
13711: # ------------------------------------------------------ Read spare server file
13712: {
13713:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
13714: 
13715:     while (my $configline=<$config>) {
13716:        chomp($configline);
13717:        if ($configline) {
13718: 	   my ($host,$type) = split(':',$configline,2);
13719: 	   if (!defined($type) || $type eq '') { $type = 'default' };
13720: 	   push(@{ $spareid{$type} }, $host);
13721:        }
13722:     }
13723:     close($config);
13724: }
13725: # ------------------------------------------------------------ Read permissions
13726: {
13727:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
13728: 
13729:     while (my $configline=<$config>) {
13730: 	chomp($configline);
13731: 	if ($configline) {
13732: 	    my ($role,$perm)=split(/ /,$configline);
13733: 	    if ($perm ne '') { $pr{$role}=$perm; }
13734: 	}
13735:     }
13736:     close($config);
13737: }
13738: 
13739: # -------------------------------------------- Read plain texts for permissions
13740: {
13741:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
13742: 
13743:     while (my $configline=<$config>) {
13744: 	chomp($configline);
13745: 	if ($configline) {
13746: 	    my ($short,@plain)=split(/:/,$configline);
13747:             %{$prp{$short}} = ();
13748: 	    if (@plain > 0) {
13749:                 $prp{$short}{'std'} = $plain[0];
13750:                 for (my $i=1; $i<@plain; $i++) {
13751:                     $prp{$short}{'alt'.$i} = $plain[$i];  
13752:                 }
13753:             }
13754: 	}
13755:     }
13756:     close($config);
13757: }
13758: 
13759: # ---------------------------------------------------------- Read package table
13760: {
13761:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
13762: 
13763:     while (my $configline=<$config>) {
13764: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
13765: 	chomp($configline);
13766: 	my ($short,$plain)=split(/:/,$configline);
13767: 	my ($pack,$name)=split(/\&/,$short);
13768: 	if ($plain ne '') {
13769: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
13770: 	    $packagetab{$short}=$plain; 
13771: 	}
13772:     }
13773:     close($config);
13774: }
13775: 
13776: # ---------------------------------------------------------- Read loncaparev table
13777: 
13778: &load_loncaparevs();
13779: 
13780: # ---------------------------------------------------------- Read serverhostID table
13781: 
13782: &load_serverhomeIDs();
13783: 
13784: # ---------------------------------------------------------- Read releaseslist XML
13785: {
13786:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13787:     if (-e $file) {
13788:         my $parser = HTML::LCParser->new($file);
13789:         while (my $token = $parser->get_token()) {
13790:             if ($token->[0] eq 'S') {
13791:                 my $item = $token->[1];
13792:                 my $name = $token->[2]{'name'};
13793:                 my $value = $token->[2]{'value'};
13794:                 my $valuematch = $token->[2]{'valuematch'};
13795:                 my $namematch = $token->[2]{'namematch'};
13796:                 if ($item eq 'parameter') {
13797:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13798:                         my $release = $parser->get_text();
13799:                         $release =~ s/(^\s*|\s*$ )//gx;
13800:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13801:                     }
13802:                 } elsif ($item ne '' && $name ne '') {
13803:                     my $release = $parser->get_text();
13804:                     $release =~ s/(^\s*|\s*$ )//gx;
13805:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
13806:                 }
13807:             }
13808:         }
13809:     }
13810: }
13811: 
13812: # ---------------------------------------------------------- Read managers table
13813: {
13814:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13815:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13816:             while (my $configline=<$config>) {
13817:                 chomp($configline);
13818:                 next if ($configline =~ /^\#/);
13819:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13820:                     $managerstab{$configline} = 1;
13821:                 }
13822:             }
13823:             close($config);
13824:         }
13825:     }
13826: }
13827: 
13828: # ------------- set up temporary directory
13829: {
13830:     $tmpdir = LONCAPA::tempdir();
13831: 
13832: }
13833: 
13834: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
13835: 				'compress_threshold'=> 20_000,
13836:  			        });
13837: 
13838: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
13839: $dumpcount=0;
13840: $locknum=0;
13841: 
13842: &logtouch();
13843: &logthis('<font color="yellow">INFO: Read configuration</font>');
13844: $readit=1;
13845:     {
13846: 	use integer;
13847: 	my $test=(2**32)+1;
13848: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
13849: 	&logthis(" Detected 64bit platform ($_64bit)");
13850:     }
13851: }
13852: }
13853: 
13854: 1;
13855: __END__
13856: 
13857: =pod
13858: 
13859: =head1 NAME
13860: 
13861: Apache::lonnet - Subroutines to ask questions about things in the network.
13862: 
13863: =head1 SYNOPSIS
13864: 
13865: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
13866: 
13867:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13868: 
13869: Common parameters:
13870: 
13871: =over 4
13872: 
13873: =item *
13874: 
13875: $uname : an internal username (if $cname expecting a course Id specifically)
13876: 
13877: =item *
13878: 
13879: $udom : a domain (if $cdom expecting a course's domain specifically)
13880: 
13881: =item *
13882: 
13883: $symb : a resource instance identifier
13884: 
13885: =item *
13886: 
13887: $namespace : the name of a .db file that contains the data needed or
13888: being set.
13889: 
13890: =back
13891: 
13892: =head1 OVERVIEW
13893: 
13894: lonnet provides subroutines which interact with the
13895: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13896: about classes, users, and resources.
13897: 
13898: For many of these objects you can also use this to store data about
13899: them or modify them in various ways.
13900: 
13901: =head2 Symbs
13902: 
13903: To identify a specific instance of a resource, LON-CAPA uses symbols
13904: or "symbs"X<symb>. These identifiers are built from the URL of the
13905: map, the resource number of the resource in the map, and the URL of
13906: the resource itself. The latter is somewhat redundant, but might help
13907: if maps change.
13908: 
13909: An example is
13910: 
13911:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13912: 
13913: The respective map entry is
13914: 
13915:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
13916:   title="Problem 2">
13917:  </resource>
13918: 
13919: Symbs are used by the random number generator, as well as to store and
13920: restore data specific to a certain instance of for example a problem.
13921: 
13922: =head2 Storing And Retrieving Data
13923: 
13924: X<store()>X<cstore()>X<restore()>Three of the most important functions
13925: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13926: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13927: is is the non-critical message twin of cstore. These functions are for
13928: handlers to store a perl hash to a user's permanent data space in an
13929: easy manner, and to retrieve it again on another call. It is expected
13930: that a handler would use this once at the beginning to retrieve data,
13931: and then again once at the end to send only the new data back.
13932: 
13933: The data is stored in the user's data directory on the user's
13934: homeserver under the ID of the course.
13935: 
13936: The hash that is returned by restore will have all of the previous
13937: value for all of the elements of the hash.
13938: 
13939: Example:
13940: 
13941:  #creating a hash
13942:  my %hash;
13943:  $hash{'foo'}='bar';
13944: 
13945:  #storing it
13946:  &Apache::lonnet::cstore(\%hash);
13947: 
13948:  #changing a value
13949:  $hash{'foo'}='notbar';
13950: 
13951:  #adding a new value
13952:  $hash{'bar'}='foo';
13953:  &Apache::lonnet::cstore(\%hash);
13954: 
13955:  #retrieving the hash
13956:  my %history=&Apache::lonnet::restore();
13957: 
13958:  #print the hash
13959:  foreach my $key (sort(keys(%history))) {
13960:    print("\%history{$key} = $history{$key}");
13961:  }
13962: 
13963: Will print out:
13964: 
13965:  %history{1:foo} = bar
13966:  %history{1:keys} = foo:timestamp
13967:  %history{1:timestamp} = 990455579
13968:  %history{2:bar} = foo
13969:  %history{2:foo} = notbar
13970:  %history{2:keys} = foo:bar:timestamp
13971:  %history{2:timestamp} = 990455580
13972:  %history{bar} = foo
13973:  %history{foo} = notbar
13974:  %history{timestamp} = 990455580
13975:  %history{version} = 2
13976: 
13977: Note that the special hash entries C<keys>, C<version> and
13978: C<timestamp> were added to the hash. C<version> will be equal to the
13979: total number of versions of the data that have been stored. The
13980: C<timestamp> attribute will be the UNIX time the hash was
13981: stored. C<keys> is available in every historical section to list which
13982: keys were added or changed at a specific historical revision of a
13983: hash.
13984: 
13985: B<Warning>: do not store the hash that restore returns directly. This
13986: will cause a mess since it will restore the historical keys as if the
13987: were new keys. I.E. 1:foo will become 1:1:foo etc.
13988: 
13989: Calling convention:
13990: 
13991:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
13992:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
13993: 
13994: For more detailed information, see lonnet specific documentation.
13995: 
13996: =head1 RETURN MESSAGES
13997: 
13998: =over 4
13999: 
14000: =item * B<con_lost>: unable to contact remote host
14001: 
14002: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14003: when the connection is brought back up
14004: 
14005: =item * B<con_failed>: unable to contact remote host and unable to save message
14006: for later delivery
14007: 
14008: =item * B<error:>: an error a occurred, a description of the error follows the :
14009: 
14010: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14011: that was requested
14012: 
14013: =back
14014: 
14015: =head1 PUBLIC SUBROUTINES
14016: 
14017: =head2 Session Environment Functions
14018: 
14019: =over 4
14020: 
14021: =item * 
14022: X<appenv()>
14023: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14024: the user envirnoment file, and will be restored for each access this
14025: user makes during this session, also modifies the %env for the current
14026: process. Optional rolesarrayref - if defined contains a reference to an array
14027: of roles which are exempt from the restriction on modifying user.role entries 
14028: in the user's environment.db and in %env.    
14029: 
14030: =item *
14031: X<delenv()>
14032: B<delenv($delthis,$regexp)>: removes all items from the session
14033: environment file that begin with $delthis. If the 
14034: optional second arg - $regexp - is true, $delthis is treated as a 
14035: regular expression, otherwise \Q$delthis\E is used. 
14036: The values are also deleted from the current processes %env.
14037: 
14038: =item * get_env_multiple($name) 
14039: 
14040: gets $name from the %env hash, it seemlessly handles the cases where multiple
14041: values may be defined and end up as an array ref.
14042: 
14043: returns an array of values
14044: 
14045: =back
14046: 
14047: =head2 User Information
14048: 
14049: =over 4
14050: 
14051: =item *
14052: X<queryauthenticate()>
14053: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14054: authentication scheme
14055: 
14056: =item *
14057: X<authenticate()>
14058: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14059: authenticate user from domain's lib servers (first use the current
14060: one). C<$upass> should be the users password.
14061: $checkdefauth is optional (value is 1 if a check should be made to
14062:    authenticate user using default authentication method, and allow
14063:    account creation if username does not have account in the domain).
14064: $clientcancheckhost is optional (value is 1 if checking whether the
14065:    server can host will occur on the client side in lonauth.pm).   
14066: 
14067: =item *
14068: X<homeserver()>
14069: B<homeserver($uname,$udom)>: find the server which has
14070: the user's directory and files (there must be only one), this caches
14071: the answer, and also caches if there is a borken connection.
14072: 
14073: =item *
14074: X<idget()>
14075: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14076: a list of student/employee IDs or clicker IDs
14077: (student/employee IDs are a unique resource in a domain, there must be 
14078: only 1 ID per username, and only 1 username per ID in a specific domain).
14079: clickerIDs are not necessarily unique, as students might share clickers.
14080: (returns hash: id=>name,id=>name)
14081: 
14082: =item *
14083: X<idrget()>
14084: B<idrget($udom,@unames)>: find the IDs behind a list of
14085: usernames (returns hash: name=>id,name=>id)
14086: 
14087: =item *
14088: X<idput()>
14089: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14090: names and associated student/employee IDs or clicker IDs.
14091: 
14092: =item *
14093: X<iddel()>
14094: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14095: student/employee ID or clicker ID username look-ups from domain.
14096: The homeserver ($uhome) and namespace ($namespace) are optional.
14097: If no $uhome is provided, it will be determined usig &homeserver()
14098: for each user.  If no $namespace is provided, the default is ids.
14099: 
14100: =item *
14101: X<updateclickers()>
14102: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14103: clicker ID-to-username look-ups in clickers.db on library server.
14104: Permitted actions are add or del (i.e., add or delete). The 
14105: clickers.db contains clickerID as keys (escaped), and each corresponding
14106: value is an escaped comma-separated list of usernames (for whom the
14107: library server is the homeserver), who registered that particular ID.
14108: If $critical is true, the update will be sent via &critical, otherwise
14109: &reply() will be used.
14110: 
14111: =item *
14112: X<rolesinit()>
14113: B<rolesinit($udom,$username)>: get user privileges.
14114: returns user role, first access and timer interval hashes
14115: 
14116: =item *
14117: X<privileged()>
14118: B<privileged($username,$domain)>: returns a true if user has a
14119: privileged and active role (i.e. su or dc), false otherwise.
14120: 
14121: =item *
14122: X<getsection()>
14123: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14124: course $cname, return section name/number or '' for "not in course"
14125: and '-1' for "no section"
14126: 
14127: =item *
14128: X<userenvironment()>
14129: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14130: passed in @what from the requested user's environment, returns a hash
14131: 
14132: =item * 
14133: X<userlog_query()>
14134: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14135: activity.log file. %filters defines filters applied when parsing the
14136: log file. These can be start or end timestamps, or the type of action
14137: - log to look for Login or Logout events, check for Checkin or
14138: Checkout, role for role selection. The response is in the form
14139: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14140: escaped strings of the action recorded in the activity.log file.
14141: 
14142: =back
14143: 
14144: =head2 User Roles
14145: 
14146: =over 4
14147: 
14148: =item *
14149: 
14150: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14151: returns codes for allowed actions.
14152: 
14153: The first argument is required, all others are optional.
14154: 
14155: $priv is the privilege being checked.
14156: $uri contains additional information about what is being checked for access (e.g.,
14157: URL, course ID etc.). 
14158: $symb is the unique resource instance identifier in a course; if needed,
14159: but not provided, it will be retrieved via a call to &symbread(). 
14160: $role is the role for which a priv is being checked (only used if priv is evb). 
14161: $clientip is the user's IP address (only used when checking for access to portfolio 
14162: files).
14163: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14164: prevents recursive calls to &allowed.
14165: 
14166:  F: full access
14167:  U,I,K: authentication modes (cxx only)
14168:  '': forbidden
14169:  1: user needs to choose course
14170:  2: browse allowed
14171:  A: passphrase authentication needed
14172:  B: access temporarily blocked because of a blocking event in a course.
14173: 
14174: =item *
14175: 
14176: constructaccess($url,$setpriv) : check for access to construction space URL
14177: 
14178: See if the owner domain and name in the URL match those in the
14179: expected environment.  If so, return three element list
14180: ($ownername,$ownerdomain,$ownerhome).
14181: 
14182: Otherwise return the null string.
14183: 
14184: If second argument 'setpriv' is true, it assigns the privileges,
14185: and returns the same three element list, unless the owner has
14186: blocked "ad hoc" Domain Coordinator access to the Author Space,
14187: in which case the null string is returned.
14188: 
14189: =item *
14190: 
14191: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14192: define a custom role rolename set privileges in format of lonTabs/roles.tab
14193: for system, domain, and course level. $uname and $udom are optional (current
14194: user's username and domain will be used when either of $uname or $udom are absent.
14195: 
14196: =item *
14197: 
14198: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14199: (rolesplain.tab); plain text explanation of a user role term.
14200: $type is Course (default) or Community.
14201: If $forcedefault evaluates to true, text returned will be default 
14202: text for $type. Otherwise, if this is a course, the text returned 
14203: will be a custom name for the role (if defined in the course's 
14204: environment).  If no custom name is defined the default is returned.
14205:    
14206: =item *
14207: 
14208: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14209: All arguments are optional. Returns a hash of a roles, either for
14210: co-author/assistant author roles for a user's Construction Space
14211: (default), or if $context is 'userroles', roles for the user himself,
14212: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14213: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14214: For each key, value is set to colon-separated start and end times for
14215: the role.  If no username and domain are specified, will default to
14216: current user/domain. Types, roles, and roledoms are references to arrays
14217: of role statuses (active, future or previous), roles 
14218: (e.g., cc,in, st etc.) and domains of the roles which can be used
14219: to restrict the list of roles reported. If no array ref is 
14220: provided for types, will default to return only active roles.
14221: 
14222: =item *
14223: 
14224: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14225: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14226: 
14227: Additional optional arguments are: $type (if role checking is to be restricted 
14228: to certain user status types -- previous (expired roles), active (currently
14229: available roles) or future (roles available in the future), and
14230: $hideprivileged -- if true will not report course roles for users who
14231: have active Domain Coordinator role in course's domain or in additional
14232: domains (specified in 'Domains to check for privileged users' in course
14233: environment -- set via:  Course Settings -> Classlists and staff listing).
14234: 
14235: =item *
14236: 
14237: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14238: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14239: $possdomains and $possroles are optional array refs -- to domains to check and
14240: roles to check.  If $possdomains is not specified, a dump will be done of the
14241: users' roles.db to check for a dc or su role in any domain. This can be
14242: time consuming if &privileged is called repeatedly (e.g., when displaying a
14243: classlist), so in such cases, supplying a $possdomains array is preferred, as
14244: this then allows &privileged_by_domain() to be used, which caches the identity
14245: of privileged users, eliminating the need for repeated calls to &dump().
14246: 
14247: =item *
14248: 
14249: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14250: where the outer hash keys are domains specified in the $possdomains array ref,
14251: next inner hash keys are privileged roles specified in the $roles array ref,
14252: and the innermost hash contains key = value pairs for username:domain = end:start
14253: for active or future "privileged" users with that role in that domain. To avoid
14254: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14255: innerhash are cached using priv_$role and $dom as the identifiers.
14256: 
14257: =back
14258: 
14259: =head2 User Modification
14260: 
14261: =over 4
14262: 
14263: =item *
14264: 
14265: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14266: user for the level given by URL.  Optional start and end dates (leave empty
14267: string or zero for "no date")
14268: 
14269: =item *
14270: 
14271: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14272: change a users, password, possible return values are: ok,
14273: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14274: refused
14275: 
14276: =item *
14277: 
14278: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14279: 
14280: =item *
14281: 
14282: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14283:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14284: 
14285: will update user information (firstname,middlename,lastname,generation,
14286: permanentemail), and if forceid is true, student/employee ID also.
14287: A user's institutional affiliation(s) can also be updated.
14288: User information fields will not be overwritten with empty entries 
14289: unless the field is included in the $candelete array reference.
14290: This array is included when a single user is modified via "Manage Users",
14291: or when Autoupdate.pl is run by cron in a domain.
14292: 
14293: =item *
14294: 
14295: modifystudent
14296: 
14297: modify a student's enrollment and identification information.
14298: The course id is resolved based on the current user's environment.  
14299: This means the invoking user must be a course coordinator or otherwise
14300: associated with a course.
14301: 
14302: This call is essentially a wrapper for lonnet::modifyuser and
14303: lonnet::modify_student_enrollment
14304: 
14305: Inputs: 
14306: 
14307: =over 4
14308: 
14309: =item B<$udom> Student's loncapa domain
14310: 
14311: =item B<$uname> Student's loncapa login name
14312: 
14313: =item B<$uid> Student/Employee ID
14314: 
14315: =item B<$umode> Student's authentication mode
14316: 
14317: =item B<$upass> Student's password
14318: 
14319: =item B<$first> Student's first name
14320: 
14321: =item B<$middle> Student's middle name
14322: 
14323: =item B<$last> Student's last name
14324: 
14325: =item B<$gene> Student's generation
14326: 
14327: =item B<$usec> Student's section in course
14328: 
14329: =item B<$end> Unix time of the roles expiration
14330: 
14331: =item B<$start> Unix time of the roles start date
14332: 
14333: =item B<$forceid> If defined, allow $uid to be changed
14334: 
14335: =item B<$desiredhome> server to use as home server for student
14336: 
14337: =item B<$email> Student's permanent e-mail address
14338: 
14339: =item B<$type> Type of enrollment (auto or manual)
14340: 
14341: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14342: 
14343: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14344: 
14345: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14346: 
14347: =item B<$context> role change context (shown in User Management Logs display in a course)
14348: 
14349: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14350: 
14351: =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.
14352: 
14353: =back
14354: 
14355: =item *
14356: 
14357: modify_student_enrollment
14358: 
14359: Change a student's enrollment status in a class.  The environment variable
14360: 'role.request.course' must be defined for this function to proceed.
14361: 
14362: Inputs:
14363: 
14364: =over 4
14365: 
14366: =item $udom, student's domain
14367: 
14368: =item $uname, student's name
14369: 
14370: =item $uid, student's user id
14371: 
14372: =item $first, student's first name
14373: 
14374: =item $middle
14375: 
14376: =item $last
14377: 
14378: =item $gene
14379: 
14380: =item $usec
14381: 
14382: =item $end
14383: 
14384: =item $start
14385: 
14386: =item $type
14387: 
14388: =item $locktype
14389: 
14390: =item $cid
14391: 
14392: =item $selfenroll
14393: 
14394: =item $context
14395: 
14396: =item $credits, number of credits student will earn from this class
14397: 
14398: =item $instsec, institutional course section code for student
14399: 
14400: =back
14401: 
14402: 
14403: =item *
14404: 
14405: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14406: custom role; give a custom role to a user for the level given by URL.  Specify
14407: name and domain of role author, and role name
14408: 
14409: =item *
14410: 
14411: revokerole($udom,$uname,$url,$role) : revoke a role for url
14412: 
14413: =item *
14414: 
14415: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14416: 
14417: =back
14418: 
14419: =head2 Course Infomation
14420: 
14421: =over 4
14422: 
14423: =item *
14424: 
14425: coursedescription($courseid,$options) : returns a hash of information about the
14426: specified course id, including all environment settings for the
14427: course, the description of the course will be in the hash under the
14428: key 'description'
14429: 
14430: $options is an optional parameter that if supplied is a hash reference that controls
14431: what how this function works.  It has the following key/values:
14432: 
14433: =over 4
14434: 
14435: =item freshen_cache
14436: 
14437: If defined, and the environment cache for the course is valid, it is 
14438: returned in the returned hash.
14439: 
14440: =item one_time
14441: 
14442: If defined, the last cache time is set to _now_
14443: 
14444: =item user
14445: 
14446: If defined, the supplied username is used instead of the current user.
14447: 
14448: 
14449: =back
14450: 
14451: =item *
14452: 
14453: resdata($name,$domain,$type,@which) : request for current parameter
14454: setting for a specific $type, where $type is either 'course' or 'user',
14455: @what should be a list of parameters to ask about. This routine caches
14456: answers for 10 minutes.
14457: 
14458: =item *
14459: 
14460: get_courseresdata($courseid, $domain) : dump the entire course resource
14461: data base, returning a hash that is keyed by the resource name and has
14462: values that are the resource value.  I believe that the timestamps and
14463: versions are also returned.
14464: 
14465: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14466: supplemental content area. This routine caches the number of files for 
14467: 10 minutes.
14468: 
14469: =back
14470: 
14471: =head2 Course Modification
14472: 
14473: =over 4
14474: 
14475: =item *
14476: 
14477: writecoursepref($courseid,%prefs) : write preferences (environment
14478: database) for a course
14479: 
14480: =item *
14481: 
14482: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14483: 
14484: =item *
14485: 
14486: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14487: 
14488: =item *
14489: 
14490: is_course($courseid), is_course($cdom, $cnum)
14491: 
14492: Accepts either a combined $courseid (in the form of domain_courseid) or the
14493: two component version $cdom, $cnum. It checks if the specified course exists.
14494: 
14495: Returns:
14496:     undef if the course doesn't exist, otherwise
14497:     in scalar context the combined courseid.
14498:     in list context the two components of the course identifier, domain and 
14499:     courseid.    
14500: 
14501: =back
14502: 
14503: =head2 Resource Subroutines
14504: 
14505: =over 4
14506: 
14507: =item *
14508: 
14509: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14510: 
14511: =item *
14512: 
14513: repcopy($filename) : subscribes to the requested file, and attempts to
14514: replicate from the owning library server, Might return
14515: 'unavailable', 'not_found', 'forbidden', 'ok', or
14516: 'bad_request', also attempts to grab the metadata for the
14517: resource. Expects the local filesystem pathname
14518: (/home/httpd/html/res/....)
14519: 
14520: =back
14521: 
14522: =head2 Resource Information
14523: 
14524: =over 4
14525: 
14526: =item *
14527: 
14528: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14529: and returns the value of a variety of different possible values,
14530: $varname should be a request string, and the other parameters can be
14531: used to specify who and what one is asking about. Ordinarily, $cid 
14532: does not need to be specified, as it is retrived from 
14533: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14534: within lonuserstate::loadmap() when initializing a course, before
14535: $env{'request.course.id'} has been set, so it needs to be provided
14536: in that one case.
14537: 
14538: Possible values for $varname are environment.lastname (or other item
14539: from the envirnment hash), user.name (or someother aspect about the
14540: user), resource.0.maxtries (or some other part and parameter of a
14541: resource)
14542: 
14543: =item *
14544: 
14545: directcondval($number) : get current value of a condition; reads from a state
14546: string
14547: 
14548: =item *
14549: 
14550: condval($condidx) : value of condition index based on state
14551: 
14552: =item *
14553: 
14554: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14555: resource's metadata, $what should be either a specific key, or either
14556: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14557: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14558: 
14559: this function automatically caches all requests
14560: 
14561: =item *
14562: 
14563: metadata_query($query,$custom,$customshow) : make a metadata query against the
14564: network of library servers; returns file handle of where SQL and regex results
14565: will be stored for query
14566: 
14567: =item *
14568: 
14569: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
14570: return symbolic list entry (all arguments optional). 
14571: 
14572: Args: filename is the filename (including path) for the file for which a symb 
14573: is required; donotrecurse, if true will prevent calls to allowed() being made 
14574: to check access status if more than one resource was found in the bighash 
14575: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
14576: a randompick); ignorecachednull, if true will prevent a symb of '' being 
14577: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14578: cause possible symbs to be checked to determine if they are subject to content
14579: blocking, if so they will not be included as possible symbs; possibles is a
14580: ref to a hash, which, as a side effect, will be populated with all possible 
14581: symbs (content blocking not tested).
14582:  
14583: returns the data handle
14584: 
14585: =item *
14586: 
14587: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14588: and is a possible symb for the URL in $thisfn, and if is an encrypted
14589: resource that the user accessed using /enc/ returns a 1 on success, 0
14590: on failure, user must be in a course, as it assumes the existence of
14591: the course initial hash, and uses $env('request.course.id'}.  The third
14592: arg is an optional reference to a scalar.  If this arg is passed in the 
14593: call to symbverify, it will be set to 1 if the symb has been set to be 
14594: encrypted; otherwise it will be null.  
14595: 
14596: =item *
14597: 
14598: symbclean($symb) : removes versions numbers from a symb, returns the
14599: cleaned symb
14600: 
14601: =item *
14602: 
14603: is_on_map($uri) : checks if the $uri is somewhere on the current
14604: course map, user must be in a course for it to work.
14605: 
14606: =item *
14607: 
14608: numval($salt) : return random seed value (addend for rndseed)
14609: 
14610: =item *
14611: 
14612: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14613: a random seed, all arguments are optional, if they aren't sent it uses the
14614: environment to derive them. Note: if symb isn't sent and it can't get one
14615: from &symbread it will use the current time as its return value
14616: 
14617: =item *
14618: 
14619: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14620: unfakeable, receipt
14621: 
14622: =item *
14623: 
14624: receipt() : API to ireceipt working off of env values; given out to users
14625: 
14626: =item *
14627: 
14628: countacc($url) : count the number of accesses to a given URL
14629: 
14630: =item *
14631: 
14632: 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
14633: 
14634: =item *
14635: 
14636: 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)
14637: 
14638: =item *
14639: 
14640: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
14641: 
14642: =item *
14643: 
14644: devalidate($symb) : devalidate temporary spreadsheet calculations,
14645: forcing spreadsheet to reevaluate the resource scores next time.
14646: 
14647: =item * 
14648: 
14649: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14650: when viewing in course context.
14651: 
14652:  input: six args -- filename (decluttered), course number, course domain,
14653:                     url, symb (if registered) and group (if this is a 
14654:                     group item -- e.g., bulletin board, group page etc.).
14655: 
14656:  output: array of five scalars --
14657:          $cfile -- url for file editing if editable on current server
14658:          $home -- homeserver of resource (i.e., for author if published,
14659:                                           or course if uploaded.).
14660:          $switchserver --  1 if server switch will be needed.
14661:          $forceedit -- 1 if icon/link should be to go to edit mode 
14662:          $forceview -- 1 if icon/link should be to go to view mode
14663: 
14664: =item *
14665: 
14666: is_course_upload($file,$cnum,$cdom)
14667: 
14668: Used in course context to determine if current file was uploaded to 
14669: the course (i.e., would be found in /userfiles/docs on the course's 
14670: homeserver.
14671: 
14672:   input: 3 args -- filename (decluttered), course number and course domain.
14673:   output: boolean -- 1 if file was uploaded.
14674: 
14675: =back
14676: 
14677: =head2 Storing/Retreiving Data
14678: 
14679: =over 4
14680: 
14681: =item *
14682: 
14683: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14684: permanently for this url; hashref needs to be given and should be a \%hashname;
14685: the remaining args aren't required and if they aren't passed or are '' they will
14686: be derived from the env (with the exception of $laststore, which is an 
14687: optional arg used when a user's submission is stored in grading).
14688: $laststore is $version=$timestamp, where $version is the most recent version
14689: number retrieved for the corresponding $symb in the $namespace db file, and
14690: $timestamp is the timestamp for that transaction (UNIX time).
14691: $laststore is currently only passed when cstore() is called by 
14692: structuretags::finalize_storage().
14693: 
14694: =item *
14695: 
14696: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14697: but uses critical subroutine
14698: 
14699: =item *
14700: 
14701: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14702: all args are optional
14703: 
14704: =item *
14705: 
14706: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
14707: dumps the complete (or key matching regexp) namespace into a hash
14708: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14709: normally &store()ed into
14710: 
14711: $range should be either an integer '100' (give me the first 100
14712:                                            matching records)
14713:               or be  two integers sperated by a - with no spaces
14714:                  '30-50' (give me the 30th through the 50th matching
14715:                           records)
14716: 
14717: 
14718: =item *
14719: 
14720: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
14721: replaces a &store() version of data with a replacement set of data
14722: for a particular resource in a namespace passed in the $storehash hash 
14723: reference. If $tolog is true, the transaction is logged in the courselog
14724: with an action=PUTSTORE.
14725: 
14726: =item *
14727: 
14728: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14729: works very similar to store/cstore, but all data is stored in a
14730: temporary location and can be reset using tmpreset, $storehash should
14731: be a hash reference, returns nothing on success
14732: 
14733: =item *
14734: 
14735: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14736: similar to restore, but all data is stored in a temporary location and
14737: can be reset using tmpreset. Returns a hash of values on success,
14738: error string otherwise.
14739: 
14740: =item *
14741: 
14742: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14743: deltes all keys for $symb form the temporary storage hash.
14744: 
14745: =item *
14746: 
14747: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14748: reference filled in from namesp ($udom and $uname are optional)
14749: 
14750: =item *
14751: 
14752: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14753: namesp ($udom and $uname are optional)
14754: 
14755: =item *
14756: 
14757: dump($namespace,$udom,$uname,$regexp,$range) : 
14758: dumps the complete (or key matching regexp) namespace into a hash
14759: ($udom, $uname, $regexp, $range are optional)
14760: 
14761: $range should be either an integer '100' (give me the first 100
14762:                                            matching records)
14763:               or be  two integers sperated by a - with no spaces
14764:                  '30-50' (give me the 30th through the 50th matching
14765:                           records)
14766: =item *
14767: 
14768: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14769: $store can be a scalar, an array reference, or if the amount to be 
14770: incremented is > 1, a hash reference.
14771: 
14772: ($udom and $uname are optional)
14773: 
14774: =item *
14775: 
14776: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14777: ($udom and $uname are optional)
14778: 
14779: =item *
14780: 
14781: cput($namespace,$storehash,$udom,$uname) : critical put
14782: ($udom and $uname are optional)
14783: 
14784: =item *
14785: 
14786: newput($namespace,$storehash,$udom,$uname) :
14787: 
14788: Attempts to store the items in the $storehash, but only if they don't
14789: currently exist, if this succeeds you can be certain that you have 
14790: successfully created a new key value pair in the $namespace db.
14791: 
14792: 
14793: Args:
14794:  $namespace: name of database to store values to
14795:  $storehash: hashref to store to the db
14796:  $udom: (optional) domain of user containing the db
14797:  $uname: (optional) name of user caontaining the db
14798: 
14799: Returns:
14800:  'ok' -> succeeded in storing all keys of $storehash
14801:  'key_exists: <key>' -> failed to anything out of $storehash, as at
14802:                         least <key> already existed in the db (other
14803:                         requested keys may also already exist)
14804:  'error: <msg>' -> unable to tie the DB or other error occurred
14805:  'con_lost' -> unable to contact request server
14806:  'refused' -> action was not allowed by remote machine
14807: 
14808: 
14809: =item *
14810: 
14811: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14812: reference filled in from namesp (encrypts the return communication)
14813: ($udom and $uname are optional)
14814: 
14815: =item *
14816: 
14817: log($udom,$name,$home,$message) : write to permanent log for user; use
14818: critical subroutine
14819: 
14820: =item *
14821: 
14822: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14823: array reference filled in from namespace found in domain level on either
14824: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
14825: 
14826: =item *
14827: 
14828: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
14829: domain level either on specified domain server ($uhome) or primary domain 
14830: server ($udom and $uhome are optional)
14831: 
14832: =item * 
14833: 
14834: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
14835: for: authentication, language, quotas, timezone, date locale, and portal URL in
14836: the target domain.
14837: 
14838: May also include additional key => value pairs for the following groups:
14839: 
14840: =over
14841: 
14842: =item
14843: disk quotas (MB allocated by default to portfolios and authoring spaces).
14844: 
14845: =over
14846: 
14847: =item defaultquota, authorquota
14848: 
14849: =back
14850: 
14851: =item
14852: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14853: portfolio for users).
14854: 
14855: =over
14856: 
14857: =item
14858: aboutme, blog, webdav, portfolio
14859: 
14860: =back
14861: 
14862: =item
14863: requestcourses: ability to request courses, and how requests are processed.
14864: 
14865: =over
14866: 
14867: =item
14868: official, unofficial, community, textbook, placement
14869: 
14870: =back
14871: 
14872: =item
14873: inststatus: types of institutional affiliation, and order in which they are displayed.
14874: 
14875: =over
14876: 
14877: =item
14878: inststatustypes, inststatusorder, inststatusguest
14879: 
14880: =back
14881: 
14882: =item
14883: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14884: for course's uploaded content.
14885: 
14886: =over
14887: 
14888: =item
14889: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
14890: communityquota, textbookquota, placementquota
14891: 
14892: =back
14893: 
14894: =item
14895: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14896: on your servers.
14897: 
14898: =over
14899: 
14900: =item 
14901: remotesessions, hostedsessions
14902: 
14903: =back
14904: 
14905: =back
14906: 
14907: In cases where a domain coordinator has never used the "Set Domain Configuration"
14908: utility to create a configuration.db file on a domain's primary library server 
14909: only the following domain defaults: auth_def, auth_arg_def, lang_def
14910: -- corresponding values are authentication type (internal, krb4, krb5,
14911: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
14912: will be available. Values are retrieved from cache (if current), unless the
14913: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14914: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14915: 
14916: Typical usage:
14917: 
14918: %domdefaults = &get_domain_defaults($target_domain);
14919: 
14920: =back
14921: 
14922: =head2 Network Status Functions
14923: 
14924: =over 4
14925: 
14926: =item *
14927: 
14928: dirlist() : return directory list based on URI (first arg).
14929: 
14930: Inputs: 1 required, 5 optional.
14931: 
14932: =over
14933: 
14934: =item 
14935: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14936: 
14937: =item
14938: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
14939: 
14940: =item
14941: $username -  username of user/course to be listed. Extracted from $uri if absent. 
14942: 
14943: =item
14944: $getpropath - boolean: 1 if prepend path using &propath(). 
14945: 
14946: =item
14947: $getuserdir - boolean: 1 if prepend path for "userfiles".
14948: 
14949: =item 
14950: $alternateRoot - path to prepend in place of path from $uri.
14951: 
14952: =back
14953: 
14954: Returns: Array of up to two items.
14955: 
14956: =over
14957: 
14958: a reference to an array of files/subdirectories
14959: 
14960: =over
14961: 
14962: Each element in the array of files/subdirectories is a & separated list of
14963: item name and the result of running stat on the item.  If dirlist was requested
14964: for a file instead of a directory, the item name will be ''. For a directory 
14965: listing, if the item is a metadata file, the element will end &N&M 
14966: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14967: default copyright set (1).  
14968: 
14969: =back
14970: 
14971: a scalar containing error condition (if encountered).
14972: 
14973: =over
14974: 
14975: =item 
14976: no_host (no homeserver identified for $username:$domain).
14977: 
14978: =item 
14979: no_such_host (server contacted for listing not identified as valid host).
14980: 
14981: =item 
14982: con_lost (connection to remote server failed).
14983: 
14984: =item 
14985: refused (invalid $username:$domain received on lond side).
14986: 
14987: =item 
14988: no_such_dir (directory at specified path on lond side does not exist). 
14989: 
14990: =item 
14991: empty (directory at specified path on lond side is empty).
14992: 
14993: =over
14994: 
14995: This is currently not encountered because the &ls3, &ls2, 
14996: &ls (_handler) routines on the lond side do not filter out
14997: . and .. from a directory listing. 
14998: 
14999: =back
15000: 
15001: =back
15002: 
15003: =back
15004: 
15005: =item *
15006: 
15007: spareserver() : find server with least workload from spare.tab
15008: 
15009: 
15010: =item *
15011: 
15012: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15013: if there is no corresponding loncapa host.
15014: 
15015: =back
15016: 
15017: 
15018: =head2 Apache Request
15019: 
15020: =over 4
15021: 
15022: =item *
15023: 
15024: ssi($url,%hash) : server side include, does a complete request cycle on url to
15025: localhost, posts hash
15026: 
15027: =back
15028: 
15029: =head2 Data to String to Data
15030: 
15031: =over 4
15032: 
15033: =item *
15034: 
15035: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15036: and '&' separators, supports elements that are arrayrefs and hashrefs
15037: 
15038: =item *
15039: 
15040: hashref2str($hashref) : convert a hashref into a string complete with
15041: escaping and '=' and '&' separators, supports elements that are
15042: arrayrefs and hashrefs
15043: 
15044: =item *
15045: 
15046: arrayref2str($arrayref) : convert an arrayref into a string complete
15047: with escaping and '&' separators, supports elements that are arrayrefs
15048: and hashrefs
15049: 
15050: =item *
15051: 
15052: str2hash($string) : convert string to hash using unescaping and
15053: splitting on '=' and '&', supports elements that are arrayrefs and
15054: hashrefs
15055: 
15056: =item *
15057: 
15058: str2array($string) : convert string to hash using unescaping and
15059: splitting on '&', supports elements that are arrayrefs and hashrefs
15060: 
15061: =back
15062: 
15063: =head2 Logging Routines
15064: 
15065: 
15066: These routines allow one to make log messages in the lonnet.log and
15067: lonnet.perm logfiles.
15068: 
15069: =over 4
15070: 
15071: =item *
15072: 
15073: logtouch() : make sure the logfile, lonnet.log, exists
15074: 
15075: =item *
15076: 
15077: logthis() : append message to the normal lonnet.log file, it gets
15078: preiodically rolled over and deleted.
15079: 
15080: =item *
15081: 
15082: logperm() : append a permanent message to lonnet.perm.log, this log
15083: file never gets deleted by any automated portion of the system, only
15084: messages of critical importance should go in here.
15085: 
15086: 
15087: =back
15088: 
15089: =head2 General File Helper Routines
15090: 
15091: =over 4
15092: 
15093: =item *
15094: 
15095: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15096: (a) files in /uploaded
15097:   (i) If a local copy of the file exists - 
15098:       compares modification date of local copy with last-modified date for 
15099:       definitive version stored on home server for course. If local copy is 
15100:       stale, requests a new version from the home server and stores it. 
15101:       If the original has been removed from the home server, then local copy 
15102:       is unlinked.
15103:   (ii) If local copy does not exist -
15104:       requests the file from the home server and stores it. 
15105:   
15106:   If $caller is 'uploadrep':  
15107:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15108:     for request for files originally uploaded via DOCS. 
15109:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15110:   
15111:   Otherwise:
15112:      This indicates a call from the content generation phase of the request.
15113:      -  returns the entire contents of the file or -1.
15114:      
15115: (b) files in /res
15116:    - returns the entire contents of a file or -1; 
15117:    it properly subscribes to and replicates the file if neccessary.
15118: 
15119: 
15120: =item *
15121: 
15122: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15123:                   reference
15124: 
15125: returns either a stat() list of data about the file or an empty list
15126: if the file doesn't exist or couldn't find out about it (connection
15127: problems or user unknown)
15128: 
15129: =item *
15130: 
15131: filelocation($dir,$file) : returns file system location of a file
15132: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15133: directory that relative $file lookups are to looked in ($dir of /a/dir
15134: and a file of ../bob will become /a/bob)
15135: 
15136: =item *
15137: 
15138: hreflocation($dir,$file) : returns file system location or a URL; same as
15139: filelocation except for hrefs
15140: 
15141: =item *
15142: 
15143: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15144: also removes beginning /home/httpd/html unless /priv/ follows it.
15145: 
15146: =back
15147: 
15148: =head2 Usererfile file routines (/uploaded*)
15149: 
15150: =over 4
15151: 
15152: =item *
15153: 
15154: userfileupload(): main rotine for putting a file in a user or course's
15155:                   filespace, arguments are,
15156: 
15157:  formname - required - this is the name of the element in $env where the
15158:            filename, and the contents of the file to create/modifed exist
15159:            the filename is in $env{'form.'.$formname.'.filename'} and the
15160:            contents of the file is located in $env{'form.'.$formname}
15161:  context - if coursedoc, store the file in the course of the active role
15162:              of the current user; 
15163:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15164:            if 'canceloverwrite': delete file in tmp/overwrites directory
15165:  subdir - required - subdirectory to put the file in under ../userfiles/
15166:          if undefined, it will be placed in "unknown"
15167: 
15168:  (This routine calls clean_filename() to remove any dangerous
15169:  characters from the filename, and then calls finuserfileupload() to
15170:  complete the transaction)
15171: 
15172:  returns either the url of the uploaded file (/uploaded/....) if successful
15173:  and /adm/notfound.html if unsuccessful
15174: 
15175: =item *
15176: 
15177: clean_filename(): routine for cleaing a filename up for storage in
15178:                  userfile space, argument is:
15179: 
15180:  filename - proposed filename
15181: 
15182: returns: the new clean filename
15183: 
15184: =item *
15185: 
15186: finishuserfileupload(): routine that creates and sends the file to
15187: userspace, probably shouldn't be called directly
15188: 
15189:   docuname: username or courseid of destination for the file
15190:   docudom: domain of user/course of destination for the file
15191:   formname: same as for userfileupload()
15192:   fname: filename (including subdirectories) for the file
15193:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15194:   allfiles: reference to hash used to store objects found by parser
15195:   codebase: reference to hash used for codebases of java objects found by parser
15196:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15197:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15198:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15199:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15200:   context: if 'overwrite', will move the uploaded file from its temporary location to
15201:             userfiles to facilitate overwriting a previously uploaded file with same name.
15202:   mimetype: reference to scalar to accommodate mime type determined
15203:             from File::MMagic if $parser = parse.
15204: 
15205:  returns either the url of the uploaded file (/uploaded/....) if successful
15206:  and /adm/notfound.html if unsuccessful (or an error message if context 
15207:  was 'overwrite').
15208:  
15209: 
15210: =item *
15211: 
15212: renameuserfile(): renames an existing userfile to a new name
15213: 
15214:   Args:
15215:    docuname: username or courseid of destination for the file
15216:    docudom: domain of user/course of destination for the file
15217:    old: current file name (including any subdirs under userfiles)
15218:    new: desired file name (including any subdirs under userfiles)
15219: 
15220: =item *
15221: 
15222: mkdiruserfile(): creates a directory is a userfiles dir
15223: 
15224:   Args:
15225:    docuname: username or courseid of destination for the file
15226:    docudom: domain of user/course of destination for the file
15227:    dir: dir to create (including any subdirs under userfiles)
15228: 
15229: =item *
15230: 
15231: removeuserfile(): removes a file that exists in userfiles
15232: 
15233:   Args:
15234:    docuname: username or courseid of destination for the file
15235:    docudom: domain of user/course of destination for the file
15236:    fname: filname to delete (including any subdirs under userfiles)
15237: 
15238: =item *
15239: 
15240: removeuploadedurl(): convience function for removeuserfile()
15241: 
15242:   Args:
15243:    url:  a full /uploaded/... url to delete
15244: 
15245: =item * 
15246: 
15247: get_portfile_permissions():
15248:   Args:
15249:     domain: domain of user or course contain the portfolio files
15250:     user: name of user or num of course contain the portfolio files
15251:   Returns:
15252:     hashref of a dump of the proper file_permissions.db
15253:    
15254: 
15255: =item * 
15256: 
15257: get_access_controls():
15258: 
15259: Args:
15260:   current_permissions: the hash ref returned from get_portfile_permissions()
15261:   group: (optional) the group you want the files associated with
15262:   file: (optional) the file you want access info on
15263: 
15264: Returns:
15265:     a hash (keys are file names) of hashes containing
15266:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15267:         values are XML containing access control settings (see below) 
15268: 
15269: Internal notes:
15270: 
15271:  access controls are stored in file_permissions.db as key=value pairs.
15272:     key -> path to file/file_name\0uniqueID:scope_end_start
15273:         where scope -> public,guest,course,group,domains or users.
15274:               end -> UNIX time for end of access (0 -> no end date)
15275:               start -> UNIX time for start of access
15276: 
15277:     value -> XML description of access control
15278:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15279:             <start></start>
15280:             <end></end>
15281: 
15282:             <password></password>  for scope type = guest
15283: 
15284:             <domain></domain>     for scope type = course or group
15285:             <number></number>
15286:             <roles id="">
15287:              <role></role>
15288:              <access></access>
15289:              <section></section>
15290:              <group></group>
15291:             </roles>
15292: 
15293:             <dom></dom>         for scope type = domains
15294: 
15295:             <users>             for scope type = users
15296:              <user>
15297:               <uname></uname>
15298:               <udom></udom>
15299:              </user>
15300:             </users>
15301:            </scope> 
15302:               
15303:  Access data is also aggregated for each file in an additional key=value pair:
15304:  key -> path to file/file_name\0accesscontrol 
15305:  value -> reference to hash
15306:           hash contains key = value pairs
15307:           where key = uniqueID:scope_end_start
15308:                 value = UNIX time record was last updated
15309: 
15310:           Used to improve speed of look-ups of access controls for each file.  
15311:  
15312:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15313: 
15314: =item *
15315: 
15316: modify_access_controls():
15317: 
15318: Modifies access controls for a portfolio file
15319: Args
15320: 1. file name
15321: 2. reference to hash of required changes,
15322: 3. domain
15323: 4. username
15324:   where domain,username are the domain of the portfolio owner 
15325:   (either a user or a course) 
15326: 
15327: Returns:
15328: 1. result of additions or updates ('ok' or 'error', with error message). 
15329: 2. result of deletions ('ok' or 'error', with error message).
15330: 3. reference to hash of any new or updated access controls.
15331: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15332:    key = integer (inbound ID)
15333:    value = uniqueID
15334: 
15335: =item *
15336: 
15337: get_timebased_id():
15338: 
15339: Attempts to get a unique timestamp-based suffix for use with items added to a 
15340: course via the Course Editor (e.g., folders, composite pages, 
15341: group bulletin boards).
15342: 
15343: Args: (first three required; six others optional)
15344: 
15345: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15346:    docssequence, or name of group
15347: 
15348: 2. keyid (alphanumeric): name of temporary locking key in hash,
15349:    e.g., num, boardids
15350: 
15351: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15352:    file will be named nohist_namespace.db
15353: 
15354: 4. cdom: domain of course; default is current course domain from %env
15355: 
15356: 5. cnum: course number; default is current course number from %env
15357: 
15358: 6. idtype: set to concat if an additional digit is to be appended to the 
15359:    unix timestamp to form the suffix, if the plain timestamp is already
15360:    in use.  Default is to not do this, but simply increment the unix 
15361:    timestamp by 1 until a unique key is obtained.
15362: 
15363: 7. who: holder of locking key; defaults to user:domain for user.
15364: 
15365: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15366:    retrying); default is 3.
15367: 
15368: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15369: 
15370: Returns:
15371: 
15372: 1. suffix obtained (numeric)
15373: 
15374: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15375: 
15376: 3. error: contains (localized) error message if an error occurred.
15377: 
15378: 
15379: =back
15380: 
15381: =head2 HTTP Helper Routines
15382: 
15383: =over 4
15384: 
15385: =item *
15386: 
15387: escape() : unpack non-word characters into CGI-compatible hex codes
15388: 
15389: =item *
15390: 
15391: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15392: 
15393: =back
15394: 
15395: =head1 PRIVATE SUBROUTINES
15396: 
15397: =head2 Underlying communication routines (Shouldn't call)
15398: 
15399: =over 4
15400: 
15401: =item *
15402: 
15403: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15404: 
15405: =item *
15406: 
15407: reply() : uses subreply to send a message to remote machine, logs all failures
15408: 
15409: =item *
15410: 
15411: critical() : passes a critical message to another server; if cannot
15412: get through then place message in connection buffer directory and
15413: returns con_delayed, if incapable of saving message, returns
15414: con_failed
15415: 
15416: =item *
15417: 
15418: reconlonc() : tries to reconnect lonc client processes.
15419: 
15420: =back
15421: 
15422: =head2 Resource Access Logging
15423: 
15424: =over 4
15425: 
15426: =item *
15427: 
15428: flushcourselogs() : flush (save) buffer logs and access logs
15429: 
15430: =item *
15431: 
15432: courselog($what) : save message for course in hash
15433: 
15434: =item *
15435: 
15436: courseacclog($what) : save message for course using &courselog().  Perform
15437: special processing for specific resource types (problems, exams, quizzes, etc).
15438: 
15439: =item *
15440: 
15441: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15442: as a PerlChildExitHandler
15443: 
15444: =back
15445: 
15446: =head2 Other
15447: 
15448: =over 4
15449: 
15450: =item *
15451: 
15452: symblist($mapname,%newhash) : update symbolic storage links
15453: 
15454: =back
15455: 
15456: =cut
15457: 

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