File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1386: download - view: text, annotated - select for diffs
Fri Oct 19 16:54:58 2018 UTC (5 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Log (to lonnet.log) if storage of firstaccess times is not needed or fails.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1386 2018/10/19 16:54:58 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: 
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 20;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_servercerts_info {
  233:     my ($lonhost,$hostname,$context) = @_;
  234:     return if ($lonhost eq '');
  235:     if ($hostname eq '') {
  236:         $hostname = &hostname($lonhost);
  237:     }
  238:     return if ($hostname eq '');
  239:     my ($rep,$uselocal);
  240:     if (grep { $_ eq $lonhost } &current_machine_ids()) {
  241:         $uselocal = 1;
  242:     }
  243:     if (($context ne 'cgi') && ($uselocal)) {
  244:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  245:         if ($distro eq '') {
  246:             $uselocal = 0;
  247:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  248:             if ($1 < 6) {
  249:                 $uselocal = 0;
  250:             }
  251:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  252:             if ($1 < 12) {
  253:                 $uselocal = 0;
  254:             }
  255:         }
  256:     }
  257:     if ($uselocal) {
  258:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  259:     } else {
  260:         $rep=&reply('servercerts',$lonhost);
  261:     }
  262:     my ($result,%returnhash);
  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,$domref) = @_;
  654:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  655:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  656:     if ($name eq 'lonDAV') {
  657:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  658:     } else {
  659:         $lonidsdir=$r->dir_config('lonIDsDir');
  660:         if ($name eq '') {
  661:             $name = 'lonID';
  662:         }
  663:     }
  664:     if ($name eq 'lonID') {
  665:         $secure = 'lonSID';
  666:         $linkname = 'lonLinkID';
  667:         $pubname = 'lonPubID';
  668:         if (exists($cookies{$secure})) {
  669:             $lonid=$cookies{$secure};
  670:         } elsif (exists($cookies{$name})) {
  671:             $lonid=$cookies{$name};
  672:         } elsif (exists($cookies{$linkname})) {
  673:             $lonid=$cookies{$linkname};
  674:         } elsif (exists($cookies{$pubname})) {
  675:             $lonid=$cookies{$pubname};
  676:         }
  677:     } else {
  678:         $lonid=$cookies{$name};
  679:     }
  680:     return undef if (!$lonid);
  681: 
  682:     my $handle=&LONCAPA::clean_handle($lonid->value);
  683:     if (-l "$lonidsdir/$handle.id") {
  684:         my $link = readlink("$lonidsdir/$handle.id");
  685:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  686:             $handle = $1;
  687:         }
  688:     }
  689:     if (!-e "$lonidsdir/$handle.id") {
  690:         if ((ref($domref)) && ($name eq 'lonID') && 
  691:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  692:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  693:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  694:                 $$domref = $possudom;
  695:             }
  696:         }
  697:         return undef;
  698:     }
  699: 
  700:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  701:     return undef if (!$opened);
  702: 
  703:     flock($idf,LOCK_SH);
  704:     my %disk_env;
  705:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  706: 	    &GDBM_READER(),0640)) {
  707: 	return undef;	
  708:     }
  709: 
  710:     if (!defined($disk_env{'user.name'})
  711: 	|| !defined($disk_env{'user.domain'})) {
  712: 	return undef;
  713:     }
  714: 
  715:     if (ref($userhashref) eq 'HASH') {
  716:         $userhashref->{'name'} = $disk_env{'user.name'};
  717:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  718:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  719:         if ($userhashref->{'lti'}) {
  720:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  721:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  722:         }
  723:     }
  724: 
  725:     return $handle;
  726: }
  727: 
  728: sub timed_flock {
  729:     my ($file,$lock_type) = @_;
  730:     my $failed=0;
  731:     eval {
  732: 	local $SIG{__DIE__}='DEFAULT';
  733: 	local $SIG{ALRM}=sub {
  734: 	    $failed=1;
  735: 	    die("failed lock");
  736: 	};
  737: 	alarm(13);
  738: 	flock($file,$lock_type);
  739: 	alarm(0);
  740:     };
  741:     if ($failed) {
  742: 	return undef;
  743:     } else {
  744: 	return 1;
  745:     }
  746: }
  747: 
  748: # ---------------------------------------------------------- Append Environment
  749: 
  750: sub appenv {
  751:     my ($newenv,$roles) = @_;
  752:     if (ref($newenv) eq 'HASH') {
  753:         foreach my $key (keys(%{$newenv})) {
  754:             my $refused = 0;
  755: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  756:                 $refused = 1;
  757:                 if (ref($roles) eq 'ARRAY') {
  758:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  759:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  760:                         $refused = 0;
  761:                     }
  762:                 }
  763:             }
  764:             if ($refused) {
  765:                 &logthis("<font color=\"blue\">WARNING: ".
  766:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  767:                          .'</font>');
  768: 	        delete($newenv->{$key});
  769:             } else {
  770:                 $env{$key}=$newenv->{$key};
  771:             }
  772:         }
  773:         my $lonids = $perlvar{'lonIDsDir'};
  774:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  775:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  776:             if ($opened
  777: 	        && &timed_flock($env_file,LOCK_EX)
  778: 	        &&
  779: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  780: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  781: 	        while (my ($key,$value) = each(%{$newenv})) {
  782: 	            $disk_env{$key} = $value;
  783: 	        }
  784: 	        untie(%disk_env);
  785:             }
  786:         }
  787:     }
  788:     return 'ok';
  789: }
  790: # ----------------------------------------------------- Delete from Environment
  791: 
  792: sub delenv {
  793:     my ($delthis,$regexp,$roles) = @_;
  794:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  795:         my $refused = 1;
  796:         if (ref($roles) eq 'ARRAY') {
  797:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  798:             if (grep(/^\Q$role\E$/,@{$roles})) {
  799:                 $refused = 0;
  800:             }
  801:         }
  802:         if ($refused) {
  803:             &logthis("<font color=\"blue\">WARNING: ".
  804:                      "Attempt to delete from environment ".$delthis);
  805:             return 'error';
  806:         }
  807:     }
  808:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  809:     if ($opened
  810: 	&& &timed_flock($env_file,LOCK_EX)
  811: 	&&
  812: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  813: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  814: 	foreach my $key (keys(%disk_env)) {
  815: 	    if ($regexp) {
  816:                 if ($key=~/^$delthis/) {
  817:                     delete($env{$key});
  818:                     delete($disk_env{$key});
  819:                 } 
  820:             } else {
  821:                 if ($key=~/^\Q$delthis\E/) {
  822: 		    delete($env{$key});
  823: 		    delete($disk_env{$key});
  824: 	        }
  825:             }
  826: 	}
  827: 	untie(%disk_env);
  828:     }
  829:     return 'ok';
  830: }
  831: 
  832: sub get_env_multiple {
  833:     my ($name) = @_;
  834:     my @values;
  835:     if (defined($env{$name})) {
  836:         # exists is it an array
  837:         if (ref($env{$name})) {
  838:             @values=@{ $env{$name} };
  839:         } else {
  840:             $values[0]=$env{$name};
  841:         }
  842:     }
  843:     return(@values);
  844: }
  845: 
  846: # ------------------------------------------------------------------- Locking
  847: 
  848: sub set_lock {
  849:     my ($text)=@_;
  850:     $locknum++;
  851:     my $id=$$.'-'.$locknum;
  852:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  853:              'session.lock.'.$id => $text});
  854:     return $id;
  855: }
  856: 
  857: sub get_locks {
  858:     my $num=0;
  859:     my %texts=();
  860:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  861:        if ($lock=~/\w/) {
  862:           $num++;
  863:           $texts{$lock}=$env{'session.lock.'.$lock};
  864:        }
  865:    }
  866:    return ($num,%texts);
  867: }
  868: 
  869: sub remove_lock {
  870:     my ($id)=@_;
  871:     my $newlocks='';
  872:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  873:        if (($lock=~/\w/) && ($lock ne $id)) {
  874:           $newlocks.=','.$lock;
  875:        }
  876:     }
  877:     &appenv({'session.locks' => $newlocks});
  878:     &delenv('session.lock.'.$id);
  879: }
  880: 
  881: sub remove_all_locks {
  882:     my $activelocks=$env{'session.locks'};
  883:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  884:        if ($lock=~/\w/) {
  885:           &remove_lock($lock);
  886:        }
  887:     }
  888: }
  889: 
  890: 
  891: # ------------------------------------------ Find out current server userload
  892: sub userload {
  893:     my $numusers=0;
  894:     {
  895: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  896: 	my $filename;
  897: 	my $curtime=time;
  898: 	while ($filename=readdir(LONIDS)) {
  899: 	    next if ($filename eq '.' || $filename eq '..');
  900: 	    next if ($filename =~ /publicuser_\d+\.id/);
  901: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  902: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  903: 	}
  904: 	closedir(LONIDS);
  905:     }
  906:     my $userloadpercent=0;
  907:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  908:     if ($maxuserload) {
  909: 	$userloadpercent=100*$numusers/$maxuserload;
  910:     }
  911:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  912:     return $userloadpercent;
  913: }
  914: 
  915: # ------------------------------ Find server with least workload from spare.tab
  916: 
  917: sub spareserver {
  918:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  919:     my $spare_server;
  920:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  921:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  922:                                                      :  $userloadpercent;
  923:     my ($uint_dom,$remotesessions);
  924:     if (($udom ne '') && (&domain($udom) ne '')) {
  925:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  926:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  927:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  928:         $remotesessions = $udomdefaults{'remotesessions'};
  929:     }
  930:     my $spareshash = &this_host_spares($udom);
  931:     if (ref($spareshash) eq 'HASH') {
  932:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  933:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  934:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  935:                                              $try_server));
  936: 	        ($spare_server, $lowest_load) =
  937: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  938:             }
  939:         }
  940: 
  941:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  942: 
  943:         if (!$found_server) {
  944:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  945: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  946:                     next unless (&spare_can_host($udom,$uint_dom,
  947:                                                  $remotesessions,$try_server));
  948: 	            ($spare_server, $lowest_load) =
  949: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  950:                 }
  951: 	    }
  952:         }
  953:     }
  954: 
  955:     if (!$want_server_name) {
  956:         my $protocol = 'http';
  957:         if ($protocol{$spare_server} eq 'https') {
  958:             $protocol = $protocol{$spare_server};
  959:         }
  960:         if (defined($spare_server)) {
  961:             my $hostname = &hostname($spare_server);
  962:             if (defined($hostname)) {
  963: 	        $spare_server = $protocol.'://'.$hostname;
  964:             }
  965:         }
  966:     }
  967:     return $spare_server;
  968: }
  969: 
  970: sub compare_server_load {
  971:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  972: 
  973:     if ($required) {
  974:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  975:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  976:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  977:         if (($major eq '' && $minor eq '') ||
  978:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  979:             return ($spare_server,$lowest_load);
  980:         }
  981:     }
  982: 
  983:     my $loadans     = &reply('load',    $try_server);
  984:     my $userloadans = &reply('userload',$try_server);
  985: 
  986:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  987: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  988:     }
  989: 
  990:     my $load;
  991:     if ($loadans =~ /\d/) {
  992: 	if ($userloadans =~ /\d/) {
  993: 	    #both are numbers, pick the bigger one
  994: 	    $load = ($loadans > $userloadans) ? $loadans 
  995: 		                              : $userloadans;
  996: 	} else {
  997: 	    $load = $loadans;
  998: 	}
  999:     } else {
 1000: 	$load = $userloadans;
 1001:     }
 1002: 
 1003:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1004: 	$spare_server = $try_server;
 1005: 	$lowest_load  = $load;
 1006:     }
 1007:     return ($spare_server,$lowest_load);
 1008: }
 1009: 
 1010: # --------------------------- ask offload servers if user already has a session
 1011: sub find_existing_session {
 1012:     my ($udom,$uname) = @_;
 1013:     my $spareshash = &this_host_spares($udom);
 1014:     if (ref($spareshash) eq 'HASH') {
 1015:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1016:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1017:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1018:             }
 1019:         }
 1020:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1021:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1022:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1023:             }
 1024:         }
 1025:     }
 1026:     return;
 1027: }
 1028: 
 1029: # -------------------------------- ask if server already has a session for user
 1030: sub has_user_session {
 1031:     my ($lonid,$udom,$uname) = @_;
 1032:     my $result = &reply(join(':','userhassession',
 1033: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1034:     return 1 if ($result eq 'ok');
 1035: 
 1036:     return 0;
 1037: }
 1038: 
 1039: # --------- determine least loaded server in a user's domain which allows login
 1040: 
 1041: sub choose_server {
 1042:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1043:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1044:     my %servers = &get_servers($udom);
 1045:     my $lowest_load = 30000;
 1046:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1047:     if ($skiploadbal) {
 1048:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1049:         unless (defined($cached)) {
 1050:             my $cachetime = 60*60*24;
 1051:             my %domconfig =
 1052:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1053:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1054:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1055:                                            $cachetime);
 1056:             }
 1057:         }
 1058:     }
 1059:     foreach my $lonhost (keys(%servers)) {
 1060:         if ($skiploadbal) {
 1061:             if (ref($balancers) eq 'HASH') {
 1062:                 next if (exists($balancers->{$lonhost}));
 1063:             }
 1064:         }   
 1065:         my $loginvia;
 1066:         if ($checkloginvia) {
 1067:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1068:             if ($loginvia) {
 1069:                 my ($server,$path) = split(/:/,$loginvia);
 1070:                 ($login_host, $lowest_load) =
 1071:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1072:                 if ($login_host eq $server) {
 1073:                     $portal_path = $path;
 1074:                     $isredirect = 1;
 1075:                 }
 1076:             } else {
 1077:                 ($login_host, $lowest_load) =
 1078:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1079:                 if ($login_host eq $lonhost) {
 1080:                     $portal_path = '';
 1081:                     $isredirect = ''; 
 1082:                 }
 1083:             }
 1084:         } else {
 1085:             ($login_host, $lowest_load) =
 1086:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1087:         }
 1088:     }
 1089:     if ($login_host ne '') {
 1090:         $hostname = &hostname($login_host);
 1091:     }
 1092:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1093: }
 1094: 
 1095: # --------------------------------------------- Try to change a user's password
 1096: 
 1097: sub changepass {
 1098:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1099:     $currentpass = &escape($currentpass);
 1100:     $newpass     = &escape($newpass);
 1101:     my $lonhost = $perlvar{'lonHostID'};
 1102:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1103: 		       $server);
 1104:     if (! $answer) {
 1105: 	&logthis("No reply on password change request to $server ".
 1106: 		 "by $uname in domain $udom.");
 1107:     } elsif ($answer =~ "^ok") {
 1108:         &logthis("$uname in $udom successfully changed their password ".
 1109: 		 "on $server.");
 1110:     } elsif ($answer =~ "^pwchange_failure") {
 1111: 	&logthis("$uname in $udom was unable to change their password ".
 1112: 		 "on $server.  The action was blocked by either lcpasswd ".
 1113: 		 "or pwchange");
 1114:     } elsif ($answer =~ "^non_authorized") {
 1115:         &logthis("$uname in $udom did not get their password correct when ".
 1116: 		 "attempting to change it on $server.");
 1117:     } elsif ($answer =~ "^auth_mode_error") {
 1118:         &logthis("$uname in $udom attempted to change their password despite ".
 1119: 		 "not being locally or internally authenticated on $server.");
 1120:     } elsif ($answer =~ "^unknown_user") {
 1121:         &logthis("$uname in $udom attempted to change their password ".
 1122: 		 "on $server but were unable to because $server is not ".
 1123: 		 "their home server.");
 1124:     } elsif ($answer =~ "^refused") {
 1125: 	&logthis("$server refused to change $uname in $udom password because ".
 1126: 		 "it was sent an unencrypted request to change the password.");
 1127:     } elsif ($answer =~ "invalid_client") {
 1128:         &logthis("$server refused to change $uname in $udom password because ".
 1129:                  "it was a reset by e-mail originating from an invalid server.");
 1130:     }
 1131:     return $answer;
 1132: }
 1133: 
 1134: # ----------------------- Try to determine user's current authentication scheme
 1135: 
 1136: sub queryauthenticate {
 1137:     my ($uname,$udom)=@_;
 1138:     my $uhome=&homeserver($uname,$udom);
 1139:     if (!$uhome) {
 1140: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1141: 	return 'no_host';
 1142:     }
 1143:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1144:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1145: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1146:     }
 1147:     return $answer;
 1148: }
 1149: 
 1150: # --------- Try to authenticate user from domain's lib servers (first this one)
 1151: 
 1152: sub authenticate {
 1153:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1154:     $upass=&escape($upass);
 1155:     $uname= &LONCAPA::clean_username($uname);
 1156:     my $uhome=&homeserver($uname,$udom,1);
 1157:     my $newhome;
 1158:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1159: # Maybe the machine was offline and only re-appeared again recently?
 1160:         &reconlonc();
 1161: # One more
 1162: 	$uhome=&homeserver($uname,$udom,1);
 1163:         if (($uhome eq 'no_host') && $checkdefauth) {
 1164:             if (defined(&domain($udom,'primary'))) {
 1165:                 $newhome=&domain($udom,'primary');
 1166:             }
 1167:             if ($newhome ne '') {
 1168:                 $uhome = $newhome;
 1169:             }
 1170:         }
 1171: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1172: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1173: 	    return 'no_host';
 1174:         }
 1175:     }
 1176:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1177:     if ($answer eq 'authorized') {
 1178:         if ($newhome) {
 1179:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1180:             return 'no_account_on_host'; 
 1181:         } else {
 1182:             &logthis("User $uname at $udom authorized by $uhome");
 1183:             return $uhome;
 1184:         }
 1185:     }
 1186:     if ($answer eq 'non_authorized') {
 1187: 	&logthis("User $uname at $udom rejected by $uhome");
 1188: 	return 'no_host'; 
 1189:     }
 1190:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1191:     return 'no_host';
 1192: }
 1193: 
 1194: sub can_host_session {
 1195:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1196:     my $canhost = 1;
 1197:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1198:     if (ref($remotesessions) eq 'HASH') {
 1199:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1200:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1201:                 $canhost = 0;
 1202:             } else {
 1203:                 $canhost = 1;
 1204:             }
 1205:         }
 1206:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1207:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1208:                 $canhost = 1;
 1209:             } else {
 1210:                 $canhost = 0;
 1211:             }
 1212:         }
 1213:         if ($canhost) {
 1214:             if ($remotesessions->{'version'} ne '') {
 1215:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1216:                 if ($reqmajor ne '' && $reqminor ne '') {
 1217:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1218:                         my $major = $1;
 1219:                         my $minor = $2;
 1220:                         if (($major < $reqmajor ) ||
 1221:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1222:                             $canhost = 0;
 1223:                         }
 1224:                     } else {
 1225:                         $canhost = 0;
 1226:                     }
 1227:                 }
 1228:             }
 1229:         }
 1230:     }
 1231:     if ($canhost) {
 1232:         if (ref($hostedsessions) eq 'HASH') {
 1233:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1234:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1235:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1236:                 if (($uint_dom ne '') && 
 1237:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1238:                     $canhost = 0;
 1239:                 } else {
 1240:                     $canhost = 1;
 1241:                 }
 1242:             }
 1243:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1244:                 if (($uint_dom ne '') && 
 1245:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1246:                     $canhost = 1;
 1247:                 } else {
 1248:                     $canhost = 0;
 1249:                 }
 1250:             }
 1251:         }
 1252:     }
 1253:     return $canhost;
 1254: }
 1255: 
 1256: sub spare_can_host {
 1257:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1258:     my $canhost=1;
 1259:     my $try_server_hostname = &hostname($try_server);
 1260:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1261:     my $serverhomedom = &host_domain($serverhomeID);
 1262:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1263:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1264:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1265:             $canhost = 0;
 1266:         }
 1267:     }
 1268:     if (($canhost) && ($uint_dom)) {
 1269:         my @intdoms;
 1270:         my $internet_names = &get_internet_names($try_server);
 1271:         if (ref($internet_names) eq 'ARRAY') {
 1272:             @intdoms = @{$internet_names};
 1273:         }
 1274:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1275:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1276:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1277:                                          $remotesessions,
 1278:                                          $defdomdefaults{'hostedsessions'});
 1279:         }
 1280:     }
 1281:     return $canhost;
 1282: }
 1283: 
 1284: sub this_host_spares {
 1285:     my ($dom) = @_;
 1286:     my ($dom_in_use,$lonhost_in_use,$result);
 1287:     my @hosts = &current_machine_ids();
 1288:     foreach my $lonhost (@hosts) {
 1289:         if (&host_domain($lonhost) eq $dom) {
 1290:             $dom_in_use = $dom;
 1291:             $lonhost_in_use = $lonhost;
 1292:             last;
 1293:         }
 1294:     }
 1295:     if ($dom_in_use ne '') {
 1296:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1297:     }
 1298:     if (ref($result) ne 'HASH') {
 1299:         $lonhost_in_use = $perlvar{'lonHostID'};
 1300:         $dom_in_use = &host_domain($lonhost_in_use);
 1301:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1302:         if (ref($result) ne 'HASH') {
 1303:             $result = \%spareid;
 1304:         }
 1305:     }
 1306:     return $result;
 1307: }
 1308: 
 1309: sub spares_for_offload  {
 1310:     my ($dom_in_use,$lonhost_in_use) = @_;
 1311:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1312:     if (defined($cached)) {
 1313:         return $result;
 1314:     } else {
 1315:         my $cachetime = 60*60*24;
 1316:         my %domconfig =
 1317:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1318:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1319:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1320:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1321:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1322:                 }
 1323:             }
 1324:         }
 1325:     }
 1326:     return;
 1327: }
 1328: 
 1329: sub get_lonbalancer_config {
 1330:     my ($servers) = @_;
 1331:     my ($currbalancer,$currtargets);
 1332:     if (ref($servers) eq 'HASH') {
 1333:         foreach my $server (keys(%{$servers})) {
 1334:             my %what = (
 1335:                          spareid => 1,
 1336:                          perlvar => 1,
 1337:                        );
 1338:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1339:             if ($result eq 'ok') {
 1340:                 if (ref($returnhash) eq 'HASH') {
 1341:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1342:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1343:                             $currbalancer = $server;
 1344:                             $currtargets = {};
 1345:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1346:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1347:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1348:                                 }
 1349:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1350:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1351:                                 }
 1352:                             }
 1353:                             last;
 1354:                         }
 1355:                     }
 1356:                 }
 1357:             }
 1358:         }
 1359:     }
 1360:     return ($currbalancer,$currtargets);
 1361: }
 1362: 
 1363: sub check_loadbalancing {
 1364:     my ($uname,$udom,$caller) = @_;
 1365:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1366:         $rule_in_effect,$offloadto,$otherserver);
 1367:     my $lonhost = $perlvar{'lonHostID'};
 1368:     my @hosts = &current_machine_ids();
 1369:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1370:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1371:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1372:     my $serverhomedom = &host_domain($lonhost);
 1373:     my $domneedscache;
 1374:     my $cachetime = 60*60*24;
 1375: 
 1376:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1377:         $dom_in_use = $udom;
 1378:         $homeintdom = 1;
 1379:     } else {
 1380:         $dom_in_use = $serverhomedom;
 1381:     }
 1382:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1383:     unless (defined($cached)) {
 1384:         my %domconfig =
 1385:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1386:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1387:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1388:         } else {
 1389:             $domneedscache = $dom_in_use;
 1390:         }
 1391:     }
 1392:     if (ref($result) eq 'HASH') {
 1393:         ($is_balancer,$currtargets,$currrules) = 
 1394:             &check_balancer_result($result,@hosts);
 1395:         if ($is_balancer) {
 1396:             if (ref($currrules) eq 'HASH') {
 1397:                 if ($homeintdom) {
 1398:                     if ($uname ne '') {
 1399:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1400:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1401:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1402:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1403:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1404:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1405:                             }
 1406:                         }
 1407:                         if ($rule_in_effect eq '') {
 1408:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1409:                             if ($userenv{'inststatus'} ne '') {
 1410:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1411:                                 my ($othertitle,$usertypes,$types) =
 1412:                                     &Apache::loncommon::sorted_inst_types($udom);
 1413:                                 if (ref($types) eq 'ARRAY') {
 1414:                                     foreach my $type (@{$types}) {
 1415:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1416:                                             if (exists($currrules->{$type})) {
 1417:                                                 $rule_in_effect = $currrules->{$type};
 1418:                                             }
 1419:                                         }
 1420:                                     }
 1421:                                 }
 1422:                             } else {
 1423:                                 if (exists($currrules->{'default'})) {
 1424:                                     $rule_in_effect = $currrules->{'default'};
 1425:                                 }
 1426:                             }
 1427:                         }
 1428:                     } else {
 1429:                         if (exists($currrules->{'default'})) {
 1430:                             $rule_in_effect = $currrules->{'default'};
 1431:                         }
 1432:                     }
 1433:                 } else {
 1434:                     if ($currrules->{'_LC_external'} ne '') {
 1435:                         $rule_in_effect = $currrules->{'_LC_external'};
 1436:                     }
 1437:                 }
 1438:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1439:                                                        $uname,$udom);
 1440:             }
 1441:         }
 1442:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1443:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1444:         unless (defined($cached)) {
 1445:             my %domconfig =
 1446:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1447:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1448:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1449:             } else {
 1450:                 $domneedscache = $serverhomedom;
 1451:             }
 1452:         }
 1453:         if (ref($result) eq 'HASH') {
 1454:             ($is_balancer,$currtargets,$currrules) = 
 1455:                 &check_balancer_result($result,@hosts);
 1456:             if ($is_balancer) {
 1457:                 if (ref($currrules) eq 'HASH') {
 1458:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1459:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1460:                     }
 1461:                 }
 1462:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1463:                                                        $uname,$udom);
 1464:             }
 1465:         } else {
 1466:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1467:                 $is_balancer = 1;
 1468:                 $offloadto = &this_host_spares($dom_in_use);
 1469:             }
 1470:             unless (defined($cached)) {
 1471:                 $domneedscache = $serverhomedom;
 1472:             }
 1473:         }
 1474:     } else {
 1475:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1476:             $is_balancer = 1;
 1477:             $offloadto = &this_host_spares($dom_in_use);
 1478:         }
 1479:         unless (defined($cached)) {
 1480:             $domneedscache = $serverhomedom;
 1481:         }
 1482:     }
 1483:     if ($domneedscache) {
 1484:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1485:     }
 1486:     if ($is_balancer) {
 1487:         my $lowest_load = 30000;
 1488:         if (ref($offloadto) eq 'HASH') {
 1489:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1490:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1491:                     ($otherserver,$lowest_load) =
 1492:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1493:                 }
 1494:             }
 1495:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1496: 
 1497:             if (!$found_server) {
 1498:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1499:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1500:                         ($otherserver,$lowest_load) =
 1501:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1502:                     }
 1503:                 }
 1504:             }
 1505:         } elsif (ref($offloadto) eq 'ARRAY') {
 1506:             if (@{$offloadto} == 1) {
 1507:                 $otherserver = $offloadto->[0];
 1508:             } elsif (@{$offloadto} > 1) {
 1509:                 foreach my $try_server (@{$offloadto}) {
 1510:                     ($otherserver,$lowest_load) =
 1511:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1512:                 }
 1513:             }
 1514:         }
 1515:         unless ($caller eq 'login') {
 1516:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1517:                 $is_balancer = 0;
 1518:                 if ($uname ne '' && $udom ne '') {
 1519:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1520:                     
 1521:                         &appenv({'user.loadbalexempt'     => $lonhost,  
 1522:                                  'user.loadbalcheck.time' => time});
 1523:                     }
 1524:                 }
 1525:             }
 1526:         }
 1527:     }
 1528:     return ($is_balancer,$otherserver);
 1529: }
 1530: 
 1531: sub check_balancer_result {
 1532:     my ($result,@hosts) = @_;
 1533:     my ($is_balancer,$currtargets,$currrules);
 1534:     if (ref($result) eq 'HASH') {
 1535:         if ($result->{'lonhost'} ne '') {
 1536:             my $currbalancer = $result->{'lonhost'};
 1537:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1538:                 $is_balancer = 1;
 1539:                 $currtargets = $result->{'targets'};
 1540:                 $currrules = $result->{'rules'};
 1541:             }
 1542:         } else {
 1543:             foreach my $key (keys(%{$result})) {
 1544:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1545:                     (ref($result->{$key}) eq 'HASH')) {
 1546:                     $is_balancer = 1;
 1547:                     $currrules = $result->{$key}{'rules'};
 1548:                     $currtargets = $result->{$key}{'targets'};
 1549:                     last;
 1550:                 }
 1551:             }
 1552:         }
 1553:     }
 1554:     return ($is_balancer,$currtargets,$currrules);
 1555: }
 1556: 
 1557: sub get_loadbalancer_targets {
 1558:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1559:     my $offloadto;
 1560:     if ($rule_in_effect eq 'none') {
 1561:         return [$perlvar{'lonHostID'}];
 1562:     } elsif ($rule_in_effect eq '') {
 1563:         $offloadto = $currtargets;
 1564:     } else {
 1565:         if ($rule_in_effect eq 'homeserver') {
 1566:             my $homeserver = &homeserver($uname,$udom);
 1567:             if ($homeserver ne 'no_host') {
 1568:                 $offloadto = [$homeserver];
 1569:             }
 1570:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1571:             my %domconfig =
 1572:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1573:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1574:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1575:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1576:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1577:                     }
 1578:                 }
 1579:             } else {
 1580:                 my %servers = &internet_dom_servers($udom);
 1581:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1582:                 if (&hostname($remotebalancer) ne '') {
 1583:                     $offloadto = [$remotebalancer];
 1584:                 }
 1585:             }
 1586:         } elsif (&hostname($rule_in_effect) ne '') {
 1587:             $offloadto = [$rule_in_effect];
 1588:         }
 1589:     }
 1590:     return $offloadto;
 1591: }
 1592: 
 1593: sub internet_dom_servers {
 1594:     my ($dom) = @_;
 1595:     my (%uniqservers,%servers);
 1596:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1597:     my @machinedoms = &machine_domains($primaryserver);
 1598:     foreach my $mdom (@machinedoms) {
 1599:         my %currservers = %servers;
 1600:         my %server = &get_servers($mdom);
 1601:         %servers = (%currservers,%server);
 1602:     }
 1603:     my %by_hostname;
 1604:     foreach my $id (keys(%servers)) {
 1605:         push(@{$by_hostname{$servers{$id}}},$id);
 1606:     }
 1607:     foreach my $hostname (sort(keys(%by_hostname))) {
 1608:         if (@{$by_hostname{$hostname}} > 1) {
 1609:             my $match = 0;
 1610:             foreach my $id (@{$by_hostname{$hostname}}) {
 1611:                 if (&host_domain($id) eq $dom) {
 1612:                     $uniqservers{$id} = $hostname;
 1613:                     $match = 1;
 1614:                 }
 1615:             }
 1616:             unless ($match) {
 1617:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1618:             }
 1619:         } else {
 1620:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1621:         }
 1622:     }
 1623:     return %uniqservers;
 1624: }
 1625: 
 1626: sub trusted_domains {
 1627:     my ($cmdtype,$calldom) = @_;
 1628:     my ($trusted,$untrusted);
 1629:     if (&domain($calldom) eq '') {
 1630:         return ($trusted,$untrusted);
 1631:     }
 1632:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1633:         return ($trusted,$untrusted);
 1634:     }
 1635:     my $callprimary = &domain($calldom,'primary');
 1636:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1637:     if ($intcalldom eq '') {
 1638:         return ($trusted,$untrusted);
 1639:     }
 1640: 
 1641:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1642:     unless (defined($cached)) {
 1643:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1644:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1645:         $trustconfig = $domconfig{'trust'};
 1646:     }
 1647:     if (ref($trustconfig)) {
 1648:         my (%possexc,%possinc,@allexc,@allinc); 
 1649:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1650:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1651:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1652:             }
 1653:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1654:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1655:             }
 1656:         }
 1657:         if (keys(%possexc)) {
 1658:             if (keys(%possinc)) {
 1659:                 foreach my $key (sort(keys(%possexc))) {
 1660:                     next if ($key eq $intcalldom);
 1661:                     unless ($possinc{$key}) {
 1662:                         push(@allexc,$key);
 1663:                     }
 1664:                 }
 1665:             } else {
 1666:                 @allexc = sort(keys(%possexc));
 1667:             }
 1668:         }
 1669:         if (keys(%possinc)) {
 1670:             $possinc{$intcalldom} = 1;
 1671:             @allinc = sort(keys(%possinc));
 1672:         }
 1673:         if ((@allexc > 0) || (@allinc > 0)) {
 1674:             my %doms_by_intdom;
 1675:             my %allintdoms = &all_host_intdom();
 1676:             my %alldoms = &all_host_domain();
 1677:             foreach my $key (%allintdoms) {
 1678:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1679:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1680:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1681:                     }
 1682:                 } else {
 1683:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1684:                 }
 1685:             }
 1686:             foreach my $exc (@allexc) {
 1687:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1688:                     $untrusted = $doms_by_intdom{$exc};
 1689:                 }
 1690:             }
 1691:             foreach my $inc (@allinc) {
 1692:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1693:                     $trusted = $doms_by_intdom{$inc};
 1694:                 }
 1695:             }
 1696:         }
 1697:     }
 1698:     return ($trusted,$untrusted);
 1699: }
 1700: 
 1701: sub will_trust {
 1702:     my ($cmdtype,$domain,$possdom) = @_;
 1703:     return 1 if ($domain eq $possdom);
 1704:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1705:     my $willtrust; 
 1706:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1707:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1708:             $willtrust = 1;
 1709:         }
 1710:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1711:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1712:             $willtrust = 1;
 1713:         }
 1714:     } else {
 1715:         $willtrust = 1;
 1716:     }
 1717:     return $willtrust;
 1718: }
 1719: 
 1720: # ---------------------- Find the homebase for a user from domain's lib servers
 1721: 
 1722: my %homecache;
 1723: sub homeserver {
 1724:     my ($uname,$udom,$ignoreBadCache)=@_;
 1725:     my $index="$uname:$udom";
 1726: 
 1727:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1728: 
 1729:     my %servers = &get_servers($udom,'library');
 1730:     foreach my $tryserver (keys(%servers)) {
 1731:         next if ($ignoreBadCache ne 'true' && 
 1732: 		 exists($badServerCache{$tryserver}));
 1733: 
 1734: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1735: 	if ($answer eq 'found') {
 1736: 	    delete($badServerCache{$tryserver}); 
 1737: 	    return $homecache{$index}=$tryserver;
 1738: 	} elsif ($answer eq 'no_host') {
 1739: 	    $badServerCache{$tryserver}=1;
 1740: 	}
 1741:     }    
 1742:     return 'no_host';
 1743: }
 1744: 
 1745: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1746: 
 1747: sub idget {
 1748:     my ($udom,$idsref,$namespace)=@_;
 1749:     my %returnhash=();
 1750:     my @ids=(); 
 1751:     if (ref($idsref) eq 'ARRAY') {
 1752:         @ids = @{$idsref};
 1753:     } else {
 1754:         return %returnhash; 
 1755:     }
 1756:     if ($namespace eq '') {
 1757:         $namespace = 'ids';
 1758:     }
 1759:     
 1760:     my %servers = &get_servers($udom,'library');
 1761:     foreach my $tryserver (keys(%servers)) {
 1762: 	my $idlist=join('&', map { &escape($_); } @ids);
 1763: 	if ($namespace eq 'ids') {
 1764: 	    $idlist=~tr/A-Z/a-z/;
 1765: 	}
 1766: 	my $reply;
 1767: 	if ($namespace eq 'ids') {
 1768: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1769: 	} else {
 1770: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1771: 	}
 1772: 	my @answer=();
 1773: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1774: 	    @answer=split(/\&/,$reply);
 1775: 	}                    ;
 1776: 	my $i;
 1777: 	for ($i=0;$i<=$#ids;$i++) {
 1778: 	    if ($answer[$i]) {
 1779: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1780: 	    }
 1781: 	}
 1782:     }
 1783:     return %returnhash;
 1784: }
 1785: 
 1786: # ------------------------------------- Find the IDs behind a list of usernames
 1787: 
 1788: sub idrget {
 1789:     my ($udom,@unames)=@_;
 1790:     my %returnhash=();
 1791:     foreach my $uname (@unames) {
 1792:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1793:     }
 1794:     return %returnhash;
 1795: }
 1796: 
 1797: # Store away a list of names and associated student/employee IDs or clicker IDs
 1798: 
 1799: sub idput {
 1800:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1801:     my %servers=();
 1802:     my %ids=();
 1803:     my %byid = ();
 1804:     if (ref($idsref) eq 'HASH') {
 1805:         %ids=%{$idsref};
 1806:     }
 1807:     if ($namespace eq '') {
 1808:         $namespace = 'ids'; 
 1809:     }
 1810:     foreach my $uname (keys(%ids)) {
 1811: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1812:         if ($uhom eq '') {
 1813:             $uhom=&homeserver($uname,$udom);
 1814:         }
 1815:         if ($uhom ne 'no_host') {
 1816:             my $esc_unam=&escape($uname);
 1817:             if ($namespace eq 'ids') {
 1818:                 my $id=&escape($ids{$uname});
 1819:                 $id=~tr/A-Z/a-z/;
 1820:                 my $esc_unam=&escape($uname);
 1821:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1822:             } else {
 1823:                 my @currids = split(/,/,$ids{$uname});
 1824:                 foreach my $id (@currids) {
 1825:                     $byid{$uhom}{$id} .= $uname.',';
 1826:                 }
 1827:             }
 1828:         }
 1829:     }
 1830:     if ($namespace eq 'clickers') {
 1831:         foreach my $server (keys(%byid)) {
 1832:             if (ref($byid{$server}) eq 'HASH') {
 1833:                 foreach my $id (keys(%{$byid{$server}})) {
 1834:                     $byid{$server} =~ s/,$//;
 1835:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1836:                 }
 1837:             }
 1838:         }
 1839:     }
 1840:     foreach my $server (keys(%servers)) {
 1841:         $servers{$server} =~ s/\&$//;
 1842:         if ($namespace eq 'ids') {     
 1843:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1844:         } else {
 1845:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1846:         }
 1847:     }
 1848: }
 1849: 
 1850: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1851: 
 1852: sub iddel {
 1853:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1854:     my %result=();
 1855:     my %ids=();
 1856:     my %byid = ();
 1857:     if (ref($idshashref) eq 'HASH') {
 1858:         %ids=%{$idshashref};
 1859:     } else {
 1860:         return %result;
 1861:     }
 1862:     if ($namespace eq '') {
 1863:         $namespace = 'ids';
 1864:     }
 1865:     my %servers=();
 1866:     while (my ($id,$unamestr) = each(%ids)) {
 1867:         if ($namespace eq 'ids') {
 1868:             my $uhom = $uhome;
 1869:             if ($uhom eq '') { 
 1870:                 $uhom=&homeserver($unamestr,$udom);
 1871:             }
 1872:             if ($uhom ne 'no_host') {
 1873:                 $servers{$uhom}.='&'.&escape($id);
 1874:             }
 1875:          } else {
 1876:             my @curritems = split(/,/,$ids{$id});
 1877:             foreach my $uname (@curritems) {
 1878:                 my $uhom = $uhome;
 1879:                 if ($uhom eq '') {
 1880:                     $uhom=&homeserver($uname,$udom);
 1881:                 }
 1882:                 if ($uhom ne 'no_host') { 
 1883:                     $byid{$uhom}{$id} .= $uname.',';
 1884:                 }
 1885:             }
 1886:         }
 1887:     }
 1888:     if ($namespace eq 'clickers') {
 1889:         foreach my $server (keys(%byid)) {
 1890:             if (ref($byid{$server}) eq 'HASH') {
 1891:                 foreach my $id (keys(%{$byid{$server}})) {
 1892:                     $byid{$server}{$id} =~ s/,$//;
 1893:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 1894:                 }
 1895:             }
 1896:         }
 1897:     }
 1898:     foreach my $server (keys(%servers)) {
 1899:         $servers{$server} =~ s/\&$//;
 1900:         if ($namespace eq 'ids') {
 1901:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1902:         } elsif ($namespace eq 'clickers') {
 1903:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 1904:         }
 1905:     }
 1906:     return %result;
 1907: }
 1908: 
 1909: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 1910: 
 1911: sub updateclickers {
 1912:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 1913:     my %clickers;
 1914:     if (ref($idshashref) eq 'HASH') {
 1915:         %clickers=%{$idshashref};
 1916:     } else {
 1917:         return;
 1918:     }
 1919:     my $items='';
 1920:     foreach my $item (keys(%clickers)) {
 1921:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 1922:     }
 1923:     $items=~s/\&$//;
 1924:     my $request = "updateclickers:$udom:$action:$items";
 1925:     if ($critical) {
 1926:         return &critical($request,$uhome);
 1927:     } else {
 1928:         return &reply($request,$uhome);
 1929:     }
 1930: }
 1931: 
 1932: # ------------------------------dump from db file owned by domainconfig user
 1933: sub dump_dom {
 1934:     my ($namespace, $udom, $regexp) = @_;
 1935: 
 1936:     $udom ||= $env{'user.domain'};
 1937: 
 1938:     return () unless $udom;
 1939: 
 1940:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1941: }
 1942: 
 1943: # ------------------------------------------ get items from domain db files   
 1944: 
 1945: sub get_dom {
 1946:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1947:     return if ($udom eq 'public');
 1948:     my $items='';
 1949:     foreach my $item (@$storearr) {
 1950:         $items.=&escape($item).'&';
 1951:     }
 1952:     $items=~s/\&$//;
 1953:     if (!$udom) {
 1954:         $udom=$env{'user.domain'};
 1955:         return if ($udom eq 'public');
 1956:         if (defined(&domain($udom,'primary'))) {
 1957:             $uhome=&domain($udom,'primary');
 1958:         } else {
 1959:             undef($uhome);
 1960:         }
 1961:     } else {
 1962:         if (!$uhome) {
 1963:             if (defined(&domain($udom,'primary'))) {
 1964:                 $uhome=&domain($udom,'primary');
 1965:             }
 1966:         }
 1967:     }
 1968:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1969:         my $rep;
 1970:         if ($namespace =~ /^enc/) {
 1971:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 1972:         } else {
 1973:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1974:         }
 1975:         my %returnhash;
 1976:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1977:             return %returnhash;
 1978:         }
 1979:         my @pairs=split(/\&/,$rep);
 1980:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1981:             return @pairs;
 1982:         }
 1983:         my $i=0;
 1984:         foreach my $item (@$storearr) {
 1985:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1986:             $i++;
 1987:         }
 1988:         return %returnhash;
 1989:     } else {
 1990:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1991:     }
 1992: }
 1993: 
 1994: # -------------------------------------------- put items in domain db files 
 1995: 
 1996: sub put_dom {
 1997:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1998:     if (!$udom) {
 1999:         $udom=$env{'user.domain'};
 2000:         if (defined(&domain($udom,'primary'))) {
 2001:             $uhome=&domain($udom,'primary');
 2002:         } else {
 2003:             undef($uhome);
 2004:         }
 2005:     } else {
 2006:         if (!$uhome) {
 2007:             if (defined(&domain($udom,'primary'))) {
 2008:                 $uhome=&domain($udom,'primary');
 2009:             }
 2010:         }
 2011:     } 
 2012:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2013:         my $items='';
 2014:         foreach my $item (keys(%$storehash)) {
 2015:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2016:         }
 2017:         $items=~s/\&$//;
 2018:         if ($namespace =~ /^enc/) {
 2019:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2020:         } else {
 2021:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2022:         }
 2023:     } else {
 2024:         &logthis("put_dom failed - no homeserver and/or domain");
 2025:     }
 2026: }
 2027: 
 2028: # --------------------- newput for items in db file owned by domainconfig user
 2029: sub newput_dom {
 2030:     my ($namespace,$storehash,$udom) = @_;
 2031:     my $result;
 2032:     if (!$udom) {
 2033:         $udom=$env{'user.domain'};
 2034:     }
 2035:     if ($udom) {
 2036:         my $uname = &get_domainconfiguser($udom);
 2037:         $result = &newput($namespace,$storehash,$udom,$uname);
 2038:     }
 2039:     return $result;
 2040: }
 2041: 
 2042: # --------------------- delete for items in db file owned by domainconfig user
 2043: sub del_dom {
 2044:     my ($namespace,$storearr,$udom)=@_;
 2045:     if (ref($storearr) eq 'ARRAY') {
 2046:         if (!$udom) {
 2047:             $udom=$env{'user.domain'};
 2048:         }
 2049:         if ($udom) {
 2050:             my $uname = &get_domainconfiguser($udom); 
 2051:             return &del($namespace,$storearr,$udom,$uname);
 2052:         }
 2053:     }
 2054: }
 2055: 
 2056: # ----------------------------------construct domainconfig user for a domain 
 2057: sub get_domainconfiguser {
 2058:     my ($udom) = @_;
 2059:     return $udom.'-domainconfig';
 2060: }
 2061: 
 2062: sub retrieve_inst_usertypes {
 2063:     my ($udom) = @_;
 2064:     my (%returnhash,@order);
 2065:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2066:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2067:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2068:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2069:     } else {
 2070:         if (defined(&domain($udom,'primary'))) {
 2071:             my $uhome=&domain($udom,'primary');
 2072:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2073:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2074:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2075:                 return (\%returnhash,\@order);
 2076:             }
 2077:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2078:             my @pairs=split(/\&/,$hashitems);
 2079:             foreach my $item (@pairs) {
 2080:                 my ($key,$value)=split(/=/,$item,2);
 2081:                 $key = &unescape($key);
 2082:                 next if ($key =~ /^error: 2 /);
 2083:                 $returnhash{$key}=&thaw_unescape($value);
 2084:             }
 2085:             my @esc_order = split(/\&/,$orderitems);
 2086:             foreach my $item (@esc_order) {
 2087:                 push(@order,&unescape($item));
 2088:             }
 2089:         } else {
 2090:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2091:         }
 2092:         return (\%returnhash,\@order);
 2093:     }
 2094: }
 2095: 
 2096: sub is_domainimage {
 2097:     my ($url) = @_;
 2098:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2099:         if (&domain($1) ne '') {
 2100:             return '1';
 2101:         }
 2102:     }
 2103:     return;
 2104: }
 2105: 
 2106: sub inst_directory_query {
 2107:     my ($srch) = @_;
 2108:     my $udom = $srch->{'srchdomain'};
 2109:     my %results;
 2110:     my $homeserver = &domain($udom,'primary');
 2111:     my $outcome;
 2112:     if ($homeserver ne '') {
 2113:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2114:             if ($srch->{'srchby'} eq 'email') {
 2115:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2116:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2117:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2118:                     (($major == 2) && ($minor < 12))) {
 2119:                     return;
 2120:                 }
 2121:             }
 2122:         }
 2123: 	my $queryid=&reply("querysend:instdirsearch:".
 2124: 			   &escape($srch->{'srchby'}).':'.
 2125: 			   &escape($srch->{'srchterm'}).':'.
 2126: 			   &escape($srch->{'srchtype'}),$homeserver);
 2127: 	my $host=&hostname($homeserver);
 2128: 	if ($queryid !~/^\Q$host\E\_/) {
 2129: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2130: 	    return;
 2131: 	}
 2132: 	my $response = &get_query_reply($queryid);
 2133: 	my $maxtries = 5;
 2134: 	my $tries = 1;
 2135: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2136: 	    $response = &get_query_reply($queryid);
 2137: 	    $tries ++;
 2138: 	}
 2139: 
 2140:         if (!&error($response) && $response ne 'refused') {
 2141:             if ($response eq 'unavailable') {
 2142:                 $outcome = $response;
 2143:             } else {
 2144:                 $outcome = 'ok';
 2145:                 my @matches = split(/\n/,$response);
 2146:                 foreach my $match (@matches) {
 2147:                     my ($key,$value) = split(/=/,$match);
 2148:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2149:                 }
 2150:             }
 2151:         }
 2152:     }
 2153:     return ($outcome,%results);
 2154: }
 2155: 
 2156: sub usersearch {
 2157:     my ($srch) = @_;
 2158:     my $dom = $srch->{'srchdomain'};
 2159:     my %results;
 2160:     my %libserv = &all_library();
 2161:     my $query = 'usersearch';
 2162:     foreach my $tryserver (keys(%libserv)) {
 2163:         if (&host_domain($tryserver) eq $dom) {
 2164:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2165:                 if ($srch->{'srchby'} eq 'email') {
 2166:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2167:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2168:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2169:                              (($major == 2) && ($minor < 12)));
 2170:                 }
 2171:             }
 2172:             my $host=&hostname($tryserver);
 2173:             my $queryid=
 2174:                 &reply("querysend:".&escape($query).':'.
 2175:                        &escape($srch->{'srchby'}).':'.
 2176:                        &escape($srch->{'srchtype'}).':'.
 2177:                        &escape($srch->{'srchterm'}),$tryserver);
 2178:             if ($queryid !~/^\Q$host\E\_/) {
 2179:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2180:                 next;
 2181:             }
 2182:             my $reply = &get_query_reply($queryid);
 2183:             my $maxtries = 1;
 2184:             my $tries = 1;
 2185:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2186:                 $reply = &get_query_reply($queryid);
 2187:                 $tries ++;
 2188:             }
 2189:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2190:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2191:             } else {
 2192:                 my @matches;
 2193:                 if ($reply =~ /\n/) {
 2194:                     @matches = split(/\n/,$reply);
 2195:                 } else {
 2196:                     @matches = split(/\&/,$reply);
 2197:                 }
 2198:                 foreach my $match (@matches) {
 2199:                     my ($uname,$udom,%userhash);
 2200:                     foreach my $entry (split(/:/,$match)) {
 2201:                         my ($key,$value) =
 2202:                             map {&unescape($_);} split(/=/,$entry);
 2203:                         $userhash{$key} = $value;
 2204:                         if ($key eq 'username') {
 2205:                             $uname = $value;
 2206:                         } elsif ($key eq 'domain') {
 2207:                             $udom = $value;
 2208:                         }
 2209:                     }
 2210:                     $results{$uname.':'.$udom} = \%userhash;
 2211:                 }
 2212:             }
 2213:         }
 2214:     }
 2215:     return %results;
 2216: }
 2217: 
 2218: sub get_instuser {
 2219:     my ($udom,$uname,$id) = @_;
 2220:     my $homeserver = &domain($udom,'primary');
 2221:     my ($outcome,%results);
 2222:     if ($homeserver ne '') {
 2223:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2224:                            &escape($id).':'.&escape($udom),$homeserver);
 2225:         my $host=&hostname($homeserver);
 2226:         if ($queryid !~/^\Q$host\E\_/) {
 2227:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2228:             return;
 2229:         }
 2230:         my $response = &get_query_reply($queryid);
 2231:         my $maxtries = 5;
 2232:         my $tries = 1;
 2233:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2234:             $response = &get_query_reply($queryid);
 2235:             $tries ++;
 2236:         }
 2237:         if (!&error($response) && $response ne 'refused') {
 2238:             if ($response eq 'unavailable') {
 2239:                 $outcome = $response;
 2240:             } else {
 2241:                 $outcome = 'ok';
 2242:                 my @matches = split(/\n/,$response);
 2243:                 foreach my $match (@matches) {
 2244:                     my ($key,$value) = split(/=/,$match);
 2245:                     $results{&unescape($key)} = &thaw_unescape($value);
 2246:                 }
 2247:             }
 2248:         }
 2249:     }
 2250:     my %userinfo;
 2251:     if (ref($results{$uname}) eq 'HASH') {
 2252:         %userinfo = %{$results{$uname}};
 2253:     } 
 2254:     return ($outcome,%userinfo);
 2255: }
 2256: 
 2257: sub get_multiple_instusers {
 2258:     my ($udom,$users,$caller) = @_;
 2259:     my ($outcome,$results);
 2260:     if (ref($users) eq 'HASH') {
 2261:         my $count = keys(%{$users}); 
 2262:         my $requested = &freeze_escape($users);
 2263:         my $homeserver = &domain($udom,'primary');
 2264:         if ($homeserver ne '') {
 2265:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2266:             my $host=&hostname($homeserver);
 2267:             if ($queryid !~/^\Q$host\E\_/) {
 2268:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2269:                          ' for host: '.$homeserver.'in domain '.$udom);
 2270:                 return ($outcome,$results);
 2271:             }
 2272:             my $response = &get_query_reply($queryid);
 2273:             my $maxtries = 5;
 2274:             if ($count > 100) {
 2275:                 $maxtries = 1+int($count/20);
 2276:             }
 2277:             my $tries = 1;
 2278:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2279:                 $response = &get_query_reply($queryid);
 2280:                 $tries ++;
 2281:             }
 2282:             if ($response eq '') {
 2283:                 $results = {};
 2284:                 foreach my $key (keys(%{$users})) {
 2285:                     my ($uname,$id);
 2286:                     if ($caller eq 'id') {
 2287:                         $id = $key;
 2288:                     } else {
 2289:                         $uname = $key;
 2290:                     }
 2291:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2292:                     $outcome = $resp;
 2293:                     if ($resp eq 'ok') {
 2294:                         %{$results} = (%{$results}, %info);
 2295:                     } else {
 2296:                         last;
 2297:                     }
 2298:                 }
 2299:             } elsif(!&error($response) && ($response ne 'refused')) {
 2300:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2301:                     $outcome = $response;
 2302:                 } else {
 2303:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2304:                     if ($outcome eq 'ok') {
 2305:                         $results = &thaw_unescape($userdata); 
 2306:                     }
 2307:                 }
 2308:             }
 2309:         }
 2310:     }
 2311:     return ($outcome,$results);
 2312: }
 2313: 
 2314: sub inst_rulecheck {
 2315:     my ($udom,$uname,$id,$item,$rules) = @_;
 2316:     my %returnhash;
 2317:     if ($udom ne '') {
 2318:         if (ref($rules) eq 'ARRAY') {
 2319:             @{$rules} = map {&escape($_);} (@{$rules});
 2320:             my $rulestr = join(':',@{$rules});
 2321:             my $homeserver=&domain($udom,'primary');
 2322:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2323:                 my $response;
 2324:                 if ($item eq 'username') {                
 2325:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2326:                                               ':'.&escape($uname).':'.$rulestr,
 2327:                                               $homeserver));
 2328:                 } elsif ($item eq 'id') {
 2329:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2330:                                               ':'.&escape($id).':'.$rulestr,
 2331:                                               $homeserver));
 2332:                 } elsif ($item eq 'selfcreate') {
 2333:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2334:                                                &escape($udom).':'.&escape($uname).
 2335:                                               ':'.$rulestr,$homeserver));
 2336:                 }
 2337:                 if ($response ne 'refused') {
 2338:                     my @pairs=split(/\&/,$response);
 2339:                     foreach my $item (@pairs) {
 2340:                         my ($key,$value)=split(/=/,$item,2);
 2341:                         $key = &unescape($key);
 2342:                         next if ($key =~ /^error: 2 /);
 2343:                         $returnhash{$key}=&thaw_unescape($value);
 2344:                     }
 2345:                 }
 2346:             }
 2347:         }
 2348:     }
 2349:     return %returnhash;
 2350: }
 2351: 
 2352: sub inst_userrules {
 2353:     my ($udom,$check) = @_;
 2354:     my (%ruleshash,@ruleorder);
 2355:     if ($udom ne '') {
 2356:         my $homeserver=&domain($udom,'primary');
 2357:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2358:             my $response;
 2359:             if ($check eq 'id') {
 2360:                 $response=&reply('instidrules:'.&escape($udom),
 2361:                                  $homeserver);
 2362:             } elsif ($check eq 'email') {
 2363:                 $response=&reply('instemailrules:'.&escape($udom),
 2364:                                  $homeserver);
 2365:             } else {
 2366:                 $response=&reply('instuserrules:'.&escape($udom),
 2367:                                  $homeserver);
 2368:             }
 2369:             if (($response ne 'refused') && ($response ne 'error') && 
 2370:                 ($response ne 'unknown_cmd') && 
 2371:                 ($response ne 'no_such_host')) {
 2372:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2373:                 my @pairs=split(/\&/,$hashitems);
 2374:                 foreach my $item (@pairs) {
 2375:                     my ($key,$value)=split(/=/,$item,2);
 2376:                     $key = &unescape($key);
 2377:                     next if ($key =~ /^error: 2 /);
 2378:                     $ruleshash{$key}=&thaw_unescape($value);
 2379:                 }
 2380:                 my @esc_order = split(/\&/,$orderitems);
 2381:                 foreach my $item (@esc_order) {
 2382:                     push(@ruleorder,&unescape($item));
 2383:                 }
 2384:             }
 2385:         }
 2386:     }
 2387:     return (\%ruleshash,\@ruleorder);
 2388: }
 2389: 
 2390: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2391: 
 2392: sub get_domain_defaults {
 2393:     my ($domain,$ignore_cache) = @_;
 2394:     return if (($domain eq '') || ($domain eq 'public'));
 2395:     my $cachetime = 60*60*24;
 2396:     unless ($ignore_cache) {
 2397:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2398:         if (defined($cached)) {
 2399:             if (ref($result) eq 'HASH') {
 2400:                 return %{$result};
 2401:             }
 2402:         }
 2403:     }
 2404:     my %domdefaults;
 2405:     my %domconfig =
 2406:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2407:                                   'requestcourses','inststatus',
 2408:                                   'coursedefaults','usersessions',
 2409:                                   'requestauthor','selfenrollment',
 2410:                                   'coursecategories','ssl','autoenroll',
 2411:                                   'trust','helpsettings'],$domain);
 2412:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2413:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2414:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2415:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2416:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2417:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2418:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2419:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2420:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2421:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2422:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2423:     } else {
 2424:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2425:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2426:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2427:     }
 2428:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2429:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2430:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2431:         } else {
 2432:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2433:         }
 2434:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2435:         foreach my $item (@usertools) {
 2436:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2437:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2438:             }
 2439:         }
 2440:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2441:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2442:         }
 2443:     }
 2444:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2445:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2446:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2447:         }
 2448:     }
 2449:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2450:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2451:     }
 2452:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2453:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2454:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2455:         }
 2456:     }
 2457:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2458:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2459:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2460:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2461:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2462:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2463:         }
 2464:         foreach my $type (@coursetypes) {
 2465:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2466:                 unless ($type eq 'community') {
 2467:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2468:                 }
 2469:             }
 2470:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2471:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2472:             }
 2473:             if ($domdefaults{'postsubmit'} eq 'on') {
 2474:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2475:                     $domdefaults{$type.'postsubtimeout'} = 
 2476:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2477:                 }
 2478:             }
 2479:         }
 2480:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2481:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2482:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2483:                 if (@clonecodes) {
 2484:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2485:                 }
 2486:             }
 2487:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2488:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2489:         }
 2490:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2491:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2492:         } 
 2493:     }
 2494:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2495:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2496:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2497:         }
 2498:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2499:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2500:         }
 2501:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2502:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2503:         }
 2504:     }
 2505:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2506:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2507:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2508:                             'approval','limit');
 2509:             foreach my $type (@coursetypes) {
 2510:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2511:                     my @mgrdc = ();
 2512:                     foreach my $item (@settings) {
 2513:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2514:                             push(@mgrdc,$item);
 2515:                         }
 2516:                     }
 2517:                     if (@mgrdc) {
 2518:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2519:                     }
 2520:                 }
 2521:             }
 2522:         }
 2523:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2524:             foreach my $type (@coursetypes) {
 2525:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2526:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2527:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2528:                     }
 2529:                 }
 2530:             }
 2531:         }
 2532:     }
 2533:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2534:         $domdefaults{'catauth'} = 'std';
 2535:         $domdefaults{'catunauth'} = 'std';
 2536:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2537:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2538:         }
 2539:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2540:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2541:         }
 2542:     }
 2543:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2544:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2545:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2546:         }
 2547:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2548:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2549:         }
 2550:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2551:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2552:         }
 2553:     }
 2554:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2555:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2556:         foreach my $prefix (@prefixes) {
 2557:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2558:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2559:             }
 2560:         }
 2561:     }
 2562:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2563:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2564:     }
 2565:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2566:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2567:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2568:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2569:         }
 2570:     }
 2571:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2572:     return %domdefaults;
 2573: }
 2574: 
 2575: sub course_portal_url {
 2576:     my ($cnum,$cdom) = @_;
 2577:     my $chome = &homeserver($cnum,$cdom);
 2578:     my $hostname = &hostname($chome);
 2579:     my $protocol = $protocol{$chome};
 2580:     $protocol = 'http' if ($protocol ne 'https');
 2581:     my %domdefaults = &get_domain_defaults($cdom);
 2582:     my $firsturl;
 2583:     if ($domdefaults{'portal_def'}) {
 2584:         $firsturl = $domdefaults{'portal_def'};
 2585:     } else {
 2586:         $firsturl = $protocol.'://'.$hostname;
 2587:     }
 2588:     return $firsturl;
 2589: }
 2590: 
 2591: # --------------------------------------------------- Assign a key to a student
 2592: 
 2593: sub assign_access_key {
 2594: #
 2595: # a valid key looks like uname:udom#comments
 2596: # comments are being appended
 2597: #
 2598:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2599:     $kdom=
 2600:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2601:     $knum=
 2602:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2603:     $cdom=
 2604:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2605:     $cnum=
 2606:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2607:     $udom=$env{'user.name'} unless (defined($udom));
 2608:     $uname=$env{'user.domain'} unless (defined($uname));
 2609:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2610:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2611:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2612:                                                   # assigned to this person
 2613:                                                   # - this should not happen,
 2614:                                                   # unless something went wrong
 2615:                                                   # the first time around
 2616: # ready to assign
 2617:         $logentry=$1.'; '.$logentry;
 2618:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2619:                                                  $kdom,$knum) eq 'ok') {
 2620: # key now belongs to user
 2621: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2622:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2623:                 &appenv({'environment.'.$envkey => $ckey});
 2624:                 return 'ok';
 2625:             } else {
 2626:                 return 
 2627:   'error: Count not permanently assign key, will need to be re-entered later.';
 2628: 	    }
 2629:         } else {
 2630:             return 'error: Could not assign key, try again later.';
 2631:         }
 2632:     } elsif (!$existing{$ckey}) {
 2633: # the key does not exist
 2634: 	return 'error: The key does not exist';
 2635:     } else {
 2636: # the key is somebody else's
 2637: 	return 'error: The key is already in use';
 2638:     }
 2639: }
 2640: 
 2641: # ------------------------------------------ put an additional comment on a key
 2642: 
 2643: sub comment_access_key {
 2644: #
 2645: # a valid key looks like uname:udom#comments
 2646: # comments are being appended
 2647: #
 2648:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2649:     $cdom=
 2650:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2651:     $cnum=
 2652:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2653:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2654:     if ($existing{$ckey}) {
 2655:         $existing{$ckey}.='; '.$logentry;
 2656: # ready to assign
 2657:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2658:                                                  $cdom,$cnum) eq 'ok') {
 2659: 	    return 'ok';
 2660:         } else {
 2661: 	    return 'error: Count not store comment.';
 2662:         }
 2663:     } else {
 2664: # the key does not exist
 2665: 	return 'error: The key does not exist';
 2666:     }
 2667: }
 2668: 
 2669: # ------------------------------------------------------ Generate a set of keys
 2670: 
 2671: sub generate_access_keys {
 2672:     my ($number,$cdom,$cnum,$logentry)=@_;
 2673:     $cdom=
 2674:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2675:     $cnum=
 2676:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2677:     unless (&allowed('mky',$cdom)) { return 0; }
 2678:     unless (($cdom) && ($cnum)) { return 0; }
 2679:     if ($number>10000) { return 0; }
 2680:     sleep(2); # make sure don't get same seed twice
 2681:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2682:     my $total=0;
 2683:     for (my $i=1;$i<=$number;$i++) {
 2684:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2685:                   sprintf("%lx",int(100000*rand)).'-'.
 2686:                   sprintf("%lx",int(100000*rand));
 2687:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2688:        $newkey=~s/0/h/g; # and also 0 and O
 2689:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2690:        if ($existing{$newkey}) {
 2691:            $i--;
 2692:        } else {
 2693: 	  if (&put('accesskeys',
 2694:               { $newkey => '# generated '.localtime().
 2695:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2696:                            '; '.$logentry },
 2697: 		   $cdom,$cnum) eq 'ok') {
 2698:               $total++;
 2699: 	  }
 2700:        }
 2701:     }
 2702:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2703:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2704:     return $total;
 2705: }
 2706: 
 2707: # ------------------------------------------------------- Validate an accesskey
 2708: 
 2709: sub validate_access_key {
 2710:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2711:     $cdom=
 2712:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2713:     $cnum=
 2714:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2715:     $udom=$env{'user.domain'} unless (defined($udom));
 2716:     $uname=$env{'user.name'} unless (defined($uname));
 2717:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2718:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2719: }
 2720: 
 2721: # ------------------------------------- Find the section of student in a course
 2722: sub devalidate_getsection_cache {
 2723:     my ($udom,$unam,$courseid)=@_;
 2724:     my $hashid="$udom:$unam:$courseid";
 2725:     &devalidate_cache_new('getsection',$hashid);
 2726: }
 2727: 
 2728: sub courseid_to_courseurl {
 2729:     my ($courseid) = @_;
 2730:     #already url style courseid
 2731:     return $courseid if ($courseid =~ m{^/});
 2732: 
 2733:     if (exists($env{'course.'.$courseid.'.num'})) {
 2734: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2735: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2736: 	return "/$cdom/$cnum";
 2737:     }
 2738: 
 2739:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2740:     if (exists($courseinfo{'num'})) {
 2741: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2742:     }
 2743: 
 2744:     return undef;
 2745: }
 2746: 
 2747: sub getsection {
 2748:     my ($udom,$unam,$courseid)=@_;
 2749:     my $cachetime=1800;
 2750: 
 2751:     my $hashid="$udom:$unam:$courseid";
 2752:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2753:     if (defined($cached)) { return $result; }
 2754: 
 2755:     my %Pending; 
 2756:     my %Expired;
 2757:     #
 2758:     # Each role can either have not started yet (pending), be active, 
 2759:     #    or have expired.
 2760:     #
 2761:     # If there is an active role, we are done.
 2762:     #
 2763:     # If there is more than one role which has not started yet, 
 2764:     #     choose the one which will start sooner
 2765:     # If there is one role which has not started yet, return it.
 2766:     #
 2767:     # If there is more than one expired role, choose the one which ended last.
 2768:     # If there is a role which has expired, return it.
 2769:     #
 2770:     $courseid = &courseid_to_courseurl($courseid);
 2771:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2772:     foreach my $key (keys(%roleshash)) {
 2773:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2774:         my $section=$1;
 2775:         if ($key eq $courseid.'_st') { $section=''; }
 2776:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2777:         my $now=time;
 2778:         if (defined($end) && $end && ($now > $end)) {
 2779:             $Expired{$end}=$section;
 2780:             next;
 2781:         }
 2782:         if (defined($start) && $start && ($now < $start)) {
 2783:             $Pending{$start}=$section;
 2784:             next;
 2785:         }
 2786:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2787:     }
 2788:     #
 2789:     # Presumedly there will be few matching roles from the above
 2790:     # loop and the sorting time will be negligible.
 2791:     if (scalar(keys(%Pending))) {
 2792:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2793:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2794:     } 
 2795:     if (scalar(keys(%Expired))) {
 2796:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2797:         my $time = pop(@sorted);
 2798:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2799:     }
 2800:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2801: }
 2802: 
 2803: sub save_cache {
 2804:     &purge_remembered();
 2805:     #&Apache::loncommon::validate_page();
 2806:     undef(%env);
 2807:     undef($env_loaded);
 2808: }
 2809: 
 2810: my $to_remember=-1;
 2811: my %remembered;
 2812: my %accessed;
 2813: my $kicks=0;
 2814: my $hits=0;
 2815: sub make_key {
 2816:     my ($name,$id) = @_;
 2817:     if (length($id) > 65 
 2818: 	&& length(&escape($id)) > 200) {
 2819: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2820:     }
 2821:     return &escape($name.':'.$id);
 2822: }
 2823: 
 2824: sub devalidate_cache_new {
 2825:     my ($name,$id,$debug) = @_;
 2826:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2827:     my $remembered_id=$name.':'.$id;
 2828:     $id=&make_key($name,$id);
 2829:     $memcache->delete($id);
 2830:     delete($remembered{$remembered_id});
 2831:     delete($accessed{$remembered_id});
 2832: }
 2833: 
 2834: sub is_cached_new {
 2835:     my ($name,$id,$debug) = @_;
 2836:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2837:     if (exists($remembered{$remembered_id})) {
 2838: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2839: 	$accessed{$remembered_id}=[&gettimeofday()];
 2840: 	$hits++;
 2841: 	return ($remembered{$remembered_id},1);
 2842:     }
 2843:     $id=&make_key($name,$id);
 2844:     my $value = $memcache->get($id);
 2845:     if (!(defined($value))) {
 2846: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2847: 	return (undef,undef);
 2848:     }
 2849:     if ($value eq '__undef__') {
 2850: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2851: 	$value=undef;
 2852:     }
 2853:     &make_room($remembered_id,$value,$debug);
 2854:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2855:     return ($value,1);
 2856: }
 2857: 
 2858: sub do_cache_new {
 2859:     my ($name,$id,$value,$time,$debug) = @_;
 2860:     my $remembered_id=$name.':'.$id;
 2861:     $id=&make_key($name,$id);
 2862:     my $setvalue=$value;
 2863:     if (!defined($setvalue)) {
 2864: 	$setvalue='__undef__';
 2865:     }
 2866:     if (!defined($time) ) {
 2867: 	$time=600;
 2868:     }
 2869:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2870:     my $result = $memcache->set($id,$setvalue,$time);
 2871:     if (! $result) {
 2872: 	&logthis("caching of id -> $id  failed");
 2873: 	$memcache->disconnect_all();
 2874:     }
 2875:     # need to make a copy of $value
 2876:     &make_room($remembered_id,$value,$debug);
 2877:     return $value;
 2878: }
 2879: 
 2880: sub make_room {
 2881:     my ($remembered_id,$value,$debug)=@_;
 2882: 
 2883:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2884:                                     : $value;
 2885:     if ($to_remember<0) { return; }
 2886:     $accessed{$remembered_id}=[&gettimeofday()];
 2887:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2888:     my $to_kick;
 2889:     my $max_time=0;
 2890:     foreach my $other (keys(%accessed)) {
 2891: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2892: 	    $to_kick=$other;
 2893: 	    $max_time=&tv_interval($accessed{$other});
 2894: 	}
 2895:     }
 2896:     delete($remembered{$to_kick});
 2897:     delete($accessed{$to_kick});
 2898:     $kicks++;
 2899:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2900:     return;
 2901: }
 2902: 
 2903: sub purge_remembered {
 2904:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2905:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2906:     undef(%remembered);
 2907:     undef(%accessed);
 2908: }
 2909: # ------------------------------------- Read an entry from a user's environment
 2910: 
 2911: sub userenvironment {
 2912:     my ($udom,$unam,@what)=@_;
 2913:     my $items;
 2914:     foreach my $item (@what) {
 2915:         $items.=&escape($item).'&';
 2916:     }
 2917:     $items=~s/\&$//;
 2918:     my %returnhash=();
 2919:     my $uhome = &homeserver($unam,$udom);
 2920:     unless ($uhome eq 'no_host') {
 2921:         my @answer=split(/\&/, 
 2922:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2923:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2924:             return %returnhash;
 2925:         }
 2926:         my $i;
 2927:         for ($i=0;$i<=$#what;$i++) {
 2928: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2929:         }
 2930:     }
 2931:     return %returnhash;
 2932: }
 2933: 
 2934: # ---------------------------------------------------------- Get a studentphoto
 2935: sub studentphoto {
 2936:     my ($udom,$unam,$ext) = @_;
 2937:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2938:     if (defined($env{'request.course.id'})) {
 2939:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2940:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2941:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2942:             } else {
 2943:                 my ($result,$perm_reqd)=
 2944: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2945:                 if ($result eq 'ok') {
 2946:                     if (!($perm_reqd eq 'yes')) {
 2947:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2948:                     }
 2949:                 }
 2950:             }
 2951:         }
 2952:     } else {
 2953:         my ($result,$perm_reqd) = 
 2954: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2955:         if ($result eq 'ok') {
 2956:             if (!($perm_reqd eq 'yes')) {
 2957:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2958:             }
 2959:         }
 2960:     }
 2961:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2962: }
 2963: 
 2964: sub retrievestudentphoto {
 2965:     my ($udom,$unam,$ext,$type) = @_;
 2966:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2967:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2968:     if ($ret eq 'ok') {
 2969:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2970:         if ($type eq 'thumbnail') {
 2971:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2972:         }
 2973:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2974:         return $tokenurl;
 2975:     } else {
 2976:         if ($type eq 'thumbnail') {
 2977:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2978:         } else { 
 2979:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2980:         }
 2981:     }
 2982: }
 2983: 
 2984: # -------------------------------------------------------------------- New chat
 2985: 
 2986: sub chatsend {
 2987:     my ($newentry,$anon,$group)=@_;
 2988:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2989:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2990:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2991:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2992: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2993: 		   &escape($newentry)).':'.$group,$chome);
 2994: }
 2995: 
 2996: # ------------------------------------------ Find current version of a resource
 2997: 
 2998: sub getversion {
 2999:     my $fname=&clutter(shift);
 3000:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3001:     return &currentversion(&filelocation('',$fname));
 3002: }
 3003: 
 3004: sub currentversion {
 3005:     my $fname=shift;
 3006:     my $author=$fname;
 3007:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3008:     my ($udom,$uname)=split(/\//,$author);
 3009:     my $home=&homeserver($uname,$udom);
 3010:     if ($home eq 'no_host') { 
 3011:         return -1; 
 3012:     }
 3013:     my $answer=&reply("currentversion:$fname",$home);
 3014:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3015: 	return -1;
 3016:     }
 3017:     return $answer;
 3018: }
 3019: 
 3020: #
 3021: # Return special version number of resource if set by override, empty otherwise
 3022: #
 3023: sub usedversion {
 3024:     my $fname=shift;
 3025:     unless ($fname) { $fname=$env{'request.uri'}; }
 3026:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3027:     if ($urlversion) { return $urlversion; }
 3028:     return '';
 3029: }
 3030: 
 3031: # ----------------------------- Subscribe to a resource, return URL if possible
 3032: 
 3033: sub subscribe {
 3034:     my $fname=shift;
 3035:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3036:     $fname=~s/[\n\r]//g;
 3037:     my $author=$fname;
 3038:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3039:     my ($udom,$uname)=split(/\//,$author);
 3040:     my $home=homeserver($uname,$udom);
 3041:     if ($home eq 'no_host') {
 3042:         return 'not_found';
 3043:     }
 3044:     my $answer=reply("sub:$fname",$home);
 3045:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3046: 	$answer.=' by '.$home;
 3047:     }
 3048:     return $answer;
 3049: }
 3050:     
 3051: # -------------------------------------------------------------- Replicate file
 3052: 
 3053: sub repcopy {
 3054:     my $filename=shift;
 3055:     $filename=~s/\/+/\//g;
 3056:     my $londocroot = $perlvar{'lonDocRoot'};
 3057:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3058:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3059:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3060: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3061: 	return &repcopy_userfile($filename);
 3062:     }
 3063:     $filename=~s/[\n\r]//g;
 3064:     my $transname="$filename.in.transfer";
 3065: # FIXME: this should flock
 3066:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3067:     my $remoteurl=subscribe($filename);
 3068:     if ($remoteurl =~ /^con_lost by/) {
 3069: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3070:            return 'unavailable';
 3071:     } elsif ($remoteurl eq 'not_found') {
 3072: 	   #&logthis("Subscribe returned not_found: $filename");
 3073: 	   return 'not_found';
 3074:     } elsif ($remoteurl =~ /^rejected by/) {
 3075: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3076:            return 'forbidden';
 3077:     } elsif ($remoteurl eq 'directory') {
 3078:            return 'ok';
 3079:     } else {
 3080:         my $author=$filename;
 3081:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3082:         my ($udom,$uname)=split(/\//,$author);
 3083:         my $home=homeserver($uname,$udom);
 3084:         unless ($home eq $perlvar{'lonHostID'}) {
 3085:            my @parts=split(/\//,$filename);
 3086:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3087:            if ($path ne "$londocroot/res") {
 3088:                &logthis("Malconfiguration for replication: $filename");
 3089: 	       return 'bad_request';
 3090:            }
 3091:            my $count;
 3092:            for ($count=5;$count<$#parts;$count++) {
 3093:                $path.="/$parts[$count]";
 3094:                if ((-e $path)!=1) {
 3095: 		   mkdir($path,0777);
 3096:                }
 3097:            }
 3098:            my $request=new HTTP::Request('GET',"$remoteurl");
 3099:            my $response;
 3100:            if ($remoteurl =~ m{/raw/}) {
 3101:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3102:            } else {
 3103:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3104:            }
 3105:            if ($response->is_error()) {
 3106: 	       unlink($transname);
 3107:                my $message=$response->status_line;
 3108:                &logthis("<font color=\"blue\">WARNING:"
 3109:                        ." LWP get: $message: $filename</font>");
 3110:                return 'unavailable';
 3111:            } else {
 3112: 	       if ($remoteurl!~/\.meta$/) {
 3113:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3114:                   my $mresponse;
 3115:                   if ($remoteurl =~ m{/raw/}) {
 3116:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3117:                   } else {
 3118:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3119:                   }
 3120:                   if ($mresponse->is_error()) {
 3121: 		      unlink($filename.'.meta');
 3122:                       &logthis(
 3123:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3124:                   }
 3125: 	       }
 3126:                rename($transname,$filename);
 3127:                return 'ok';
 3128:            }
 3129:        }
 3130:     }
 3131: }
 3132: 
 3133: # ------------------------------------------------ Get server side include body
 3134: sub ssi_body {
 3135:     my ($filelink,%form)=@_;
 3136:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3137:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3138:     }
 3139:     my $output='';
 3140:     my $response;
 3141:     if ($filelink=~/^https?\:/) {
 3142:        ($output,$response)=&externalssi($filelink);
 3143:     } else {
 3144:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3145:        $filelink .= 'inhibitmenu=yes';
 3146:        ($output,$response)=&ssi($filelink,%form);
 3147:     }
 3148:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3149:     $output=~s/^.*?\<body[^\>]*\>//si;
 3150:     $output=~s/\<\/body\s*\>.*?$//si;
 3151:     if (wantarray) {
 3152:         return ($output, $response);
 3153:     } else {
 3154:         return $output;
 3155:     }
 3156: }
 3157: 
 3158: # --------------------------------------------------------- Server Side Include
 3159: 
 3160: sub absolute_url {
 3161:     my ($host_name) = @_;
 3162:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3163:     if ($host_name eq '') {
 3164: 	$host_name = $ENV{'SERVER_NAME'};
 3165:     }
 3166:     return $protocol.$host_name;
 3167: }
 3168: 
 3169: #
 3170: #   Server side include.
 3171: # Parameters:
 3172: #  fn     Possibly encrypted resource name/id.
 3173: #  form   Hash that describes how the rendering should be done
 3174: #         and other things.
 3175: # Returns:
 3176: #   Scalar context: The content of the response.
 3177: #   Array context:  2 element list of the content and the full response object.
 3178: #     
 3179: sub ssi {
 3180: 
 3181:     my ($fn,%form)=@_;
 3182:     my $request;
 3183: 
 3184:     $form{'no_update_last_known'}=1;
 3185:     &Apache::lonenc::check_encrypt(\$fn);
 3186:     if (%form) {
 3187:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3188:       $request->content(join('&',map { 
 3189:             my $name = escape($_);
 3190:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3191:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3192:             : &escape($form{$_}) );    
 3193:         } keys(%form)));
 3194:     } else {
 3195:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3196:     }
 3197: 
 3198:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3199:     my $lonhost = $perlvar{'lonHostID'};
 3200:     my $islocal;
 3201:     if (($env{'request.course.id'}) &&
 3202:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3203:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3204:         ($form{'grade_symb'} ne '') &&
 3205:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3206:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3207:         $islocal = 1;
 3208:     }
 3209:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3210:                                                 '','','',$islocal);
 3211: 
 3212:     if (wantarray) {
 3213: 	return ($response->content, $response);
 3214:     } else {
 3215: 	return $response->content;
 3216:     }
 3217: }
 3218: 
 3219: sub externalssi {
 3220:     my ($url)=@_;
 3221:     my $request=new HTTP::Request('GET',$url);
 3222:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3223:     if (wantarray) {
 3224:         return ($response->content, $response);
 3225:     } else {
 3226:         return $response->content;
 3227:     }
 3228: }
 3229: 
 3230: 
 3231: # If the local copy of a replicated resource is outdated, trigger a  
 3232: # connection from the homeserver to flush the delayed queue. If no update 
 3233: # happens, remove local copies of outdated resource (and corresponding
 3234: # metadata file).
 3235: 
 3236: sub remove_stale_resfile {
 3237:     my ($url) = @_;
 3238:     my $removed;
 3239:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3240:         my $audom = $1;
 3241:         my $auname = $2;
 3242:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3243:             my $homeserver = &homeserver($auname,$audom);
 3244:             unless (($homeserver eq 'no_host') ||
 3245:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3246:                 my $fname = &filelocation('',$url);
 3247:                 if (-e $fname) {
 3248:                     my $protocol = $protocol{$homeserver};
 3249:                     $protocol = 'http' if ($protocol ne 'https');
 3250:                     my $hostname = &hostname($homeserver);
 3251:                     if ($hostname) {
 3252:                         my $uri = &declutter($url);
 3253:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3254:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3255:                         if ($response->is_success()) {
 3256:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3257:                             my $locmodtime = (stat($fname))[9];
 3258:                             if ($locmodtime < $remmodtime) {
 3259:                                 my $stale;
 3260:                                 my $answer = &reply('pong',$homeserver);
 3261:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3262:                                     sleep(0.2);
 3263:                                     $locmodtime = (stat($fname))[9];
 3264:                                     if ($locmodtime < $remmodtime) {
 3265:                                         my $posstransfer = $fname.'.in.transfer';
 3266:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3267:                                             $removed = 1;
 3268:                                         } else {
 3269:                                             $stale = 1;
 3270:                                         }
 3271:                                     } else {
 3272:                                         $removed = 1;
 3273:                                     }
 3274:                                 } else {
 3275:                                     $stale = 1;
 3276:                                 }
 3277:                                 if ($stale) {
 3278:                                     unlink($fname);
 3279:                                     if ($uri!~/\.meta$/) {
 3280:                                         unlink($fname.'.meta');
 3281:                                     }
 3282:                                     &reply("unsub:$fname",$homeserver);
 3283:                                     $removed = 1;
 3284:                                 }
 3285:                             }
 3286:                         }
 3287:                     }
 3288:                 }
 3289:             }
 3290:         }
 3291:     }
 3292:     return $removed;
 3293: }
 3294: 
 3295: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3296: 
 3297: sub allowuploaded {
 3298:     my ($srcurl,$url)=@_;
 3299:     $url=&clutter(&declutter($url));
 3300:     my $dir=$url;
 3301:     $dir=~s/\/[^\/]+$//;
 3302:     my %httpref=();
 3303:     my $httpurl=&hreflocation('',$url);
 3304:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3305:     &Apache::lonnet::appenv(\%httpref);
 3306: }
 3307: 
 3308: #
 3309: # Determine if the current user should be able to edit a particular resource,
 3310: # when viewing in course context.
 3311: # (a) When viewing resource used to determine if "Edit" item is included in 
 3312: #     Functions.
 3313: # (b) When displaying folder contents in course editor, used to determine if
 3314: #     "Edit" link will be displayed alongside resource.
 3315: #
 3316: #  input: six args -- filename (decluttered), course number, course domain,
 3317: #                   url, symb (if registered) and group (if this is a group
 3318: #                   item -- e.g., bulletin board, group page etc.).
 3319: #  output: array of five scalars -- 
 3320: #          $cfile -- url for file editing if editable on current server
 3321: #          $home -- homeserver of resource (i.e., for author if published,
 3322: #                                           or course if uploaded.).
 3323: #          $switchserver --  1 if server switch will be needed.
 3324: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3325: #          $forceview -- 1 if icon/link should be to go to view mode
 3326: #
 3327: 
 3328: sub can_edit_resource {
 3329:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3330:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3331: #
 3332: # For aboutme pages user can only edit his/her own.
 3333: #
 3334:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3335:         my ($sdom,$sname) = ($1,$2);
 3336:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3337:             $home = $env{'user.home'};
 3338:             $cfile = $resurl;
 3339:             if ($env{'form.forceedit'}) {
 3340:                 $forceview = 1;
 3341:             } else {
 3342:                 $forceedit = 1;
 3343:             }
 3344:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3345:         } else {
 3346:             return;
 3347:         }
 3348:     }
 3349: 
 3350:     if ($env{'request.course.id'}) {
 3351:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3352:         if ($group ne '') {
 3353: # if this is a group homepage or group bulletin board, check group privs
 3354:             my $allowed = 0;
 3355:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3356:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3357:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3358:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3359:                     $allowed = 1;
 3360:                 }
 3361:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3362:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3363:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3364:                     $allowed = 1;
 3365:                 }
 3366:             }
 3367:             if ($allowed) {
 3368:                 $home=&homeserver($cnum,$cdom);
 3369:                 if ($env{'form.forceedit'}) {
 3370:                     $forceview = 1;
 3371:                 } else {
 3372:                     $forceedit = 1;
 3373:                 }
 3374:                 $cfile = $resurl;
 3375:             } else {
 3376:                 return;
 3377:             }
 3378:         } else {
 3379:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3380:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3381:                     return;
 3382:                 }
 3383:             } elsif (!$crsedit) {
 3384: #
 3385: # No edit allowed where CC has switched to student role.
 3386: #
 3387:                 return;
 3388:             }
 3389:         }
 3390:     }
 3391: 
 3392:     if ($file ne '') {
 3393:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3394:             if (&is_course_upload($file,$cnum,$cdom)) {
 3395:                 $uploaded = 1;
 3396:                 $incourse = 1;
 3397:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3398:                     $cfile = &hreflocation('',$file);
 3399:                     if ($env{'form.forceedit'}) {
 3400:                         $forceview = 1;
 3401:                     } else {
 3402:                         $forceedit = 1;
 3403:                     }
 3404:                 }
 3405:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3406:                 $incourse = 1;
 3407:                 if ($env{'form.forceedit'}) {
 3408:                     $forceview = 1;
 3409:                 } else {
 3410:                     $forceedit = 1;
 3411:                 }
 3412:                 $cfile = $resurl;
 3413:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3414:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3415:                     $incourse = 1;
 3416:                     if ($env{'form.forceedit'}) {
 3417:                         $forceview = 1;
 3418:                     } else {
 3419:                         $forceedit = 1;
 3420:                     }
 3421:                     $cfile = $resurl;
 3422:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3423:                     $incourse = 1;
 3424:                     $cfile = $resurl.'/smpedit';
 3425:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3426:                     $incourse = 1;
 3427:                     if ($env{'form.forceedit'}) {
 3428:                         $forceview = 1;
 3429:                     } else {
 3430:                         $forceedit = 1;
 3431:                     }
 3432:                     $cfile = $resurl;
 3433:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3434:                     $incourse = 1;
 3435:                     if ($env{'form.forceedit'}) {
 3436:                         $forceview = 1;
 3437:                     } else {
 3438:                         $forceedit = 1;
 3439:                     }
 3440:                     $cfile = $resurl;
 3441:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3442:                     $incourse = 1;
 3443:                     if ($env{'form.forceedit'}) {
 3444:                         $forceview = 1;
 3445:                     } else {
 3446:                         $forceedit = 1;
 3447:                     }
 3448:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3449:                 }
 3450:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3451:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3452:                 if (&is_on_map($template)) { 
 3453:                     $incourse = 1;
 3454:                     $forceview = 1;
 3455:                     $cfile = $template;
 3456:                 }
 3457:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3458:                     $incourse = 1;
 3459:                     if ($env{'form.forceedit'}) {
 3460:                         $forceview = 1;
 3461:                     } else {
 3462:                         $forceedit = 1;
 3463:                     }
 3464:                     $cfile = $resurl;
 3465:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3466:                 $incourse = 1;
 3467:                 if ($env{'form.forceedit'}) {
 3468:                     $forceview = 1;
 3469:                 } else {
 3470:                     $forceedit = 1;
 3471:                 }
 3472:                 $cfile = $resurl;
 3473:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3474:                 $incourse = 1;
 3475:                 $forceview = 1;
 3476:                 if ($symb) {
 3477:                     my ($map,$id,$res)=&decode_symb($symb);
 3478:                     $env{'request.symb'} = $symb;
 3479:                     $cfile = &clutter($res);
 3480:                 } else {
 3481:                     $cfile = $env{'form.suppurl'};
 3482:                     my $escfile = &unescape($cfile);
 3483:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3484:                         $cfile = '/adm/wrapper'.$escfile;
 3485:                     } else {
 3486:                         $escfile =~ s{^http://}{};
 3487:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3488:                     }
 3489:                 }
 3490:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3491:                 if ($env{'form.forceedit'}) {
 3492:                     $forceview = 1;
 3493:                 } else {
 3494:                     $forceedit = 1;
 3495:                 }
 3496:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3497:             }
 3498:         }
 3499:         if ($uploaded || $incourse) {
 3500:             $home=&homeserver($cnum,$cdom);
 3501:         } elsif ($file !~ m{/$}) {
 3502:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3503:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3504:             # Check that the user has permission to edit this resource
 3505:             my $setpriv = 1;
 3506:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3507:             if (defined($cfudom)) {
 3508:                 $home=&homeserver($cfuname,$cfudom);
 3509:                 $cfile=$file;
 3510:             }
 3511:         }
 3512:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3513:             (($home ne '') && ($home ne 'no_host'))) {
 3514:             my @ids=&current_machine_ids();
 3515:             unless (grep(/^\Q$home\E$/,@ids)) {
 3516:                 $switchserver=1;
 3517:             }
 3518:         }
 3519:     }
 3520:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3521: }
 3522: 
 3523: sub is_course_upload {
 3524:     my ($file,$cnum,$cdom) = @_;
 3525:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3526:     $uploadpath =~ s{^\/}{};
 3527:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3528:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3529:         return 1;
 3530:     }
 3531:     return;
 3532: }
 3533: 
 3534: sub in_course {
 3535:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3536:     if ($hideprivileged) {
 3537:         my $skipuser;
 3538:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3539:         my @possdoms = ($cdom);  
 3540:         if ($coursehash{'checkforpriv'}) { 
 3541:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3542:         }
 3543:         if (&privileged($uname,$udom,\@possdoms)) {
 3544:             $skipuser = 1;
 3545:             if ($coursehash{'nothideprivileged'}) {
 3546:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3547:                     my $user;
 3548:                     if ($item =~ /:/) {
 3549:                         $user = $item;
 3550:                     } else {
 3551:                         $user = join(':',split(/[\@]/,$item));
 3552:                     }
 3553:                     if ($user eq $uname.':'.$udom) {
 3554:                         undef($skipuser);
 3555:                         last;
 3556:                     }
 3557:                 }
 3558:             }
 3559:             if ($skipuser) {
 3560:                 return 0;
 3561:             }
 3562:         }
 3563:     }
 3564:     $type ||= 'any';
 3565:     if (!defined($cdom) || !defined($cnum)) {
 3566:         my $cid  = $env{'request.course.id'};
 3567:         $cdom = $env{'course.'.$cid.'.domain'};
 3568:         $cnum = $env{'course.'.$cid.'.num'};
 3569:     }
 3570:     my $typesref;
 3571:     if (($type eq 'any') || ($type eq 'all')) {
 3572:         $typesref = ['active','previous','future'];
 3573:     } elsif ($type eq 'previous' || $type eq 'future') {
 3574:         $typesref = [$type];
 3575:     }
 3576:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3577:                               $typesref,undef,[$cdom]);
 3578:     my ($tmp) = keys(%roles);
 3579:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3580:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3581:     if (@course_roles > 0) {
 3582:         return 1;
 3583:     }
 3584:     return 0;
 3585: }
 3586: 
 3587: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3588: # input: action, courseID, current domain, intended
 3589: #        path to file, source of file, instruction to parse file for objects,
 3590: #        ref to hash for embedded objects,
 3591: #        ref to hash for codebase of java objects.
 3592: #        reference to scalar to accommodate mime type determined
 3593: #          from File::MMagic if $parser = parse.
 3594: #
 3595: # output: url to file (if action was uploaddoc), 
 3596: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3597: #
 3598: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3599: # course.
 3600: #
 3601: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3602: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3603: #          course's home server.
 3604: #
 3605: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3606: #          be copied from $source (current location) to 
 3607: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3608: #         and will then be copied to
 3609: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3610: #         course's home server.
 3611: #
 3612: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3613: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3614: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3615: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3616: #         in course's home server.
 3617: #
 3618: 
 3619: sub process_coursefile {
 3620:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3621:         $mimetype)=@_;
 3622:     my $fetchresult;
 3623:     my $home=&homeserver($docuname,$docudom);
 3624:     if ($action eq 'propagate') {
 3625:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3626: 			     $home);
 3627:     } else {
 3628:         my $fpath = '';
 3629:         my $fname = $file;
 3630:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3631:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3632:         my $filepath = &build_filepath($fpath);
 3633:         if ($action eq 'copy') {
 3634:             if ($source eq '') {
 3635:                 $fetchresult = 'no source file';
 3636:                 return $fetchresult;
 3637:             } else {
 3638:                 my $destination = $filepath.'/'.$fname;
 3639:                 rename($source,$destination);
 3640:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3641:                                  $home);
 3642:             }
 3643:         } elsif ($action eq 'uploaddoc') {
 3644:             open(my $fh,'>',$filepath.'/'.$fname);
 3645:             print $fh $env{'form.'.$source};
 3646:             close($fh);
 3647:             if ($parser eq 'parse') {
 3648:                 my $mm = new File::MMagic;
 3649:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3650:                 if ($type eq 'text/html') {
 3651:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3652:                     unless ($parse_result eq 'ok') {
 3653:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3654:                     }
 3655:                 }
 3656:                 if (ref($mimetype)) {
 3657:                     $$mimetype = $type;
 3658:                 } 
 3659:             }
 3660:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3661:                                  $home);
 3662:             if ($fetchresult eq 'ok') {
 3663:                 return '/uploaded/'.$fpath.'/'.$fname;
 3664:             } else {
 3665:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3666:                         ' to host '.$home.': '.$fetchresult);
 3667:                 return '/adm/notfound.html';
 3668:             }
 3669:         }
 3670:     }
 3671:     unless ( $fetchresult eq 'ok') {
 3672:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3673:              ' to host '.$home.': '.$fetchresult);
 3674:     }
 3675:     return $fetchresult;
 3676: }
 3677: 
 3678: sub build_filepath {
 3679:     my ($fpath) = @_;
 3680:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3681:     unless ($fpath eq '') {
 3682:         my @parts=split('/',$fpath);
 3683:         foreach my $part (@parts) {
 3684:             $filepath.= '/'.$part;
 3685:             if ((-e $filepath)!=1) {
 3686:                 mkdir($filepath,0777);
 3687:             }
 3688:         }
 3689:     }
 3690:     return $filepath;
 3691: }
 3692: 
 3693: sub store_edited_file {
 3694:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3695:     my $file = $primary_url;
 3696:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3697:     my $fpath = '';
 3698:     my $fname = $file;
 3699:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3700:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3701:     my $filepath = &build_filepath($fpath);
 3702:     open(my $fh,'>',$filepath.'/'.$fname);
 3703:     print $fh $content;
 3704:     close($fh);
 3705:     my $home=&homeserver($docuname,$docudom);
 3706:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3707: 			  $home);
 3708:     if ($$fetchresult eq 'ok') {
 3709:         return '/uploaded/'.$fpath.'/'.$fname;
 3710:     } else {
 3711:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3712: 		 ' to host '.$home.': '.$$fetchresult);
 3713:         return '/adm/notfound.html';
 3714:     }
 3715: }
 3716: 
 3717: sub clean_filename {
 3718:     my ($fname,$args)=@_;
 3719: # Replace Windows backslashes by forward slashes
 3720:     $fname=~s/\\/\//g;
 3721:     if (!$args->{'keep_path'}) {
 3722:         # Get rid of everything but the actual filename
 3723: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3724:     }
 3725: # Replace spaces by underscores
 3726:     $fname=~s/\s+/\_/g;
 3727: # Replace all other weird characters by nothing
 3728:     $fname=~s{[^/\w\.\-]}{}g;
 3729: # Replace all .\d. sequences with _\d. so they no longer look like version
 3730: # numbers
 3731:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3732:     return $fname;
 3733: }
 3734: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3735: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3736: # image with the same aspect ratio as the original, but with dimensions which do 
 3737: # not exceed $resizewidth and $resizeheight.
 3738:  
 3739: sub resizeImage {
 3740:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3741:     my $ima = Image::Magick->new;
 3742:     my $resized;
 3743:     if (-e $img_path) {
 3744:         $ima->Read($img_path);
 3745:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3746:             my $width = $ima->Get('width');
 3747:             my $height = $ima->Get('height');
 3748:             if ($width > $resizewidth) {
 3749: 	        my $factor = $width/$resizewidth;
 3750:                 my $newheight = $height/$factor;
 3751:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3752:                 $resized = 1;
 3753:             }
 3754:         }
 3755:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3756:             my $width = $ima->Get('width');
 3757:             my $height = $ima->Get('height');
 3758:             if ($height > $resizeheight) {
 3759:                 my $factor = $height/$resizeheight;
 3760:                 my $newwidth = $width/$factor;
 3761:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3762:                 $resized = 1;
 3763:             }
 3764:         }
 3765:         if ($resized) {
 3766:             $ima->Write($img_path);
 3767:         }
 3768:     }
 3769:     return;
 3770: }
 3771: 
 3772: # --------------- Take an uploaded file and put it into the userfiles directory
 3773: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3774: #                    the desired filename is in $env{"form.$formname.filename"}
 3775: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3776: #                                    canceloverwrite, or ''. 
 3777: #                   if 'coursedoc': upload to the current course
 3778: #                   if 'existingfile': write file to tmp/overwrites directory 
 3779: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3780: #                   $context is passed as argument to &finishuserfileupload
 3781: #        $subdir - directory in userfile to store the file into
 3782: #        $parser - instruction to parse file for objects ($parser = parse)    
 3783: #        $allfiles - reference to hash for embedded objects
 3784: #        $codebase - reference to hash for codebase of java objects
 3785: #        $desuname - username for permanent storage of uploaded file
 3786: #        $dsetudom - domain for permanaent storage of uploaded file
 3787: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3788: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3789: #        $resizewidth - width (pixels) to which to resize uploaded image
 3790: #        $resizeheight - height (pixels) to which to resize uploaded image
 3791: #        $mimetype - reference to scalar to accommodate mime type determined
 3792: #                    from File::MMagic.
 3793: # 
 3794: # output: url of file in userspace, or error: <message> 
 3795: #             or /adm/notfound.html if failure to upload occurse
 3796: 
 3797: sub userfileupload {
 3798:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3799:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3800:     if (!defined($subdir)) { $subdir='unknown'; }
 3801:     my $fname=$env{'form.'.$formname.'.filename'};
 3802:     $fname=&clean_filename($fname);
 3803:     # See if there is anything left
 3804:     unless ($fname) { return 'error: no uploaded file'; }
 3805:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3806:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3807:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3808:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3809:         my $now = time;
 3810:         my $filepath;
 3811:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3812:              $filepath = 'tmp/helprequests/'.$now;
 3813:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3814:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3815:                          '_'.$env{'user.domain'}.'/pending';
 3816:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3817:             my ($docuname,$docudom);
 3818:             if ($destudom =~ /^$match_domain$/) {
 3819:                 $docudom = $destudom;
 3820:             } else {
 3821:                 $docudom = $env{'user.domain'};
 3822:             }
 3823:             if ($destuname =~ /^$match_username$/) {
 3824:                 $docuname = $destuname;
 3825:             } else {
 3826:                 $docuname = $env{'user.name'};
 3827:             }
 3828:             if (exists($env{'form.group'})) {
 3829:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3830:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3831:             }
 3832:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3833:             if ($context eq 'canceloverwrite') {
 3834:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3835:                 if (-e  $tempfile) {
 3836:                     my @info = stat($tempfile);
 3837:                     if ($info[9] eq $env{'form.timestamp'}) {
 3838:                         unlink($tempfile);
 3839:                     }
 3840:                 }
 3841:                 return;
 3842:             }
 3843:         }
 3844:         # Create the directory if not present
 3845:         my @parts=split(/\//,$filepath);
 3846:         my $fullpath = $perlvar{'lonDaemons'};
 3847:         for (my $i=0;$i<@parts;$i++) {
 3848:             $fullpath .= '/'.$parts[$i];
 3849:             if ((-e $fullpath)!=1) {
 3850:                 mkdir($fullpath,0777);
 3851:             }
 3852:         }
 3853:         open(my $fh,'>',$fullpath.'/'.$fname);
 3854:         print $fh $env{'form.'.$formname};
 3855:         close($fh);
 3856:         if ($context eq 'existingfile') {
 3857:             my @info = stat($fullpath.'/'.$fname);
 3858:             return ($fullpath.'/'.$fname,$info[9]);
 3859:         } else {
 3860:             return $fullpath.'/'.$fname;
 3861:         }
 3862:     }
 3863:     if ($subdir eq 'scantron') {
 3864:         $fname = 'scantron_orig_'.$fname;
 3865:     } else {
 3866:         $fname="$subdir/$fname";
 3867:     }
 3868:     if ($context eq 'coursedoc') {
 3869: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3870: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3871:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3872:             return &finishuserfileupload($docuname,$docudom,
 3873: 					 $formname,$fname,$parser,$allfiles,
 3874: 					 $codebase,$thumbwidth,$thumbheight,
 3875:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3876:         } else {
 3877:             if ($env{'form.folder'}) {
 3878:                 $fname=$env{'form.folder'}.'/'.$fname;
 3879:             }
 3880:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3881: 				       $fname,$formname,$parser,
 3882: 				       $allfiles,$codebase,$mimetype);
 3883:         }
 3884:     } elsif (defined($destuname)) {
 3885:         my $docuname=$destuname;
 3886:         my $docudom=$destudom;
 3887: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3888: 				     $parser,$allfiles,$codebase,
 3889:                                      $thumbwidth,$thumbheight,
 3890:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3891:     } else {
 3892:         my $docuname=$env{'user.name'};
 3893:         my $docudom=$env{'user.domain'};
 3894:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3895:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3896:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3897:         }
 3898: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3899: 				     $parser,$allfiles,$codebase,
 3900:                                      $thumbwidth,$thumbheight,
 3901:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3902:     }
 3903: }
 3904: 
 3905: sub finishuserfileupload {
 3906:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3907:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3908:     my $path=$docudom.'/'.$docuname.'/';
 3909:     my $filepath=$perlvar{'lonDocRoot'};
 3910:   
 3911:     my ($fnamepath,$file,$fetchthumb);
 3912:     $file=$fname;
 3913:     if ($fname=~m|/|) {
 3914:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3915: 	$path.=$fnamepath.'/';
 3916:     }
 3917:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3918:     my $count;
 3919:     for ($count=4;$count<=$#parts;$count++) {
 3920:         $filepath.="/$parts[$count]";
 3921:         if ((-e $filepath)!=1) {
 3922: 	    mkdir($filepath,0777);
 3923:         }
 3924:     }
 3925: 
 3926: # Save the file
 3927:     {
 3928: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 3929: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3930: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3931: 	    return '/adm/notfound.html';
 3932: 	}
 3933:         if ($context eq 'overwrite') {
 3934:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3935:             my $target = $filepath.'/'.$file;
 3936:             if (-e $source) {
 3937:                 my @info = stat($source);
 3938:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3939:                     unless (&File::Copy::move($source,$target)) {
 3940:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3941:                         return "Moving from $source failed";
 3942:                     }
 3943:                 } else {
 3944:                     return "Temporary file: $source had unexpected date/time for last modification";
 3945:                 }
 3946:             } else {
 3947:                 return "Temporary file: $source missing";
 3948:             }
 3949:         } elsif (!print FH ($env{'form.'.$formname})) {
 3950: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3951: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3952: 	    return '/adm/notfound.html';
 3953: 	}
 3954: 	close(FH);
 3955:         if ($resizewidth && $resizeheight) {
 3956:             my $mm = new File::MMagic;
 3957:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3958:             if ($mime_type =~ m{^image/}) {
 3959: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3960:             }  
 3961: 	}
 3962:     }
 3963:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3964:         if (ref($mimetype)) {
 3965:             if ($$mimetype eq '') {
 3966:                 my $mm = new File::MMagic;
 3967:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3968:                 $$mimetype = $type;
 3969:             }
 3970:         }
 3971:     }
 3972:     if ($parser eq 'parse') {
 3973:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3974:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3975:                                                        $allfiles,$codebase);
 3976:             unless ($parse_result eq 'ok') {
 3977:                 &logthis('Failed to parse '.$filepath.$file.
 3978: 	   	         ' for embedded media: '.$parse_result); 
 3979:             }
 3980:         }
 3981:     }
 3982:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3983:         my $input = $filepath.'/'.$file;
 3984:         my $output = $filepath.'/'.'tn-'.$file;
 3985:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3986:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 3987:         system({$args[0]} @args);
 3988:         if (-e $filepath.'/'.'tn-'.$file) {
 3989:             $fetchthumb  = 1; 
 3990:         }
 3991:     }
 3992:  
 3993: # Notify homeserver to grep it
 3994: #
 3995:     my $docuhome=&homeserver($docuname,$docudom);	
 3996:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3997:     if ($fetchresult eq 'ok') {
 3998:         if ($fetchthumb) {
 3999:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4000:             if ($thumbresult ne 'ok') {
 4001:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4002:                          $docuhome.': '.$thumbresult);
 4003:             }
 4004:         }
 4005: #
 4006: # Return the URL to it
 4007:         return '/uploaded/'.$path.$file;
 4008:     } else {
 4009:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4010: 		 ': '.$fetchresult);
 4011:         return '/adm/notfound.html';
 4012:     }
 4013: }
 4014: 
 4015: sub extract_embedded_items {
 4016:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4017:     my @state = ();
 4018:     my (%lastids,%related,%shockwave,%flashvars);
 4019:     my %javafiles = (
 4020:                       codebase => '',
 4021:                       code => '',
 4022:                       archive => ''
 4023:                     );
 4024:     my %mediafiles = (
 4025:                       src => '',
 4026:                       movie => '',
 4027:                      );
 4028:     my $p;
 4029:     if ($content) {
 4030:         $p = HTML::LCParser->new($content);
 4031:     } else {
 4032:         $p = HTML::LCParser->new($fullpath);
 4033:     }
 4034:     while (my $t=$p->get_token()) {
 4035: 	if ($t->[0] eq 'S') {
 4036: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4037: 	    push(@state, $tagname);
 4038:             if (lc($tagname) eq 'allow') {
 4039:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4040:             }
 4041: 	    if (lc($tagname) eq 'img') {
 4042: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4043: 	    }
 4044: 	    if (lc($tagname) eq 'a') {
 4045:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4046:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4047:                 }
 4048: 	    }
 4049:             if (lc($tagname) eq 'script') {
 4050:                 my $src;
 4051:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4052:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4053:                 } else {
 4054:                     if ($attr->{'src'} ne '') {
 4055:                         $src = $attr->{'src'};
 4056:                         &add_filetype($allfiles,$src,'src');
 4057:                     }
 4058:                 }
 4059:                 my $text = $p->get_trimmed_text();
 4060:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4061:                     my @swfargs = split(/,/,$1);
 4062:                     foreach my $item (@swfargs) {
 4063:                         $item =~ s/["']//g;
 4064:                         $item =~ s/^\s+//;
 4065:                         $item =~ s/\s+$//;
 4066:                     }
 4067:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4068:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4069:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4070:                         } else {
 4071:                             $related{$swfargs[0]} = [$swfargs[2]];
 4072:                         }
 4073:                     }
 4074:                 }
 4075:             }
 4076:             if (lc($tagname) eq 'link') {
 4077:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4078:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4079:                 }
 4080:             }
 4081: 	    if (lc($tagname) eq 'object' ||
 4082: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4083: 		foreach my $item (keys(%javafiles)) {
 4084: 		    $javafiles{$item} = '';
 4085: 		}
 4086:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4087:                     $lastids{lc($tagname)} = $attr->{'id'};
 4088:                 }
 4089: 	    }
 4090: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4091: 		my $name = lc($attr->{'name'});
 4092: 		foreach my $item (keys(%javafiles)) {
 4093: 		    if ($name eq $item) {
 4094: 			$javafiles{$item} = $attr->{'value'};
 4095: 			last;
 4096: 		    }
 4097: 		}
 4098:                 my $pathfrom;
 4099: 		foreach my $item (keys(%mediafiles)) {
 4100: 		    if ($name eq $item) {
 4101:                         $pathfrom = $attr->{'value'};
 4102:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4103: 			&add_filetype($allfiles,$pathfrom,$name);
 4104: 			last;
 4105: 		    }
 4106: 		}
 4107:                 if ($name eq 'flashvars') {
 4108:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4109:                 }
 4110:                 if ($pathfrom ne '') {
 4111:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4112:                                          $pathfrom);
 4113:                 }
 4114: 	    }
 4115: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4116: 		foreach my $item (keys(%javafiles)) {
 4117: 		    if ($attr->{$item}) {
 4118: 			$javafiles{$item} = $attr->{$item};
 4119: 			last;
 4120: 		    }
 4121: 		}
 4122: 		foreach my $item (keys(%mediafiles)) {
 4123: 		    if ($attr->{$item}) {
 4124: 			&add_filetype($allfiles,$attr->{$item},$item);
 4125: 			last;
 4126: 		    }
 4127: 		}
 4128:                 if (lc($tagname) eq 'embed') {
 4129:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4130:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4131:                                              $attr->{'src'});
 4132:                     }
 4133:                 }
 4134: 	    }
 4135:             if (lc($tagname) eq 'iframe') {
 4136:                 my $src = $attr->{'src'} ;
 4137:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4138:                     &add_filetype($allfiles,$src,'src');
 4139:                 } elsif ($src =~ m{^/}) {
 4140:                     if ($env{'request.course.id'}) {
 4141:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4142:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4143:                         my $url = &hreflocation('',$fullpath);
 4144:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4145:                             my $relpath = $1;
 4146:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4147:                                 &add_filetype($allfiles,$1,'src');
 4148:                             }
 4149:                         }
 4150:                     }
 4151:                 }
 4152:             }
 4153:             if ($t->[4] =~ m{/>$}) {
 4154:                 pop(@state);
 4155:             }
 4156: 	} elsif ($t->[0] eq 'E') {
 4157: 	    my ($tagname) = ($t->[1]);
 4158: 	    if ($javafiles{'codebase'} ne '') {
 4159: 		$javafiles{'codebase'} .= '/';
 4160: 	    }  
 4161: 	    if (lc($tagname) eq 'applet' ||
 4162: 		lc($tagname) eq 'object' ||
 4163: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4164: 		) {
 4165: 		foreach my $item (keys(%javafiles)) {
 4166: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4167: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4168: 			&add_filetype($allfiles,$file,$item);
 4169: 		    }
 4170: 		}
 4171: 	    } 
 4172: 	    pop @state;
 4173: 	}
 4174:     }
 4175:     foreach my $id (sort(keys(%flashvars))) {
 4176:         if ($shockwave{$id} ne '') {
 4177:             my @pairs = split(/\&/,$flashvars{$id});
 4178:             foreach my $pair (@pairs) {
 4179:                 my ($key,$value) = split(/\=/,$pair);
 4180:                 if ($key eq 'thumb') {
 4181:                     &add_filetype($allfiles,$value,$key);
 4182:                 } elsif ($key eq 'content') {
 4183:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4184:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4185:                     if ($ext ne '') {
 4186:                         &add_filetype($allfiles,$path.$value,$ext);
 4187:                     }
 4188:                 }
 4189:             }
 4190:         }
 4191:     }
 4192:     return 'ok';
 4193: }
 4194: 
 4195: sub add_filetype {
 4196:     my ($allfiles,$file,$type)=@_;
 4197:     if (exists($allfiles->{$file})) {
 4198: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4199: 	    push(@{$allfiles->{$file}}, &escape($type));
 4200: 	}
 4201:     } else {
 4202: 	@{$allfiles->{$file}} = (&escape($type));
 4203:     }
 4204: }
 4205: 
 4206: sub embedded_dependency {
 4207:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4208:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4209:         if (($identifier ne '') &&
 4210:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4211:             ($pathfrom ne '')) {
 4212:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4213:             foreach my $dep (@{$related->{$identifier}}) {
 4214:                 &add_filetype($allfiles,$path.$dep,'object');
 4215:             }
 4216:         }
 4217:     }
 4218:     return;
 4219: }
 4220: 
 4221: sub removeuploadedurl {
 4222:     my ($url)=@_;	
 4223:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4224:     return &removeuserfile($uname,$udom,$fname);
 4225: }
 4226: 
 4227: sub removeuserfile {
 4228:     my ($docuname,$docudom,$fname)=@_;
 4229:     my $home=&homeserver($docuname,$docudom);    
 4230:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4231:     if ($result eq 'ok') {	
 4232:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4233:             my $metafile = $fname.'.meta';
 4234:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4235: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4236:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4237:             my $sqlresult = 
 4238:                 &update_portfolio_table($docuname,$docudom,$file,
 4239:                                         'portfolio_metadata',$group,
 4240:                                         'delete');
 4241:         }
 4242:     }
 4243:     return $result;
 4244: }
 4245: 
 4246: sub mkdiruserfile {
 4247:     my ($docuname,$docudom,$dir)=@_;
 4248:     my $home=&homeserver($docuname,$docudom);
 4249:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4250: }
 4251: 
 4252: sub renameuserfile {
 4253:     my ($docuname,$docudom,$old,$new)=@_;
 4254:     my $home=&homeserver($docuname,$docudom);
 4255:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4256:                         &escape("$old").':'.&escape("$new"),$home);
 4257:     if ($result eq 'ok') {
 4258:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4259:             my $oldmeta = $old.'.meta';
 4260:             my $newmeta = $new.'.meta';
 4261:             my $metaresult = 
 4262:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4263: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4264:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4265:             my $sqlresult = 
 4266:                 &update_portfolio_table($docuname,$docudom,$file,
 4267:                                         'portfolio_metadata',$group,
 4268:                                         'delete');
 4269:         }
 4270:     }
 4271:     return $result;
 4272: }
 4273: 
 4274: # ------------------------------------------------------------------------- Log
 4275: 
 4276: sub log {
 4277:     my ($dom,$nam,$hom,$what)=@_;
 4278:     return critical("log:$dom:$nam:$what",$hom);
 4279: }
 4280: 
 4281: # ------------------------------------------------------------------ Course Log
 4282: #
 4283: # This routine flushes several buffers of non-mission-critical nature
 4284: #
 4285: 
 4286: sub flushcourselogs {
 4287:     &logthis('Flushing log buffers');
 4288: #
 4289: # course logs
 4290: # This is a log of all transactions in a course, which can be used
 4291: # for data mining purposes
 4292: #
 4293: # It also collects the courseid database, which lists last transaction
 4294: # times and course titles for all courseids
 4295: #
 4296:     my %courseidbuffer=();
 4297:     foreach my $crsid (keys(%courselogs)) {
 4298:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4299: 		          &escape($courselogs{$crsid}),
 4300: 		          $coursehombuf{$crsid}) eq 'ok') {
 4301: 	    delete $courselogs{$crsid};
 4302:         } else {
 4303:             &logthis('Failed to flush log buffer for '.$crsid);
 4304:             if (length($courselogs{$crsid})>40000) {
 4305:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4306:                         " exceeded maximum size, deleting.</font>");
 4307:                delete $courselogs{$crsid};
 4308:             }
 4309:         }
 4310:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4311:             'description' => $coursedescrbuf{$crsid},
 4312:             'inst_code'    => $courseinstcodebuf{$crsid},
 4313:             'type'        => $coursetypebuf{$crsid},
 4314:             'owner'       => $courseownerbuf{$crsid},
 4315:         };
 4316:     }
 4317: #
 4318: # Write course id database (reverse lookup) to homeserver of courses 
 4319: # Is used in pickcourse
 4320: #
 4321:     foreach my $crs_home (keys(%courseidbuffer)) {
 4322:         my $response = &courseidput(&host_domain($crs_home),
 4323:                                     $courseidbuffer{$crs_home},
 4324:                                     $crs_home,'timeonly');
 4325:     }
 4326: #
 4327: # File accesses
 4328: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4329: #
 4330:     foreach my $entry (keys(%accesshash)) {
 4331:         if ($entry =~ /___count$/) {
 4332:             my ($dom,$name);
 4333:             ($dom,$name,undef)=
 4334: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4335:             if (! defined($dom) || $dom eq '' || 
 4336:                 ! defined($name) || $name eq '') {
 4337:                 my $cid = $env{'request.course.id'};
 4338:                 $dom  = $env{'request.'.$cid.'.domain'};
 4339:                 $name = $env{'request.'.$cid.'.num'};
 4340:             }
 4341:             my $value = $accesshash{$entry};
 4342:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4343:             my %temphash=($url => $value);
 4344:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4345:             if ($result eq 'ok') {
 4346:                 delete $accesshash{$entry};
 4347:             }
 4348:         } else {
 4349:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4350:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4351:             my %temphash=($entry => $accesshash{$entry});
 4352:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4353:                 delete $accesshash{$entry};
 4354:             }
 4355:         }
 4356:     }
 4357: #
 4358: # Roles
 4359: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4360: #
 4361:     foreach my $entry (keys(%userrolehash)) {
 4362:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4363: 	    split(/\:/,$entry);
 4364:         if (&Apache::lonnet::put('nohist_userroles',
 4365:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4366:                 $rudom,$runame) eq 'ok') {
 4367: 	    delete $userrolehash{$entry};
 4368:         }
 4369:     }
 4370: #
 4371: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4372: #
 4373:     my %domrolebuffer = ();
 4374:     foreach my $entry (keys(%domainrolehash)) {
 4375:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4376:         if ($domrolebuffer{$rudom}) {
 4377:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4378:                       '='.&escape($domainrolehash{$entry});
 4379:         } else {
 4380:             $domrolebuffer{$rudom}.=&escape($entry).
 4381:                       '='.&escape($domainrolehash{$entry});
 4382:         }
 4383:         delete $domainrolehash{$entry};
 4384:     }
 4385:     foreach my $dom (keys(%domrolebuffer)) {
 4386: 	my %servers;
 4387: 	if (defined(&domain($dom,'primary'))) {
 4388: 	    my $primary=&domain($dom,'primary');
 4389: 	    my $hostname=&hostname($primary);
 4390: 	    $servers{$primary} = $hostname;
 4391: 	} else { 
 4392: 	    %servers = &get_servers($dom,'library');
 4393: 	}
 4394: 	foreach my $tryserver (keys(%servers)) {
 4395: 	    if (&reply('domroleput:'.$dom.':'.
 4396: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4397: 		last;
 4398: 	    } else {  
 4399: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4400: 	    }
 4401:         }
 4402:     }
 4403:     $dumpcount++;
 4404: }
 4405: 
 4406: sub courselog {
 4407:     my $what=shift;
 4408:     $what=time.':'.$what;
 4409:     unless ($env{'request.course.id'}) { return ''; }
 4410:     $coursedombuf{$env{'request.course.id'}}=
 4411:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4412:     $coursenumbuf{$env{'request.course.id'}}=
 4413:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4414:     $coursehombuf{$env{'request.course.id'}}=
 4415:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4416:     $coursedescrbuf{$env{'request.course.id'}}=
 4417:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4418:     $courseinstcodebuf{$env{'request.course.id'}}=
 4419:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4420:     $courseownerbuf{$env{'request.course.id'}}=
 4421:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4422:     $coursetypebuf{$env{'request.course.id'}}=
 4423:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4424:     if (defined $courselogs{$env{'request.course.id'}}) {
 4425: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4426:     } else {
 4427: 	$courselogs{$env{'request.course.id'}}.=$what;
 4428:     }
 4429:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4430: 	&flushcourselogs();
 4431:     }
 4432: }
 4433: 
 4434: sub courseacclog {
 4435:     my $fnsymb=shift;
 4436:     unless ($env{'request.course.id'}) { return ''; }
 4437:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4438:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4439:         $what.=':POST';
 4440:         # FIXME: Probably ought to escape things....
 4441: 	foreach my $key (keys(%env)) {
 4442:             if ($key=~/^form\.(.*)/) {
 4443:                 my $formitem = $1;
 4444:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4445:                     $what.=':'.$formitem.'='.$env{$key};
 4446:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4447:                     $what.=':'.$formitem.'='.$env{$key};
 4448:                 }
 4449:             }
 4450:         }
 4451:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4452:         # FIXME: We should not be depending on a form parameter that someone
 4453:         # editing lonsearchcat.pm might change in the future.
 4454:         if ($env{'form.phase'} eq 'course_search') {
 4455:             $what.= ':POST';
 4456:             # FIXME: Probably ought to escape things....
 4457:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4458:                                  'crsdiscuss') {
 4459:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4460:             }
 4461:         }
 4462:     }
 4463:     &courselog($what);
 4464: }
 4465: 
 4466: sub countacc {
 4467:     my $url=&declutter(shift);
 4468:     return if (! defined($url) || $url eq '');
 4469:     unless ($env{'request.course.id'}) { return ''; }
 4470: #
 4471: # Mark that this url was used in this course
 4472: #
 4473:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4474: #
 4475: # Increase the access count for this resource in this child process
 4476: #
 4477:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4478:     $accesshash{$key}++;
 4479: }
 4480: 
 4481: sub linklog {
 4482:     my ($from,$to)=@_;
 4483:     $from=&declutter($from);
 4484:     $to=&declutter($to);
 4485:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4486:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4487: }
 4488: 
 4489: sub statslog {
 4490:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4491:     if ($users<2) { return; }
 4492:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4493:             'course'       => $env{'request.course.id'},
 4494:             'sections'     => '"all"',
 4495:             'num_students' => $users,
 4496:             'part'         => $part,
 4497:             'symb'         => $symb,
 4498:             'mean_tries'   => $av_attempts,
 4499:             'deg_of_diff'  => $degdiff});
 4500:     foreach my $key (keys(%dynstore)) {
 4501:         $accesshash{$key}=$dynstore{$key};
 4502:     }
 4503: }
 4504:   
 4505: sub userrolelog {
 4506:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4507:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4508:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4509:        $userrolehash
 4510:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4511:                     =$tend.':'.$tstart;
 4512:     }
 4513:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4514:        $userrolehash
 4515:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4516:                     =$tend.':'.$tstart;
 4517:     }
 4518:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4519:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4520:        $domainrolehash
 4521:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4522:                     = $tend.':'.$tstart;
 4523:     }
 4524: }
 4525: 
 4526: sub courserolelog {
 4527:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4528:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4529:         my $cdom = $1;
 4530:         my $cnum = $2;
 4531:         my $sec = $3;
 4532:         my $namespace = 'rolelog';
 4533:         my %storehash = (
 4534:                            role    => $trole,
 4535:                            start   => $tstart,
 4536:                            end     => $tend,
 4537:                            selfenroll => $selfenroll,
 4538:                            context    => $context,
 4539:                         );
 4540:         if ($trole eq 'gr') {
 4541:             $namespace = 'groupslog';
 4542:             $storehash{'group'} = $sec;
 4543:         } else {
 4544:             $storehash{'section'} = $sec;
 4545:         }
 4546:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4547:                    $domain,$cnum,$cdom);
 4548:         if (($trole ne 'st') || ($sec ne '')) {
 4549:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4550:         }
 4551:     }
 4552:     return;
 4553: }
 4554: 
 4555: sub domainrolelog {
 4556:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4557:     if ($area =~ m{^/($match_domain)/$}) {
 4558:         my $cdom = $1;
 4559:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4560:         my $namespace = 'rolelog';
 4561:         my %storehash = (
 4562:                            role    => $trole,
 4563:                            start   => $tstart,
 4564:                            end     => $tend,
 4565:                            context => $context,
 4566:                         );
 4567:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4568:                    $domain,$domconfiguser,$cdom);
 4569:     }
 4570:     return;
 4571: 
 4572: }
 4573: 
 4574: sub coauthorrolelog {
 4575:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4576:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4577:         my $audom = $1;
 4578:         my $auname = $2;
 4579:         my $namespace = 'rolelog';
 4580:         my %storehash = (
 4581:                            role    => $trole,
 4582:                            start   => $tstart,
 4583:                            end     => $tend,
 4584:                            context => $context,
 4585:                         );
 4586:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4587:                    $domain,$auname,$audom);
 4588:     }
 4589:     return;
 4590: }
 4591: 
 4592: sub get_course_adv_roles {
 4593:     my ($cid,$codes) = @_;
 4594:     $cid=$env{'request.course.id'} unless (defined($cid));
 4595:     my %coursehash=&coursedescription($cid);
 4596:     my $crstype = &Apache::loncommon::course_type($cid);
 4597:     my %nothide=();
 4598:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4599:         if ($user !~ /:/) {
 4600: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4601:         } else {
 4602:             $nothide{$user}=1;
 4603:         }
 4604:     }
 4605:     my @possdoms = ($coursehash{'domain'});
 4606:     if ($coursehash{'checkforpriv'}) {
 4607:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4608:     }
 4609:     my %returnhash=();
 4610:     my %dumphash=
 4611:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4612:     my $now=time;
 4613:     my %privileged;
 4614:     foreach my $entry (keys(%dumphash)) {
 4615: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4616:         if (($tstart) && ($tstart<0)) { next; }
 4617:         if (($tend) && ($tend<$now)) { next; }
 4618:         if (($tstart) && ($now<$tstart)) { next; }
 4619:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4620: 	if ($username eq '' || $domain eq '') { next; }
 4621:         if ((&privileged($username,$domain,\@possdoms)) &&
 4622:             (!$nothide{$username.':'.$domain})) { next; }
 4623: 	if ($role eq 'cr') { next; }
 4624:         if ($codes) {
 4625:             if ($section) { $role .= ':'.$section; }
 4626:             if ($returnhash{$role}) {
 4627:                 $returnhash{$role}.=','.$username.':'.$domain;
 4628:             } else {
 4629:                 $returnhash{$role}=$username.':'.$domain;
 4630:             }
 4631:         } else {
 4632:             my $key=&plaintext($role,$crstype);
 4633:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4634:             if ($returnhash{$key}) {
 4635: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4636:             } else {
 4637:                 $returnhash{$key}=$username.':'.$domain;
 4638:             }
 4639:         }
 4640:     }
 4641:     return %returnhash;
 4642: }
 4643: 
 4644: sub get_my_roles {
 4645:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4646:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4647:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4648:     my (%dumphash,%nothide);
 4649:     if ($context eq 'userroles') {
 4650:         %dumphash = &dump('roles',$udom,$uname);
 4651:     } else {
 4652:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4653:         if ($hidepriv) {
 4654:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4655:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4656:                 if ($user !~ /:/) {
 4657:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4658:                 } else {
 4659:                     $nothide{$user} = 1;
 4660:                 }
 4661:             }
 4662:         }
 4663:     }
 4664:     my %returnhash=();
 4665:     my $now=time;
 4666:     my %privileged;
 4667:     foreach my $entry (keys(%dumphash)) {
 4668:         my ($role,$tend,$tstart);
 4669:         if ($context eq 'userroles') {
 4670:             next if ($entry =~ /^rolesdef/);
 4671: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4672:         } else {
 4673:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4674:         }
 4675:         if (($tstart) && ($tstart<0)) { next; }
 4676:         my $status = 'active';
 4677:         if (($tend) && ($tend<=$now)) {
 4678:             $status = 'previous';
 4679:         } 
 4680:         if (($tstart) && ($now<$tstart)) {
 4681:             $status = 'future';
 4682:         }
 4683:         if (ref($types) eq 'ARRAY') {
 4684:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4685:                 next;
 4686:             } 
 4687:         } else {
 4688:             if ($status ne 'active') {
 4689:                 next;
 4690:             }
 4691:         }
 4692:         my ($rolecode,$username,$domain,$section,$area);
 4693:         if ($context eq 'userroles') {
 4694:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4695:             (undef,$domain,$username,$section) = split(/\//,$area);
 4696:         } else {
 4697:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4698:         }
 4699:         if (ref($roledoms) eq 'ARRAY') {
 4700:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4701:                 next;
 4702:             }
 4703:         }
 4704:         if (ref($roles) eq 'ARRAY') {
 4705:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4706:                 if ($role =~ /^cr\//) {
 4707:                     if (!grep(/^cr$/,@{$roles})) {
 4708:                         next;
 4709:                     }
 4710:                 } elsif ($role =~ /^gr\//) {
 4711:                     if (!grep(/^gr$/,@{$roles})) {
 4712:                         next;
 4713:                     }
 4714:                 } else {
 4715:                     next;
 4716:                 }
 4717:             }
 4718:         }
 4719:         if ($hidepriv) {
 4720:             my @privroles = ('dc','su');
 4721:             if ($context eq 'userroles') {
 4722:                 next if (grep(/^\Q$role\E$/,@privroles));
 4723:             } else {
 4724:                 my $possdoms = [$domain];
 4725:                 if (ref($roledoms) eq 'ARRAY') {
 4726:                    push(@{$possdoms},@{$roledoms}); 
 4727:                 }
 4728:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4729:                     if (!$nothide{$username.':'.$domain}) {
 4730:                         next;
 4731:                     }
 4732:                 }
 4733:             }
 4734:         }
 4735:         if ($withsec) {
 4736:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4737:                 $tstart.':'.$tend;
 4738:         } else {
 4739:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4740:         }
 4741:     }
 4742:     return %returnhash;
 4743: }
 4744: 
 4745: sub get_all_adhocroles {
 4746:     my ($dom) = @_;
 4747:     my @roles_by_num = ();
 4748:     my %domdefaults = &get_domain_defaults($dom);
 4749:     my (%description,%access_in_dom,%access_info);
 4750:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4751:         my $count = 0;
 4752:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4753:         my %ordered;
 4754:         foreach my $role (sort(keys(%domcurrent))) {
 4755:             my ($order,$desc,$access_in_dom);
 4756:             if (ref($domcurrent{$role}) eq 'HASH') {
 4757:                 $order = $domcurrent{$role}{'order'};
 4758:                 $desc = $domcurrent{$role}{'desc'};
 4759:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4760:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4761:             }
 4762:             if ($order eq '') {
 4763:                 $order = $count;
 4764:             }
 4765:             $ordered{$order} = $role;
 4766:             if ($desc ne '') {
 4767:                 $description{$role} = $desc;
 4768:             } else {
 4769:                 $description{$role}= $role;
 4770:             }
 4771:             $count++;
 4772:         }
 4773:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4774:             push(@roles_by_num,$ordered{$item});
 4775:         }
 4776:     }
 4777:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4778: }
 4779: 
 4780: sub get_my_adhocroles {
 4781:     my ($cid,$checkreg) = @_;
 4782:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4783:     if ($env{'request.course.id'} eq $cid) {
 4784:         $cdom = $env{'course.'.$cid.'.domain'};
 4785:         $cnum = $env{'course.'.$cid.'.num'};
 4786:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4787:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4788:         $cdom = $1;
 4789:         $cnum = $2;
 4790:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4791:                                      $cdom,$cnum);
 4792:     }
 4793:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4794:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4795:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4796:         if ($rosterhash{$user} ne '') {
 4797:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4798:             return ([],{}) if ($type eq 'auto');
 4799:         }
 4800:     }
 4801:     if (($cdom ne '') && ($cnum ne ''))  {
 4802:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4803:             my $then=$env{'user.login.time'};
 4804:             my $update=$env{'user.update.time'};
 4805:             if (!$update) {
 4806:                 $update = $then;
 4807:             }
 4808:             my @liveroles;
 4809:             foreach my $role ('dh','da') {
 4810:                 if ($env{"user.role.$role./$cdom/"}) {
 4811:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4812:                     my $limit = $update;
 4813:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4814:                         $limit = $then;
 4815:                     }
 4816:                     my $activerole = 1;
 4817:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4818:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4819:                     if ($activerole) {
 4820:                         push(@liveroles,$role);
 4821:                     }
 4822:                 }
 4823:             }
 4824:             if (@liveroles) {
 4825:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4826:                     my ($accessref,$accessinfo,%access_in_dom);
 4827:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4828:                     if (ref($roles_by_num) eq 'ARRAY') {
 4829:                         if (@{$roles_by_num}) {
 4830:                             my %settings;
 4831:                             if ($env{'request.course.id'} eq $cid) {
 4832:                                 foreach my $envkey (keys(%env)) {
 4833:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4834:                                         $settings{$1} = $env{$envkey};
 4835:                                     }
 4836:                                 }
 4837:                             } else {
 4838:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4839:                             }
 4840:                             my %setincrs;
 4841:                             if ($settings{'internal.adhocaccess'}) {
 4842:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4843:                             }
 4844:                             my @statuses;
 4845:                             if ($env{'environment.inststatus'}) {
 4846:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4847:                             }
 4848:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4849:                             if (ref($accessref) eq 'HASH') {
 4850:                                 %access_in_dom = %{$accessref};
 4851:                             }
 4852:                             foreach my $role (@{$roles_by_num}) {
 4853:                                 my ($curraccess,@okstatus,@personnel);
 4854:                                 if ($setincrs{$role}) {
 4855:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4856:                                     if ($curraccess eq 'status') {
 4857:                                         @okstatus = split(/\&/,$rest);
 4858:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4859:                                         @personnel = split(/\&/,$rest);
 4860:                                     }
 4861:                                 } else {
 4862:                                     $curraccess = $access_in_dom{$role};
 4863:                                     if (ref($accessinfo) eq 'HASH') {
 4864:                                         if ($curraccess eq 'status') {
 4865:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4866:                                                 @okstatus = @{$accessinfo->{$role}};
 4867:                                             }
 4868:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4869:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4870:                                                 @personnel = @{$accessinfo->{$role}};
 4871:                                             }
 4872:                                         }
 4873:                                     }
 4874:                                 }
 4875:                                 if ($curraccess eq 'none') {
 4876:                                     next;
 4877:                                 } elsif ($curraccess eq 'all') {
 4878:                                     push(@possroles,$role);
 4879:                                 } elsif ($curraccess eq 'dh') {
 4880:                                     if (grep(/^dh$/,@liveroles)) {
 4881:                                         push(@possroles,$role);
 4882:                                     } else {
 4883:                                         next;
 4884:                                     }
 4885:                                 } elsif ($curraccess eq 'da') {
 4886:                                     if (grep(/^da$/,@liveroles)) {
 4887:                                         push(@possroles,$role);
 4888:                                     } else {
 4889:                                         next;
 4890:                                     }
 4891:                                 } elsif ($curraccess eq 'status') {
 4892:                                     if (@okstatus) {
 4893:                                         if (!@statuses) {
 4894:                                             if (grep(/^default$/,@okstatus)) {
 4895:                                                 push(@possroles,$role);
 4896:                                             }
 4897:                                         } else {
 4898:                                             foreach my $status (@okstatus) {
 4899:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 4900:                                                     push(@possroles,$role);
 4901:                                                     last;
 4902:                                                 }
 4903:                                             }
 4904:                                         }
 4905:                                     }
 4906:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4907:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 4908:                                         if ($curraccess eq 'exc') {
 4909:                                             push(@possroles,$role);
 4910:                                         }
 4911:                                     } elsif ($curraccess eq 'inc') {
 4912:                                         push(@possroles,$role);
 4913:                                     }
 4914:                                 }
 4915:                             }
 4916:                         }
 4917:                     }
 4918:                 }
 4919:             }
 4920:         }
 4921:     }
 4922:     unless (ref($description) eq 'HASH') {
 4923:         if (ref($roles_by_num) eq 'ARRAY') {
 4924:             my %desc;
 4925:             map { $desc{$_} = $_; } (@{$roles_by_num});
 4926:             $description = \%desc;
 4927:         } else {
 4928:             $description = {};
 4929:         }
 4930:     }
 4931:     return (\@possroles,$description);
 4932: }
 4933: 
 4934: # ----------------------------------------------------- Frontpage Announcements
 4935: #
 4936: #
 4937: 
 4938: sub postannounce {
 4939:     my ($server,$text)=@_;
 4940:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4941:     unless ($text=~/\w/) { $text=''; }
 4942:     return &reply('setannounce:'.&escape($text),$server);
 4943: }
 4944: 
 4945: sub getannounce {
 4946: 
 4947:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4948: 	my $announcement='';
 4949: 	while (my $line = <$fh>) { $announcement .= $line; }
 4950: 	close($fh);
 4951: 	if ($announcement=~/\w/) { 
 4952: 	    return 
 4953:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4954:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4955: 	} else {
 4956: 	    return '';
 4957: 	}
 4958:     } else {
 4959: 	return '';
 4960:     }
 4961: }
 4962: 
 4963: # ---------------------------------------------------------- Course ID routines
 4964: # Deal with domain's nohist_courseid.db files
 4965: #
 4966: 
 4967: sub courseidput {
 4968:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4969:     return unless (ref($storehash) eq 'HASH');
 4970:     my $outcome;
 4971:     if ($caller eq 'timeonly') {
 4972:         my $cids = '';
 4973:         foreach my $item (keys(%$storehash)) {
 4974:             $cids.=&escape($item).'&';
 4975:         }
 4976:         $cids=~s/\&$//;
 4977:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4978:                           $coursehome);       
 4979:     } else {
 4980:         my $items = '';
 4981:         foreach my $item (keys(%$storehash)) {
 4982:             $items.= &escape($item).'='.
 4983:                      &freeze_escape($$storehash{$item}).'&';
 4984:         }
 4985:         $items=~s/\&$//;
 4986:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4987:                           $coursehome);
 4988:     }
 4989:     if ($outcome eq 'unknown_cmd') {
 4990:         my $what;
 4991:         foreach my $cid (keys(%$storehash)) {
 4992:             $what .= &escape($cid).'=';
 4993:             foreach my $item ('description','inst_code','owner','type') {
 4994:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4995:             }
 4996:             $what =~ s/\:$/&/;
 4997:         }
 4998:         $what =~ s/\&$//;  
 4999:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5000:     } else {
 5001:         return $outcome;
 5002:     }
 5003: }
 5004: 
 5005: sub courseiddump {
 5006:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5007:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5008:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5009:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5010:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5011:     my $as_hash = 1;
 5012:     my %returnhash;
 5013:     if (!$domfilter) { $domfilter=''; }
 5014:     my %libserv = &all_library();
 5015:     foreach my $tryserver (keys(%libserv)) {
 5016:         if ( (  $hostidflag == 1 
 5017: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5018: 	     || (!defined($hostidflag)) ) {
 5019: 
 5020: 	    if (($domfilter eq '') ||
 5021: 		(&host_domain($tryserver) eq $domfilter)) {
 5022:                 my $rep;
 5023:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5024:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5025:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5026:                                 &escape($descfilter), &escape($instcodefilter), 
 5027:                                 &escape($ownerfilter), &escape($coursefilter),
 5028:                                 &escape($typefilter), &escape($regexp_ok), 
 5029:                                 $as_hash, &escape($selfenrollonly), 
 5030:                                 &escape($catfilter), $showhidden, $caller, 
 5031:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5032:                                 &escape($createdbefore), &escape($createdafter), 
 5033:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5034:                                 $reqcrsdom,&escape($reqinstcode))));
 5035:                 } else {
 5036:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5037:                              $sincefilter.':'.&escape($descfilter).':'.
 5038:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5039:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5040:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5041:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5042:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5043:                              &escape($cc_clone).':'.$cloneonly.':'.
 5044:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5045:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5046:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5047:                 }
 5048:                      
 5049:                 my @pairs=split(/\&/,$rep);
 5050:                 foreach my $item (@pairs) {
 5051:                     my ($key,$value)=split(/\=/,$item,2);
 5052:                     $key = &unescape($key);
 5053:                     next if ($key =~ /^error: 2 /);
 5054:                     my $result = &thaw_unescape($value);
 5055:                     if (ref($result) eq 'HASH') {
 5056:                         $returnhash{$key}=$result;
 5057:                     } else {
 5058:                         my @responses = split(/:/,$value);
 5059:                         my @items = ('description','inst_code','owner','type');
 5060:                         for (my $i=0; $i<@responses; $i++) {
 5061:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5062:                         }
 5063:                     }
 5064:                 }
 5065:             }
 5066:         }
 5067:     }
 5068:     return %returnhash;
 5069: }
 5070: 
 5071: sub courselastaccess {
 5072:     my ($cdom,$cnum,$hostidref) = @_;
 5073:     my %returnhash;
 5074:     if ($cdom && $cnum) {
 5075:         my $chome = &homeserver($cnum,$cdom);
 5076:         if ($chome ne 'no_host') {
 5077:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5078:             &extract_lastaccess(\%returnhash,$rep);
 5079:         }
 5080:     } else {
 5081:         if (!$cdom) { $cdom=''; }
 5082:         my %libserv = &all_library();
 5083:         foreach my $tryserver (keys(%libserv)) {
 5084:             if (ref($hostidref) eq 'ARRAY') {
 5085:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5086:             } 
 5087:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5088:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5089:                 &extract_lastaccess(\%returnhash,$rep);
 5090:             }
 5091:         }
 5092:     }
 5093:     return %returnhash;
 5094: }
 5095: 
 5096: sub extract_lastaccess {
 5097:     my ($returnhash,$rep) = @_;
 5098:     if (ref($returnhash) eq 'HASH') {
 5099:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5100:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5101:                  $rep eq '') {
 5102:             my @pairs=split(/\&/,$rep);
 5103:             foreach my $item (@pairs) {
 5104:                 my ($key,$value)=split(/\=/,$item,2);
 5105:                 $key = &unescape($key);
 5106:                 next if ($key =~ /^error: 2 /);
 5107:                 $returnhash->{$key} = &thaw_unescape($value);
 5108:             }
 5109:         }
 5110:     }
 5111:     return;
 5112: }
 5113: 
 5114: # ---------------------------------------------------------- DC e-mail
 5115: 
 5116: sub dcmailput {
 5117:     my ($domain,$msgid,$message,$server)=@_;
 5118:     my $status = &Apache::lonnet::critical(
 5119:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5120:        &escape($message),$server);
 5121:     return $status;
 5122: }
 5123: 
 5124: sub dcmaildump {
 5125:     my ($dom,$startdate,$enddate,$senders) = @_;
 5126:     my %returnhash=();
 5127: 
 5128:     if (defined(&domain($dom,'primary'))) {
 5129:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5130:                                                          &escape($enddate).':';
 5131: 	my @esc_senders=map { &escape($_)} @$senders;
 5132: 	$cmd.=&escape(join('&',@esc_senders));
 5133: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5134:             my ($key,$value) = split(/\=/,$line,2);
 5135:             if (($key) && ($value)) {
 5136:                 $returnhash{&unescape($key)} = &unescape($value);
 5137:             }
 5138:         }
 5139:     }
 5140:     return %returnhash;
 5141: }
 5142: # ---------------------------------------------------------- Domain roles
 5143: 
 5144: sub get_domain_roles {
 5145:     my ($dom,$roles,$startdate,$enddate)=@_;
 5146:     if ((!defined($startdate)) || ($startdate eq '')) {
 5147:         $startdate = '.';
 5148:     }
 5149:     if ((!defined($enddate)) || ($enddate eq '')) {
 5150:         $enddate = '.';
 5151:     }
 5152:     my $rolelist;
 5153:     if (ref($roles) eq 'ARRAY') {
 5154:         $rolelist = join('&',@{$roles});
 5155:     }
 5156:     my %personnel = ();
 5157: 
 5158:     my %servers = &get_servers($dom,'library');
 5159:     foreach my $tryserver (keys(%servers)) {
 5160: 	%{$personnel{$tryserver}}=();
 5161: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5162: 					    &escape($startdate).':'.
 5163: 					    &escape($enddate).':'.
 5164: 					    &escape($rolelist), $tryserver))) {
 5165: 	    my ($key,$value) = split(/\=/,$line,2);
 5166: 	    if (($key) && ($value)) {
 5167: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5168: 	    }
 5169: 	}
 5170:     }
 5171:     return %personnel;
 5172: }
 5173: 
 5174: sub get_active_domroles {
 5175:     my ($dom,$roles) = @_;
 5176:     return () unless (ref($roles) eq 'ARRAY');
 5177:     my $now = time;
 5178:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5179:     my %domroles;
 5180:     foreach my $server (keys(%dompersonnel)) {
 5181:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5182:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5183:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5184:         }
 5185:     }
 5186:     return %domroles;
 5187: }
 5188: 
 5189: # ----------------------------------------------------------- Interval timing 
 5190: 
 5191: {
 5192: # Caches needed for speedup of navmaps
 5193: # We don't want to cache this for very long at all (5 seconds at most)
 5194: # 
 5195: # The user for whom we cache
 5196: my $cachedkey='';
 5197: # The cached times for this user
 5198: my %cachedtimes=();
 5199: # When this was last done
 5200: my $cachedtime='';
 5201: 
 5202: sub load_all_first_access {
 5203:     my ($uname,$udom,$ignorecache)=@_;
 5204:     if (($cachedkey eq $uname.':'.$udom) &&
 5205:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5206:         (!$ignorecache)) {
 5207:         return;
 5208:     }
 5209:     $cachedtime=time;
 5210:     $cachedkey=$uname.':'.$udom;
 5211:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5212: }
 5213: 
 5214: sub get_first_access {
 5215:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5216:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5217:     if ($argsymb) { $symb=$argsymb; }
 5218:     my ($map,$id,$res)=&decode_symb($symb);
 5219:     if ($argmap) { $map = $argmap; }
 5220:     if ($type eq 'course') {
 5221: 	$res='course';
 5222:     } elsif ($type eq 'map') {
 5223: 	$res=&symbread($map);
 5224:     } else {
 5225: 	$res=$symb;
 5226:     }
 5227:     &load_all_first_access($uname,$udom,$ignorecache);
 5228:     return $cachedtimes{"$courseid\0$res"};
 5229: }
 5230: 
 5231: sub set_first_access {
 5232:     my ($type,$interval)=@_;
 5233:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5234:     my ($map,$id,$res)=&decode_symb($symb);
 5235:     if ($type eq 'course') {
 5236: 	$res='course';
 5237:     } elsif ($type eq 'map') {
 5238: 	$res=&symbread($map);
 5239:     } else {
 5240: 	$res=$symb;
 5241:     }
 5242:     $cachedkey='';
 5243:     my $firstaccess=&get_first_access($type,$symb,$map);
 5244:     if ($firstaccess) {
 5245:         &logthis("First access time already set ($firstaccess) when attempting ".
 5246:                  "to set new value (type: $type, extent: $res) for $uname:$udom ". 
 5247:                  "in $courseid"); 
 5248:         return 'already_set';
 5249:     } else {
 5250:         my $start = time;
 5251: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5252:                           $udom,$uname);
 5253:         if ($putres eq 'ok') {
 5254:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5255:                  $udom,$uname); 
 5256:             &appenv(
 5257:                      {
 5258:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5259:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5260:                      }
 5261:                   );
 5262:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5263:                 $cachedtimes{"$courseid\0$res"} = $start;
 5264:             }
 5265:         } elsif ($putres ne 'refused') {
 5266:             &logthis("Result: $putres when attempting to set first access time ".
 5267:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5268:         }
 5269:         return $putres;
 5270:     }
 5271:     return 'already_set';
 5272: }
 5273: }
 5274: 
 5275: # --------------------------------------------- Set Expire Date for Spreadsheet
 5276: 
 5277: sub expirespread {
 5278:     my ($uname,$udom,$stype,$usymb)=@_;
 5279:     my $cid=$env{'request.course.id'}; 
 5280:     if ($cid) {
 5281:        my $now=time;
 5282:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5283:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5284:                             $env{'course.'.$cid.'.num'}.
 5285: 	        	    ':nohist_expirationdates:'.
 5286:                             &escape($key).'='.$now,
 5287:                             $env{'course.'.$cid.'.home'})
 5288:     }
 5289:     return 'ok';
 5290: }
 5291: 
 5292: # ----------------------------------------------------- Devalidate Spreadsheets
 5293: 
 5294: sub devalidate {
 5295:     my ($symb,$uname,$udom)=@_;
 5296:     my $cid=$env{'request.course.id'}; 
 5297:     if ($cid) {
 5298:         # delete the stored spreadsheets for
 5299:         # - the student level sheet of this user in course's homespace
 5300:         # - the assessment level sheet for this resource 
 5301:         #   for this user in user's homespace
 5302: 	# - current conditional state info
 5303: 	my $key=$uname.':'.$udom.':';
 5304:         my $status=
 5305: 	    &del('nohist_calculatedsheets',
 5306: 		 [$key.'studentcalc:'],
 5307: 		 $env{'course.'.$cid.'.domain'},
 5308: 		 $env{'course.'.$cid.'.num'})
 5309: 		.' '.
 5310: 	    &del('nohist_calculatedsheets_'.$cid,
 5311: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5312:         unless ($status eq 'ok ok') {
 5313:            &logthis('Could not devalidate spreadsheet '.
 5314:                     $uname.' at '.$udom.' for '.
 5315: 		    $symb.': '.$status);
 5316:         }
 5317: 	&delenv('user.state.'.$cid);
 5318:     }
 5319: }
 5320: 
 5321: sub get_scalar {
 5322:     my ($string,$end) = @_;
 5323:     my $value;
 5324:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5325: 	$value = $1;
 5326:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5327: 	$value = $1;
 5328:     }
 5329:     return &unescape($value);
 5330: }
 5331: 
 5332: sub array2str {
 5333:   my (@array) = @_;
 5334:   my $result=&arrayref2str(\@array);
 5335:   $result=~s/^__ARRAY_REF__//;
 5336:   $result=~s/__END_ARRAY_REF__$//;
 5337:   return $result;
 5338: }
 5339: 
 5340: sub arrayref2str {
 5341:   my ($arrayref) = @_;
 5342:   my $result='__ARRAY_REF__';
 5343:   foreach my $elem (@$arrayref) {
 5344:     if(ref($elem) eq 'ARRAY') {
 5345:       $result.=&arrayref2str($elem).'&';
 5346:     } elsif(ref($elem) eq 'HASH') {
 5347:       $result.=&hashref2str($elem).'&';
 5348:     } elsif(ref($elem)) {
 5349:       #print("Got a ref of ".(ref($elem))." skipping.");
 5350:     } else {
 5351:       $result.=&escape($elem).'&';
 5352:     }
 5353:   }
 5354:   $result=~s/\&$//;
 5355:   $result .= '__END_ARRAY_REF__';
 5356:   return $result;
 5357: }
 5358: 
 5359: sub hash2str {
 5360:   my (%hash) = @_;
 5361:   my $result=&hashref2str(\%hash);
 5362:   $result=~s/^__HASH_REF__//;
 5363:   $result=~s/__END_HASH_REF__$//;
 5364:   return $result;
 5365: }
 5366: 
 5367: sub hashref2str {
 5368:   my ($hashref)=@_;
 5369:   my $result='__HASH_REF__';
 5370:   foreach my $key (sort(keys(%$hashref))) {
 5371:     if (ref($key) eq 'ARRAY') {
 5372:       $result.=&arrayref2str($key).'=';
 5373:     } elsif (ref($key) eq 'HASH') {
 5374:       $result.=&hashref2str($key).'=';
 5375:     } elsif (ref($key)) {
 5376:       $result.='=';
 5377:       #print("Got a ref of ".(ref($key))." skipping.");
 5378:     } else {
 5379: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5380:     }
 5381: 
 5382:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5383:       $result.=&arrayref2str($hashref->{$key}).'&';
 5384:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5385:       $result.=&hashref2str($hashref->{$key}).'&';
 5386:     } elsif(ref($hashref->{$key})) {
 5387:        $result.='&';
 5388:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5389:     } else {
 5390:       $result.=&escape($hashref->{$key}).'&';
 5391:     }
 5392:   }
 5393:   $result=~s/\&$//;
 5394:   $result .= '__END_HASH_REF__';
 5395:   return $result;
 5396: }
 5397: 
 5398: sub str2hash {
 5399:     my ($string)=@_;
 5400:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5401:     return %$hash;
 5402: }
 5403: 
 5404: sub str2hashref {
 5405:   my ($string) = @_;
 5406: 
 5407:   my %hash;
 5408: 
 5409:   if($string !~ /^__HASH_REF__/) {
 5410:       if (! ($string eq '' || !defined($string))) {
 5411: 	  $hash{'error'}='Not hash reference';
 5412:       }
 5413:       return (\%hash, $string);
 5414:   }
 5415: 
 5416:   $string =~ s/^__HASH_REF__//;
 5417: 
 5418:   while($string !~ /^__END_HASH_REF__/) {
 5419:       #key
 5420:       my $key='';
 5421:       if($string =~ /^__HASH_REF__/) {
 5422:           ($key, $string)=&str2hashref($string);
 5423:           if(defined($key->{'error'})) {
 5424:               $hash{'error'}='Bad data';
 5425:               return (\%hash, $string);
 5426:           }
 5427:       } elsif($string =~ /^__ARRAY_REF__/) {
 5428:           ($key, $string)=&str2arrayref($string);
 5429:           if($key->[0] eq 'Array reference error') {
 5430:               $hash{'error'}='Bad data';
 5431:               return (\%hash, $string);
 5432:           }
 5433:       } else {
 5434:           $string =~ s/^(.*?)=//;
 5435: 	  $key=&unescape($1);
 5436:       }
 5437:       $string =~ s/^=//;
 5438: 
 5439:       #value
 5440:       my $value='';
 5441:       if($string =~ /^__HASH_REF__/) {
 5442:           ($value, $string)=&str2hashref($string);
 5443:           if(defined($value->{'error'})) {
 5444:               $hash{'error'}='Bad data';
 5445:               return (\%hash, $string);
 5446:           }
 5447:       } elsif($string =~ /^__ARRAY_REF__/) {
 5448:           ($value, $string)=&str2arrayref($string);
 5449:           if($value->[0] eq 'Array reference error') {
 5450:               $hash{'error'}='Bad data';
 5451:               return (\%hash, $string);
 5452:           }
 5453:       } else {
 5454: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5455:       }
 5456:       $string =~ s/^&//;
 5457: 
 5458:       $hash{$key}=$value;
 5459:   }
 5460: 
 5461:   $string =~ s/^__END_HASH_REF__//;
 5462: 
 5463:   return (\%hash, $string);
 5464: }
 5465: 
 5466: sub str2array {
 5467:     my ($string)=@_;
 5468:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5469:     return @$array;
 5470: }
 5471: 
 5472: sub str2arrayref {
 5473:   my ($string) = @_;
 5474:   my @array;
 5475: 
 5476:   if($string !~ /^__ARRAY_REF__/) {
 5477:       if (! ($string eq '' || !defined($string))) {
 5478: 	  $array[0]='Array reference error';
 5479:       }
 5480:       return (\@array, $string);
 5481:   }
 5482: 
 5483:   $string =~ s/^__ARRAY_REF__//;
 5484: 
 5485:   while($string !~ /^__END_ARRAY_REF__/) {
 5486:       my $value='';
 5487:       if($string =~ /^__HASH_REF__/) {
 5488:           ($value, $string)=&str2hashref($string);
 5489:           if(defined($value->{'error'})) {
 5490:               $array[0] ='Array reference error';
 5491:               return (\@array, $string);
 5492:           }
 5493:       } elsif($string =~ /^__ARRAY_REF__/) {
 5494:           ($value, $string)=&str2arrayref($string);
 5495:           if($value->[0] eq 'Array reference error') {
 5496:               $array[0] ='Array reference error';
 5497:               return (\@array, $string);
 5498:           }
 5499:       } else {
 5500: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5501:       }
 5502:       $string =~ s/^&//;
 5503: 
 5504:       push(@array, $value);
 5505:   }
 5506: 
 5507:   $string =~ s/^__END_ARRAY_REF__//;
 5508: 
 5509:   return (\@array, $string);
 5510: }
 5511: 
 5512: # -------------------------------------------------------------------Temp Store
 5513: 
 5514: sub tmpreset {
 5515:   my ($symb,$namespace,$domain,$stuname) = @_;
 5516:   if (!$symb) {
 5517:     $symb=&symbread();
 5518:     if (!$symb) { $symb= $env{'request.url'}; }
 5519:   }
 5520:   $symb=escape($symb);
 5521: 
 5522:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5523:   $namespace=~s/\//\_/g;
 5524:   $namespace=~s/\W//g;
 5525: 
 5526:   if (!$domain) { $domain=$env{'user.domain'}; }
 5527:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5528:   if ($domain eq 'public' && $stuname eq 'public') {
 5529:       $stuname=$ENV{'REMOTE_ADDR'};
 5530:   }
 5531:   my $path=LONCAPA::tempdir();
 5532:   my %hash;
 5533:   if (tie(%hash,'GDBM_File',
 5534: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5535: 	  &GDBM_WRCREAT(),0640)) {
 5536:     foreach my $key (keys(%hash)) {
 5537:       if ($key=~ /:$symb/) {
 5538: 	delete($hash{$key});
 5539:       }
 5540:     }
 5541:   }
 5542: }
 5543: 
 5544: sub tmpstore {
 5545:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5546: 
 5547:   if (!$symb) {
 5548:     $symb=&symbread();
 5549:     if (!$symb) { $symb= $env{'request.url'}; }
 5550:   }
 5551:   $symb=escape($symb);
 5552: 
 5553:   if (!$namespace) {
 5554:     # I don't think we would ever want to store this for a course.
 5555:     # it seems this will only be used if we don't have a course.
 5556:     #$namespace=$env{'request.course.id'};
 5557:     #if (!$namespace) {
 5558:       $namespace=$env{'request.state'};
 5559:     #}
 5560:   }
 5561:   $namespace=~s/\//\_/g;
 5562:   $namespace=~s/\W//g;
 5563:   if (!$domain) { $domain=$env{'user.domain'}; }
 5564:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5565:   if ($domain eq 'public' && $stuname eq 'public') {
 5566:       $stuname=$ENV{'REMOTE_ADDR'};
 5567:   }
 5568:   my $now=time;
 5569:   my %hash;
 5570:   my $path=LONCAPA::tempdir();
 5571:   if (tie(%hash,'GDBM_File',
 5572: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5573: 	  &GDBM_WRCREAT(),0640)) {
 5574:     $hash{"version:$symb"}++;
 5575:     my $version=$hash{"version:$symb"};
 5576:     my $allkeys=''; 
 5577:     foreach my $key (keys(%$storehash)) {
 5578:       $allkeys.=$key.':';
 5579:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5580:     }
 5581:     $hash{"$version:$symb:timestamp"}=$now;
 5582:     $allkeys.='timestamp';
 5583:     $hash{"$version:keys:$symb"}=$allkeys;
 5584:     if (untie(%hash)) {
 5585:       return 'ok';
 5586:     } else {
 5587:       return "error:$!";
 5588:     }
 5589:   } else {
 5590:     return "error:$!";
 5591:   }
 5592: }
 5593: 
 5594: # -----------------------------------------------------------------Temp Restore
 5595: 
 5596: sub tmprestore {
 5597:   my ($symb,$namespace,$domain,$stuname) = @_;
 5598: 
 5599:   if (!$symb) {
 5600:     $symb=&symbread();
 5601:     if (!$symb) { $symb= $env{'request.url'}; }
 5602:   }
 5603:   $symb=escape($symb);
 5604: 
 5605:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5606: 
 5607:   if (!$domain) { $domain=$env{'user.domain'}; }
 5608:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5609:   if ($domain eq 'public' && $stuname eq 'public') {
 5610:       $stuname=$ENV{'REMOTE_ADDR'};
 5611:   }
 5612:   my %returnhash;
 5613:   $namespace=~s/\//\_/g;
 5614:   $namespace=~s/\W//g;
 5615:   my %hash;
 5616:   my $path=LONCAPA::tempdir();
 5617:   if (tie(%hash,'GDBM_File',
 5618: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5619: 	  &GDBM_READER(),0640)) {
 5620:     my $version=$hash{"version:$symb"};
 5621:     $returnhash{'version'}=$version;
 5622:     my $scope;
 5623:     for ($scope=1;$scope<=$version;$scope++) {
 5624:       my $vkeys=$hash{"$scope:keys:$symb"};
 5625:       my @keys=split(/:/,$vkeys);
 5626:       my $key;
 5627:       $returnhash{"$scope:keys"}=$vkeys;
 5628:       foreach $key (@keys) {
 5629: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5630: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5631:       }
 5632:     }
 5633:     if (!(untie(%hash))) {
 5634:       return "error:$!";
 5635:     }
 5636:   } else {
 5637:     return "error:$!";
 5638:   }
 5639:   return %returnhash;
 5640: }
 5641: 
 5642: # ----------------------------------------------------------------------- Store
 5643: 
 5644: sub store {
 5645:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5646:     my $home='';
 5647: 
 5648:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5649: 
 5650:     $symb=&symbclean($symb);
 5651:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5652: 
 5653:     if (!$domain) { $domain=$env{'user.domain'}; }
 5654:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5655: 
 5656:     &devalidate($symb,$stuname,$domain);
 5657: 
 5658:     $symb=escape($symb);
 5659:     if (!$namespace) { 
 5660:        unless ($namespace=$env{'request.course.id'}) { 
 5661:           return ''; 
 5662:        } 
 5663:     }
 5664:     if (!$home) { $home=$env{'user.home'}; }
 5665: 
 5666:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5667:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5668: 
 5669:     my $namevalue='';
 5670:     foreach my $key (keys(%$storehash)) {
 5671:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5672:     }
 5673:     $namevalue=~s/\&$//;
 5674:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5675:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5676: }
 5677: 
 5678: # -------------------------------------------------------------- Critical Store
 5679: 
 5680: sub cstore {
 5681:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5682:     my $home='';
 5683: 
 5684:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5685: 
 5686:     $symb=&symbclean($symb);
 5687:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5688: 
 5689:     if (!$domain) { $domain=$env{'user.domain'}; }
 5690:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5691: 
 5692:     &devalidate($symb,$stuname,$domain);
 5693: 
 5694:     $symb=escape($symb);
 5695:     if (!$namespace) { 
 5696:        unless ($namespace=$env{'request.course.id'}) { 
 5697:           return ''; 
 5698:        } 
 5699:     }
 5700:     if (!$home) { $home=$env{'user.home'}; }
 5701: 
 5702:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5703:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5704: 
 5705:     my $namevalue='';
 5706:     foreach my $key (keys(%$storehash)) {
 5707:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5708:     }
 5709:     $namevalue=~s/\&$//;
 5710:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5711:     return critical
 5712:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5713: }
 5714: 
 5715: # --------------------------------------------------------------------- Restore
 5716: 
 5717: sub restore {
 5718:     my ($symb,$namespace,$domain,$stuname) = @_;
 5719:     my $home='';
 5720: 
 5721:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5722: 
 5723:     if (!$symb) {
 5724:         return if ($namespace eq 'courserequests');
 5725:         unless ($symb=escape(&symbread())) { return ''; }
 5726:     } else {
 5727:         unless ($namespace eq 'courserequests') {
 5728:             $symb=&escape(&symbclean($symb));
 5729:         }
 5730:     }
 5731:     if (!$namespace) { 
 5732:        unless ($namespace=$env{'request.course.id'}) { 
 5733:           return ''; 
 5734:        } 
 5735:     }
 5736:     if (!$domain) { $domain=$env{'user.domain'}; }
 5737:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5738:     if (!$home) { $home=$env{'user.home'}; }
 5739:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5740: 
 5741:     my %returnhash=();
 5742:     foreach my $line (split(/\&/,$answer)) {
 5743: 	my ($name,$value)=split(/\=/,$line);
 5744:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5745:     }
 5746:     my $version;
 5747:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5748:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5749:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5750:        }
 5751:     }
 5752:     return %returnhash;
 5753: }
 5754: 
 5755: # ---------------------------------------------------------- Course Description
 5756: #
 5757: #  
 5758: 
 5759: sub coursedescription {
 5760:     my ($courseid,$args)=@_;
 5761:     $courseid=~s/^\///;
 5762:     $courseid=~s/\_/\//g;
 5763:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5764:     my $chome=&homeserver($cnum,$cdomain);
 5765:     my $normalid=$cdomain.'_'.$cnum;
 5766:     # need to always cache even if we get errors otherwise we keep 
 5767:     # trying and trying and trying to get the course description.
 5768:     my %envhash=();
 5769:     my %returnhash=();
 5770:     
 5771:     my $expiretime=600;
 5772:     if ($env{'request.course.id'} eq $normalid) {
 5773: 	$expiretime=120;
 5774:     }
 5775: 
 5776:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5777:     if (!$args->{'freshen_cache'}
 5778: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5779: 	foreach my $key (keys(%env)) {
 5780: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5781: 	    my ($setting) = $1;
 5782: 	    $returnhash{$setting} = $env{$key};
 5783: 	}
 5784: 	return %returnhash;
 5785:     }
 5786: 
 5787:     # get the data again
 5788: 
 5789:     if (!$args->{'one_time'}) {
 5790: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5791:     }
 5792: 
 5793:     if ($chome ne 'no_host') {
 5794:        %returnhash=&dump('environment',$cdomain,$cnum);
 5795:        if (!exists($returnhash{'con_lost'})) {
 5796: 	   my $username = $env{'user.name'}; # Defult username
 5797: 	   if(defined $args->{'user'}) {
 5798: 	       $username = $args->{'user'};
 5799: 	   }
 5800:            $returnhash{'home'}= $chome;
 5801: 	   $returnhash{'domain'} = $cdomain;
 5802: 	   $returnhash{'num'} = $cnum;
 5803:            if (!defined($returnhash{'type'})) {
 5804:                $returnhash{'type'} = 'Course';
 5805:            }
 5806:            while (my ($name,$value) = each %returnhash) {
 5807:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5808:            }
 5809:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5810:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5811: 	       $username.'_'.$cdomain.'_'.$cnum;
 5812:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5813:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5814:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5815:        }
 5816:     }
 5817:     if (!$args->{'one_time'}) {
 5818: 	&appenv(\%envhash);
 5819:     }
 5820:     return %returnhash;
 5821: }
 5822: 
 5823: sub update_released_required {
 5824:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5825:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5826:         $cid = $env{'request.course.id'};
 5827:         $cdom = $env{'course.'.$cid.'.domain'};
 5828:         $cnum = $env{'course.'.$cid.'.num'};
 5829:         $chome = $env{'course.'.$cid.'.home'};
 5830:     }
 5831:     if ($needsrelease) {
 5832:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5833:         my $needsupdate;
 5834:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5835:             $needsupdate = 1;
 5836:         } else {
 5837:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5838:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5839:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5840:                 $needsupdate = 1;
 5841:             }
 5842:         }
 5843:         if ($needsupdate) {
 5844:             my %needshash = (
 5845:                              'internal.releaserequired' => $needsrelease,
 5846:                             );
 5847:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5848:             if ($putresult eq 'ok') {
 5849:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5850:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5851:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5852:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5853:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5854:                 }
 5855:             }
 5856:         }
 5857:     }
 5858:     return;
 5859: }
 5860: 
 5861: # -------------------------------------------------See if a user is privileged
 5862: 
 5863: sub privileged {
 5864:     my ($username,$domain,$possdomains,$possroles)=@_;
 5865:     my $now = time;
 5866:     my $roles;
 5867:     if (ref($possroles) eq 'ARRAY') {
 5868:         $roles = $possroles; 
 5869:     } else {
 5870:         $roles = ['dc','su'];
 5871:     }
 5872:     if (ref($possdomains) eq 'ARRAY') {
 5873:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5874:         foreach my $dom (@{$possdomains}) {
 5875:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5876:                 (ref($privileged{$dom}) eq 'HASH')) {
 5877:                 foreach my $role (@{$roles}) {
 5878:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5879:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5880:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5881:                             return 1 unless (($end && $end < $now) ||
 5882:                                              ($start && $start > $now));
 5883:                         }
 5884:                     }
 5885:                 }
 5886:             }
 5887:         }
 5888:     } else {
 5889:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5890:         my $now = time;
 5891: 
 5892:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5893:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5894:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5895:                 return 1 unless ($tend && $tend < $now) 
 5896:                         or ($tstart && $tstart > $now);
 5897:             }
 5898:         }
 5899:     }
 5900:     return 0;
 5901: }
 5902: 
 5903: sub privileged_by_domain {
 5904:     my ($domains,$roles) = @_;
 5905:     my %privileged = ();
 5906:     my $cachetime = 60*60*24;
 5907:     my $now = time;
 5908:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5909:         return %privileged;
 5910:     }
 5911:     foreach my $dom (@{$domains}) {
 5912:         next if (ref($privileged{$dom}) eq 'HASH');
 5913:         my $needroles;
 5914:         foreach my $role (@{$roles}) {
 5915:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5916:             if (defined($cached)) {
 5917:                 if (ref($result) eq 'HASH') {
 5918:                     $privileged{$dom}{$role} = $result;
 5919:                 }
 5920:             } else {
 5921:                 $needroles = 1;
 5922:             }
 5923:         }
 5924:         if ($needroles) {
 5925:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5926:             $privileged{$dom} = {};
 5927:             foreach my $server (keys(%dompersonnel)) {
 5928:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5929:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5930:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5931:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5932:                         next if ($end && $end < $now);
 5933:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5934:                             $dompersonnel{$server}{$item};
 5935:                     }
 5936:                 }
 5937:             }
 5938:             if (ref($privileged{$dom}) eq 'HASH') {
 5939:                 foreach my $role (@{$roles}) {
 5940:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5941:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5942:                     } else {
 5943:                         my %hash = ();
 5944:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5945:                     }
 5946:                 }
 5947:             }
 5948:         }
 5949:     }
 5950:     return %privileged;
 5951: }
 5952: 
 5953: # -------------------------------------------------------- Get user privileges
 5954: 
 5955: sub rolesinit {
 5956:     my ($domain, $username) = @_;
 5957:     my %userroles = ('user.login.time' => time);
 5958:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5959: 
 5960:     # firstaccess and timerinterval are related to timed maps/resources. 
 5961:     # also, blocking can be triggered by an activating timer
 5962:     # it's saved in the user's %env.
 5963:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5964:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5965:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5966:         %timerintchk, %timerintenv);
 5967: 
 5968:     foreach my $key (keys(%firstaccess)) {
 5969:         my ($cid, $rest) = split(/\0/, $key);
 5970:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5971:     }
 5972: 
 5973:     foreach my $key (keys(%timerinterval)) {
 5974:         my ($cid,$rest) = split(/\0/,$key);
 5975:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5976:     }
 5977: 
 5978:     my %allroles=();
 5979:     my %allgroups=();
 5980: 
 5981:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5982:         my $role = $rolesdump{$area};
 5983:         $area =~ s/\_\w\w$//;
 5984: 
 5985:         my ($trole, $tend, $tstart, $group_privs);
 5986: 
 5987:         if ($role =~ /^cr/) {
 5988:         # Custom role, defined by a user 
 5989:         # e.g., user.role.cr/msu/smith/mynewrole
 5990:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5991:                 $trole = $1;
 5992:                 ($tend, $tstart) = split('_', $2);
 5993:             } else {
 5994:                 $trole = $role;
 5995:             }
 5996:         } elsif ($role =~ m|^gr/|) {
 5997:         # Role of member in a group, defined within a course/community
 5998:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5999:             ($trole, $tend, $tstart) = split(/_/, $role);
 6000:             next if $tstart eq '-1';
 6001:             ($trole, $group_privs) = split(/\//, $trole);
 6002:             $group_privs = &unescape($group_privs);
 6003:         } else {
 6004:         # Just a normal role, defined in roles.tab
 6005:             ($trole, $tend, $tstart) = split(/_/,$role);
 6006:         }
 6007: 
 6008:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6009:                  $username);
 6010:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6011: 
 6012:         # role expired or not available yet?
 6013:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6014:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6015: 
 6016:         next if $area eq '' or $trole eq '';
 6017: 
 6018:         my $spec = "$trole.$area";
 6019:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6020: 
 6021:         if ($trole =~ /^cr\//) {
 6022:         # Custom role, defined by a user
 6023:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6024:         } elsif ($trole eq 'gr') {
 6025:         # Role of a member in a group, defined within a course/community
 6026:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6027:             next;
 6028:         } else {
 6029:         # Normal role, defined in roles.tab
 6030:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6031:         }
 6032: 
 6033:         my $cid = $tdomain.'_'.$trest;
 6034:         unless ($firstaccchk{$cid}) {
 6035:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6036:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6037:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6038:                         $coursetimerstarts{$cid}{$item}; 
 6039:                 }
 6040:             }
 6041:             $firstaccchk{$cid} = 1;
 6042:         }
 6043:         unless ($timerintchk{$cid}) {
 6044:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6045:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6046:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6047:                        $coursetimerintervals{$cid}{$item};
 6048:                 }
 6049:             }
 6050:             $timerintchk{$cid} = 1;
 6051:         }
 6052:     }
 6053: 
 6054:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6055:                                                           \%allroles, \%allgroups);
 6056:     $env{'user.adv'} = $userroles{'user.adv'};
 6057:     $env{'user.rar'} = $userroles{'user.rar'};
 6058: 
 6059:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6060: }
 6061: 
 6062: sub set_arearole {
 6063:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6064:     unless ($nolog) {
 6065: # log the associated role with the area
 6066:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6067:     }
 6068:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6069: }
 6070: 
 6071: sub custom_roleprivs {
 6072:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6073:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6074:     my $homsvr = &homeserver($rauthor,$rdomain);
 6075:     if (&hostname($homsvr) ne '') {
 6076:         my ($rdummy,$roledef)=
 6077:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6078:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6079:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6080:             if (defined($syspriv)) {
 6081:                 if ($trest =~ /^$match_community$/) {
 6082:                     $syspriv =~ s/bre\&S//; 
 6083:                 }
 6084:                 $$allroles{'cm./'}.=':'.$syspriv;
 6085:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6086:             }
 6087:             if ($tdomain ne '') {
 6088:                 if (defined($dompriv)) {
 6089:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6090:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6091:                 }
 6092:                 if (($trest ne '') && (defined($coursepriv))) {
 6093:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6094:                         my $rolename = $1;
 6095:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6096:                     }
 6097:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6098:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6099:                 }
 6100:             }
 6101:         }
 6102:     }
 6103: }
 6104: 
 6105: sub course_adhocrole_privs {
 6106:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6107:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6108:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6109:         my (%currprivs,%storeprivs);
 6110:         foreach my $item (split(/:/,$coursepriv)) {
 6111:             my ($priv,$restrict) = split(/\&/,$item);
 6112:             $currprivs{$priv} = $restrict;
 6113:         }
 6114:         my (%possadd,%possremove,%full);
 6115:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6116:             my ($priv,$restrict)=split(/\&/,$item);
 6117:             $full{$priv} = $restrict;
 6118:         }
 6119:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6120:              next if ($item eq '');
 6121:              my ($rule,$rest) = split(/=/,$item);
 6122:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6123:              foreach my $priv (split(/:/,$rest)) {
 6124:                  if ($priv ne '') {
 6125:                      if ($rule eq 'off') {
 6126:                          $possremove{$priv} = 1;
 6127:                      } else {
 6128:                          $possadd{$priv} = 1;
 6129:                      }
 6130:                  }
 6131:              }
 6132:          }
 6133:          foreach my $priv (sort(keys(%full))) {
 6134:              if (exists($currprivs{$priv})) {
 6135:                  unless (exists($possremove{$priv})) {
 6136:                      $storeprivs{$priv} = $currprivs{$priv};
 6137:                  }
 6138:              } elsif (exists($possadd{$priv})) {
 6139:                  $storeprivs{$priv} = $full{$priv};
 6140:              }
 6141:          }
 6142:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6143:      }
 6144:      return $coursepriv;
 6145: }
 6146: 
 6147: sub group_roleprivs {
 6148:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6149:     my $access = 1;
 6150:     my $now = time;
 6151:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6152:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6153:     if ($access) {
 6154:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6155:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6156:     }
 6157: }
 6158: 
 6159: sub standard_roleprivs {
 6160:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6161:     if (defined($pr{$trole.':s'})) {
 6162:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6163:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6164:     }
 6165:     if ($tdomain ne '') {
 6166:         if (defined($pr{$trole.':d'})) {
 6167:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6168:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6169:         }
 6170:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6171:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6172:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6173:         }
 6174:     }
 6175: }
 6176: 
 6177: sub set_userprivs {
 6178:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6179:     my $author=0;
 6180:     my $adv=0;
 6181:     my $rar=0;
 6182:     my %grouproles = ();
 6183:     if (keys(%{$allgroups}) > 0) {
 6184:         my @groupkeys; 
 6185:         foreach my $role (keys(%{$allroles})) {
 6186:             push(@groupkeys,$role);
 6187:         }
 6188:         if (ref($groups_roles) eq 'HASH') {
 6189:             foreach my $key (keys(%{$groups_roles})) {
 6190:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6191:                     push(@groupkeys,$key);
 6192:                 }
 6193:             }
 6194:         }
 6195:         if (@groupkeys > 0) {
 6196:             foreach my $role (@groupkeys) {
 6197:                 my ($trole,$area,$sec,$extendedarea);
 6198:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6199:                     $trole = $1;
 6200:                     $area = $2;
 6201:                     $sec = $3;
 6202:                     $extendedarea = $area.$sec;
 6203:                     if (exists($$allgroups{$area})) {
 6204:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6205:                             my $spec = $trole.'.'.$extendedarea;
 6206:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6207:                                                 $$allgroups{$area}{$group};
 6208:                         }
 6209:                     }
 6210:                 }
 6211:             }
 6212:         }
 6213:     }
 6214:     foreach my $group (keys(%grouproles)) {
 6215:         $$allroles{$group} = $grouproles{$group};
 6216:     }
 6217:     foreach my $role (keys(%{$allroles})) {
 6218:         my %thesepriv;
 6219:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6220:         foreach my $item (split(/:/,$$allroles{$role})) {
 6221:             if ($item ne '') {
 6222:                 my ($privilege,$restrictions)=split(/&/,$item);
 6223:                 if ($restrictions eq '') {
 6224:                     $thesepriv{$privilege}='F';
 6225:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6226:                     $thesepriv{$privilege}.=$restrictions;
 6227:                 }
 6228:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6229:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6230:             }
 6231:         }
 6232:         my $thesestr='';
 6233:         foreach my $priv (sort(keys(%thesepriv))) {
 6234: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6235: 	}
 6236:         $userroles->{'user.priv.'.$role} = $thesestr;
 6237:     }
 6238:     return ($author,$adv,$rar);
 6239: }
 6240: 
 6241: sub role_status {
 6242:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6243:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6244:         my ($one,$two) = split(m{\./},$rolekey,2);
 6245:         (undef,undef,$$role) = split(/\./,$one,3);
 6246:         unless (!defined($$role) || $$role eq '') {
 6247:             $$where = '/'.$two;
 6248:             $$trolecode=$$role.'.'.$$where;
 6249:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6250:             $$tstatus='is';
 6251:             if ($$tstart && $$tstart>$update) {
 6252:                 $$tstatus='future';
 6253:                 if ($$tstart<$now) {
 6254:                     if ($$tstart && $$tstart>$refresh) {
 6255:                         if (($$where ne '') && ($$role ne '')) {
 6256:                             my (%allroles,%allgroups,$group_privs,
 6257:                                 %groups_roles,@rolecodes);
 6258:                             my %userroles = (
 6259:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6260:                             );
 6261:                             @rolecodes = ('cm'); 
 6262:                             my $spec=$$role.'.'.$$where;
 6263:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6264:                             if ($$role =~ /^cr\//) {
 6265:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6266:                                 push(@rolecodes,'cr');
 6267:                             } elsif ($$role eq 'gr') {
 6268:                                 push(@rolecodes,$$role);
 6269:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6270:                                                     $env{'user.name'});
 6271:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6272:                                 (undef,my $group_privs) = split(/\//,$trole);
 6273:                                 $group_privs = &unescape($group_privs);
 6274:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6275:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6276:                                 &get_groups_roles($tdomain,$trest,
 6277:                                                   \%course_roles,\@rolecodes,
 6278:                                                   \%groups_roles);
 6279:                             } else {
 6280:                                 push(@rolecodes,$$role);
 6281:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6282:                             }
 6283:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6284:                                                                    \%groups_roles);
 6285:                             &appenv(\%userroles,\@rolecodes);
 6286:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6287:                         }
 6288:                     }
 6289:                     $$tstatus = 'is';
 6290:                 }
 6291:             }
 6292:             if ($$tend) {
 6293:                 if ($$tend<$update) {
 6294:                     $$tstatus='expired';
 6295:                 } elsif ($$tend<$now) {
 6296:                     $$tstatus='will_not';
 6297:                 }
 6298:             }
 6299:         }
 6300:     }
 6301: }
 6302: 
 6303: sub get_groups_roles {
 6304:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6305:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6306:                   (ref($rolecodes) eq 'ARRAY') && 
 6307:                   (ref($groups_roles) eq 'HASH')); 
 6308:     if (keys(%{$cdom_courseroles}) > 0) {
 6309:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6310:         if ($cdom ne '' && $cnum ne '') {
 6311:             foreach my $key (keys(%{$cdom_courseroles})) {
 6312:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6313:                     my $crsrole = $1;
 6314:                     my $crssec = $2;
 6315:                     if ($crsrole =~ /^cr/) {
 6316:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6317:                             push(@{$rolecodes},'cr');
 6318:                         }
 6319:                     } else {
 6320:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6321:                             push(@{$rolecodes},$crsrole);
 6322:                         }
 6323:                     }
 6324:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6325:                     if ($crssec ne '') {
 6326:                         $rolekey .= "/$crssec";
 6327:                     }
 6328:                     $rolekey .= './';
 6329:                     $groups_roles->{$rolekey} = $rolecodes;
 6330:                 }
 6331:             }
 6332:         }
 6333:     }
 6334:     return;
 6335: }
 6336: 
 6337: sub delete_env_groupprivs {
 6338:     my ($where,$courseroles,$possroles) = @_;
 6339:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6340:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6341:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6342:         %{$courseroles->{$udom}} =
 6343:             &get_my_roles('','','userroles',['active'],
 6344:                           $possroles,[$udom],1);
 6345:     }
 6346:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6347:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6348:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6349:             my $area = '/'.$cdom.'/'.$cnum;
 6350:             my $privkey = "user.priv.$crsrole.$area";
 6351:             if ($crssec ne '') {
 6352:                 $privkey .= '/'.$crssec;
 6353:             }
 6354:             $privkey .= ".$area/$group";
 6355:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6356:         }
 6357:     }
 6358:     return;
 6359: }
 6360: 
 6361: sub check_adhoc_privs {
 6362:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6363:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6364:     if ($sec) {
 6365:         $cckey .= '/'.$sec;
 6366:     } 
 6367:     my $setprivs;
 6368:     if ($env{$cckey}) {
 6369:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6370:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6371:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6372:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6373:             $setprivs = 1;
 6374:         }
 6375:     } else {
 6376:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6377:         $setprivs = 1;
 6378:     }
 6379:     return $setprivs;
 6380: }
 6381: 
 6382: sub set_adhoc_privileges {
 6383: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6384:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6385:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6386:     if ($sec ne '') {
 6387:         $area .= '/'.$sec;
 6388:     }
 6389:     my $spec = $role.'.'.$area;
 6390:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6391:                                   $env{'user.name'},1);
 6392:     my %rolehash = ();
 6393:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6394:         my $rolename = $1;
 6395:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6396:         my %domdef = &get_domain_defaults($dcdom);
 6397:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6398:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6399:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6400:             }
 6401:         }
 6402:     } else {
 6403:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6404:     }
 6405:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6406:     &appenv(\%userroles,[$role,'cm']);
 6407:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6408:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6409:         &appenv( {'request.role'        => $spec,
 6410:                   'request.role.domain' => $dcdom,
 6411:                   'request.course.sec'  => $sec,
 6412:                  }
 6413:                );
 6414:         my $tadv=0;
 6415:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6416:         &appenv({'request.role.adv'    => $tadv});
 6417:     }
 6418: }
 6419: 
 6420: # --------------------------------------------------------------- get interface
 6421: 
 6422: sub get {
 6423:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6424:    my $items='';
 6425:    foreach my $item (@$storearr) {
 6426:        $items.=&escape($item).'&';
 6427:    }
 6428:    $items=~s/\&$//;
 6429:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6430:    if (!$uname) { $uname=$env{'user.name'}; }
 6431:    my $uhome=&homeserver($uname,$udomain);
 6432: 
 6433:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6434:    my @pairs=split(/\&/,$rep);
 6435:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6436:      return @pairs;
 6437:    }
 6438:    my %returnhash=();
 6439:    my $i=0;
 6440:    foreach my $item (@$storearr) {
 6441:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6442:       $i++;
 6443:    }
 6444:    return %returnhash;
 6445: }
 6446: 
 6447: # --------------------------------------------------------------- del interface
 6448: 
 6449: sub del {
 6450:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6451:    my $items='';
 6452:    foreach my $item (@$storearr) {
 6453:        $items.=&escape($item).'&';
 6454:    }
 6455: 
 6456:    $items=~s/\&$//;
 6457:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6458:    if (!$uname) { $uname=$env{'user.name'}; }
 6459:    my $uhome=&homeserver($uname,$udomain);
 6460:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6461: }
 6462: 
 6463: # -------------------------------------------------------------- dump interface
 6464: 
 6465: sub unserialize {
 6466:     my ($rep, $escapedkeys) = @_;
 6467: 
 6468:     return {} if $rep =~ /^error/;
 6469: 
 6470:     my %returnhash=();
 6471: 	foreach my $item (split(/\&/,$rep)) {
 6472: 	    my ($key, $value) = split(/=/, $item, 2);
 6473: 	    $key = unescape($key) unless $escapedkeys;
 6474: 	    next if $key =~ /^error: 2 /;
 6475: 	    $returnhash{$key} = &thaw_unescape($value);
 6476: 	}
 6477:     #return %returnhash;
 6478:     return \%returnhash;
 6479: }        
 6480: 
 6481: # see Lond::dump_with_regexp
 6482: # if $escapedkeys hash keys won't get unescaped.
 6483: sub dump {
 6484:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6485:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6486:     if (!$uname) { $uname=$env{'user.name'}; }
 6487:     my $uhome=&homeserver($uname,$udomain);
 6488: 
 6489:     if ($regexp) {
 6490:         $regexp=&escape($regexp);
 6491:     } else {
 6492:         $regexp='.';
 6493:     }
 6494:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6495:         # user is hosted on this machine
 6496:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6497:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6498:         return %{unserialize($reply, $escapedkeys)};
 6499:     }
 6500:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6501:     my @pairs=split(/\&/,$rep);
 6502:     my %returnhash=();
 6503:     if (!($rep =~ /^error/ )) {
 6504: 	foreach my $item (@pairs) {
 6505: 	    my ($key,$value)=split(/=/,$item,2);
 6506:         $key = unescape($key) unless $escapedkeys;
 6507:         #$key = &unescape($key);
 6508: 	    next if ($key =~ /^error: 2 /);
 6509: 	    $returnhash{$key}=&thaw_unescape($value);
 6510: 	}
 6511:     }
 6512:     return %returnhash;
 6513: }
 6514: 
 6515: 
 6516: # --------------------------------------------------------- dumpstore interface
 6517: 
 6518: sub dumpstore {
 6519:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6520:    # same as dump but keys must be escaped. They may contain colon separated
 6521:    # lists of values that may themself contain colons (e.g. symbs).
 6522:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6523: }
 6524: 
 6525: # -------------------------------------------------------------- keys interface
 6526: 
 6527: sub getkeys {
 6528:    my ($namespace,$udomain,$uname)=@_;
 6529:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6530:    if (!$uname) { $uname=$env{'user.name'}; }
 6531:    my $uhome=&homeserver($uname,$udomain);
 6532:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6533:    my @keyarray=();
 6534:    foreach my $key (split(/\&/,$rep)) {
 6535:       next if ($key =~ /^error: 2 /);
 6536:       push(@keyarray,&unescape($key));
 6537:    }
 6538:    return @keyarray;
 6539: }
 6540: 
 6541: # --------------------------------------------------------------- currentdump
 6542: sub currentdump {
 6543:    my ($courseid,$sdom,$sname)=@_;
 6544:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6545:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6546:    $sname    = $env{'user.name'}         if (! defined($sname));
 6547:    my $uhome = &homeserver($sname,$sdom);
 6548:    my $rep;
 6549: 
 6550:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6551:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6552:                    $courseid)));
 6553:    } else {
 6554:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6555:    }
 6556: 
 6557:    return if ($rep =~ /^(error:|no_such_host)/);
 6558:    #
 6559:    my %returnhash=();
 6560:    #
 6561:    if ($rep eq 'unknown_cmd') {
 6562:        # an old lond will not know currentdump
 6563:        # Do a dump and make it look like a currentdump
 6564:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6565:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6566:        my %hash = @tmp;
 6567:        @tmp=();
 6568:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6569:    } else {
 6570:        my @pairs=split(/\&/,$rep);
 6571:        foreach my $pair (@pairs) {
 6572:            my ($key,$value)=split(/=/,$pair,2);
 6573:            my ($symb,$param) = split(/:/,$key);
 6574:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6575:                                                         &thaw_unescape($value);
 6576:        }
 6577:    }
 6578:    return %returnhash;
 6579: }
 6580: 
 6581: sub convert_dump_to_currentdump{
 6582:     my %hash = %{shift()};
 6583:     my %returnhash;
 6584:     # Code ripped from lond, essentially.  The only difference
 6585:     # here is the unescaping done by lonnet::dump().  Conceivably
 6586:     # we might run in to problems with parameter names =~ /^v\./
 6587:     while (my ($key,$value) = each(%hash)) {
 6588:         my ($v,$symb,$param) = split(/:/,$key);
 6589: 	$symb  = &unescape($symb);
 6590: 	$param = &unescape($param);
 6591:         next if ($v eq 'version' || $symb eq 'keys');
 6592:         next if (exists($returnhash{$symb}) &&
 6593:                  exists($returnhash{$symb}->{$param}) &&
 6594:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6595:         $returnhash{$symb}->{$param}=$value;
 6596:         $returnhash{$symb}->{'v.'.$param}=$v;
 6597:     }
 6598:     #
 6599:     # Remove all of the keys in the hashes which keep track of
 6600:     # the version of the parameter.
 6601:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6602:         # use a foreach because we are going to delete from the hash.
 6603:         foreach my $key (keys(%$param_hash)) {
 6604:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6605:         }
 6606:     }
 6607:     return \%returnhash;
 6608: }
 6609: 
 6610: # ------------------------------------------------------ critical inc interface
 6611: 
 6612: sub cinc {
 6613:     return &inc(@_,'critical');
 6614: }
 6615: 
 6616: # --------------------------------------------------------------- inc interface
 6617: 
 6618: sub inc {
 6619:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6620:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6621:     if (!$uname) { $uname=$env{'user.name'}; }
 6622:     my $uhome=&homeserver($uname,$udomain);
 6623:     my $items='';
 6624:     if (! ref($store)) {
 6625:         # got a single value, so use that instead
 6626:         $items = &escape($store).'=&';
 6627:     } elsif (ref($store) eq 'SCALAR') {
 6628:         $items = &escape($$store).'=&';        
 6629:     } elsif (ref($store) eq 'ARRAY') {
 6630:         $items = join('=&',map {&escape($_);} @{$store});
 6631:     } elsif (ref($store) eq 'HASH') {
 6632:         while (my($key,$value) = each(%{$store})) {
 6633:             $items.= &escape($key).'='.&escape($value).'&';
 6634:         }
 6635:     }
 6636:     $items=~s/\&$//;
 6637:     if ($critical) {
 6638: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6639:     } else {
 6640: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6641:     }
 6642: }
 6643: 
 6644: # --------------------------------------------------------------- put interface
 6645: 
 6646: sub put {
 6647:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6648:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6649:    if (!$uname) { $uname=$env{'user.name'}; }
 6650:    my $uhome=&homeserver($uname,$udomain);
 6651:    my $items='';
 6652:    foreach my $item (keys(%$storehash)) {
 6653:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6654:    }
 6655:    $items=~s/\&$//;
 6656:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6657: }
 6658: 
 6659: # ------------------------------------------------------------ newput interface
 6660: 
 6661: sub newput {
 6662:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6663:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6664:    if (!$uname) { $uname=$env{'user.name'}; }
 6665:    my $uhome=&homeserver($uname,$udomain);
 6666:    my $items='';
 6667:    foreach my $key (keys(%$storehash)) {
 6668:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6669:    }
 6670:    $items=~s/\&$//;
 6671:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6672: }
 6673: 
 6674: # ---------------------------------------------------------  putstore interface
 6675: 
 6676: sub putstore {
 6677:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6678:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6679:    if (!$uname) { $uname=$env{'user.name'}; }
 6680:    my $uhome=&homeserver($uname,$udomain);
 6681:    my $items='';
 6682:    foreach my $key (keys(%$storehash)) {
 6683:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6684:    }
 6685:    $items=~s/\&$//;
 6686:    my $esc_symb=&escape($symb);
 6687:    my $esc_v=&escape($version);
 6688:    my $reply =
 6689:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6690: 	      $uhome);
 6691:    if (($tolog) && ($reply eq 'ok')) {
 6692:        my $namevalue='';
 6693:        foreach my $key (keys(%{$storehash})) {
 6694:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6695:        }
 6696:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6697:                      '&host='.&escape($perlvar{'lonHostID'}).
 6698:                      '&version='.$esc_v.
 6699:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6700:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6701:    }
 6702:    if ($reply eq 'unknown_cmd') {
 6703:        # gfall back to way things use to be done
 6704:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6705: 			    $uname);
 6706:    }
 6707:    return $reply;
 6708: }
 6709: 
 6710: sub old_putstore {
 6711:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6712:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6713:     if (!$uname) { $uname=$env{'user.name'}; }
 6714:     my $uhome=&homeserver($uname,$udomain);
 6715:     my %newstorehash;
 6716:     foreach my $item (keys(%$storehash)) {
 6717: 	my $key = $version.':'.&escape($symb).':'.$item;
 6718: 	$newstorehash{$key} = $storehash->{$item};
 6719:     }
 6720:     my $items='';
 6721:     my %allitems = ();
 6722:     foreach my $item (keys(%newstorehash)) {
 6723: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6724: 	    my $key = $1.':keys:'.$2;
 6725: 	    $allitems{$key} .= $3.':';
 6726: 	}
 6727: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6728:     }
 6729:     foreach my $item (keys(%allitems)) {
 6730: 	$allitems{$item} =~ s/\:$//;
 6731: 	$items.= $item.'='.$allitems{$item}.'&';
 6732:     }
 6733:     $items=~s/\&$//;
 6734:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6735: }
 6736: 
 6737: # ------------------------------------------------------ critical put interface
 6738: 
 6739: sub cput {
 6740:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6741:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6742:    if (!$uname) { $uname=$env{'user.name'}; }
 6743:    my $uhome=&homeserver($uname,$udomain);
 6744:    my $items='';
 6745:    foreach my $item (keys(%$storehash)) {
 6746:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6747:    }
 6748:    $items=~s/\&$//;
 6749:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6750: }
 6751: 
 6752: # -------------------------------------------------------------- eget interface
 6753: 
 6754: sub eget {
 6755:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6756:    my $items='';
 6757:    foreach my $item (@$storearr) {
 6758:        $items.=&escape($item).'&';
 6759:    }
 6760:    $items=~s/\&$//;
 6761:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6762:    if (!$uname) { $uname=$env{'user.name'}; }
 6763:    my $uhome=&homeserver($uname,$udomain);
 6764:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6765:    my @pairs=split(/\&/,$rep);
 6766:    my %returnhash=();
 6767:    my $i=0;
 6768:    foreach my $item (@$storearr) {
 6769:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6770:       $i++;
 6771:    }
 6772:    return %returnhash;
 6773: }
 6774: 
 6775: # ------------------------------------------------------------ tmpput interface
 6776: sub tmpput {
 6777:     my ($storehash,$server,$context)=@_;
 6778:     my $items='';
 6779:     foreach my $item (keys(%$storehash)) {
 6780: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6781:     }
 6782:     $items=~s/\&$//;
 6783:     if (defined($context)) {
 6784:         $items .= ':'.&escape($context);
 6785:     }
 6786:     return &reply("tmpput:$items",$server);
 6787: }
 6788: 
 6789: # ------------------------------------------------------------ tmpget interface
 6790: sub tmpget {
 6791:     my ($token,$server)=@_;
 6792:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6793:     my $rep=&reply("tmpget:$token",$server);
 6794:     my %returnhash;
 6795:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6796:         return %returnhash;
 6797:     }
 6798:     foreach my $item (split(/\&/,$rep)) {
 6799: 	my ($key,$value)=split(/=/,$item);
 6800: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6801:     }
 6802:     return %returnhash;
 6803: }
 6804: 
 6805: # ------------------------------------------------------------ tmpdel interface
 6806: sub tmpdel {
 6807:     my ($token,$server)=@_;
 6808:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6809:     return &reply("tmpdel:$token",$server);
 6810: }
 6811: 
 6812: # ------------------------------------------------------------ get_timebased_id 
 6813: 
 6814: sub get_timebased_id {
 6815:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6816:         $maxtries) = @_;
 6817:     my ($newid,$error,$dellock);
 6818:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6819:         return ('','ok','invalid call to get suffix');
 6820:     }
 6821: 
 6822: # set defaults for any optional args for which values were not supplied
 6823:     if ($who eq '') {
 6824:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6825:     }
 6826:     if (!$locktries) {
 6827:         $locktries = 3;
 6828:     }
 6829:     if (!$maxtries) {
 6830:         $maxtries = 10;
 6831:     }
 6832:     
 6833:     if (($cdom eq '') || ($cnum eq '')) {
 6834:         if ($env{'request.course.id'}) {
 6835:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6836:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6837:         }
 6838:         if (($cdom eq '') || ($cnum eq '')) {
 6839:             return ('','ok','call to get suffix not in course context');
 6840:         }
 6841:     }
 6842: 
 6843: # construct locking item
 6844:     my $lockhash = {
 6845:                       $prefix."\0".'locked_'.$keyid => $who,
 6846:                    };
 6847:     my $tries = 0;
 6848: 
 6849: # attempt to get lock on nohist_$namespace file
 6850:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6851:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6852:         $tries ++;
 6853:         sleep 1;
 6854:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6855:     }
 6856: 
 6857: # attempt to get unique identifier, based on current timestamp
 6858:     if ($gotlock eq 'ok') {
 6859:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6860:         my $id = time;
 6861:         $newid = $id;
 6862:         if ($idtype eq 'addcode') {
 6863:             $newid .= &sixnum_code();
 6864:         }
 6865:         my $idtries = 0;
 6866:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6867:             if ($idtype eq 'concat') {
 6868:                 $newid = $id.$idtries;
 6869:             } elsif ($idtype eq 'addcode') {
 6870:                 $newid = $newid.&sixnum_code();
 6871:             } else {
 6872:                 $newid ++;
 6873:             }
 6874:             $idtries ++;
 6875:         }
 6876:         if (!exists($inuse{$prefix."\0".$newid})) {
 6877:             my %new_item =  (
 6878:                               $prefix."\0".$newid => $who,
 6879:                             );
 6880:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6881:                                                  $cdom,$cnum);
 6882:             if ($putresult ne 'ok') {
 6883:                 undef($newid);
 6884:                 $error = 'error saving new item: '.$putresult;
 6885:             }
 6886:         } else {
 6887:              undef($newid);
 6888:              $error = ('error: no unique suffix available for the new item ');
 6889:         }
 6890: #  remove lock
 6891:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6892:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6893:     } else {
 6894:         $error = "error: could not obtain lockfile\n";
 6895:         $dellock = 'ok';
 6896:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6897:             $dellock = 'nolock';
 6898:         }
 6899:     }
 6900:     return ($newid,$dellock,$error);
 6901: }
 6902: 
 6903: sub sixnum_code {
 6904:     my $code;
 6905:     for (0..6) {
 6906:         $code .= int( rand(9) );
 6907:     }
 6908:     return $code;
 6909: }
 6910: 
 6911: # -------------------------------------------------- portfolio access checking
 6912: 
 6913: sub portfolio_access {
 6914:     my ($requrl,$clientip) = @_;
 6915:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6916:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6917:     if ($result) {
 6918:         my %setters;
 6919:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6920:             my ($startblock,$endblock) =
 6921:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6922:             if ($startblock && $endblock) {
 6923:                 return 'B';
 6924:             }
 6925:         } else {
 6926:             my ($startblock,$endblock) =
 6927:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6928:             if ($startblock && $endblock) {
 6929:                 return 'B';
 6930:             }
 6931:         }
 6932:     }
 6933:     if ($result eq 'ok') {
 6934:        return 'F';
 6935:     } elsif ($result =~ /^[^:]+:guest_/) {
 6936:        return 'A';
 6937:     }
 6938:     return '';
 6939: }
 6940: 
 6941: sub get_portfolio_access {
 6942:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6943: 
 6944:     if (!ref($access_hash)) {
 6945: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6946: 	my %access_controls = &get_access_controls($current_perms,$group,
 6947: 						   $file_name);
 6948: 	$access_hash = $access_controls{$file_name};
 6949:     }
 6950: 
 6951:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6952:     my $now = time;
 6953:     if (ref($access_hash) eq 'HASH') {
 6954:         foreach my $key (keys(%{$access_hash})) {
 6955:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6956:             if ($start > $now) {
 6957:                 next;
 6958:             }
 6959:             if ($end && $end<$now) {
 6960:                 next;
 6961:             }
 6962:             if ($scope eq 'public') {
 6963:                 $public = $key;
 6964:                 last;
 6965:             } elsif ($scope eq 'guest') {
 6966:                 $guest = $key;
 6967:             } elsif ($scope eq 'domains') {
 6968:                 push(@domains,$key);
 6969:             } elsif ($scope eq 'users') {
 6970:                 push(@users,$key);
 6971:             } elsif ($scope eq 'course') {
 6972:                 push(@courses,$key);
 6973:             } elsif ($scope eq 'group') {
 6974:                 push(@groups,$key);
 6975:             } elsif ($scope eq 'ip') {
 6976:                 push(@ips,$key);
 6977:             }
 6978:         }
 6979:         if ($public) {
 6980:             return 'ok';
 6981:         } elsif (@ips > 0) {
 6982:             my $allowed;
 6983:             foreach my $ipkey (@ips) {
 6984:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6985:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6986:                         $allowed = 1;
 6987:                         last; 
 6988:                     }
 6989:                 }
 6990:             }
 6991:             if ($allowed) {
 6992:                 return 'ok';
 6993:             }
 6994:         }
 6995:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6996:             if ($guest) {
 6997:                 return $guest;
 6998:             }
 6999:         } else {
 7000:             if (@domains > 0) {
 7001:                 foreach my $domkey (@domains) {
 7002:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7003:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7004:                             return 'ok';
 7005:                         }
 7006:                     }
 7007:                 }
 7008:             }
 7009:             if (@users > 0) {
 7010:                 foreach my $userkey (@users) {
 7011:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7012:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7013:                             if (ref($item) eq 'HASH') {
 7014:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7015:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7016:                                     return 'ok';
 7017:                                 }
 7018:                             }
 7019:                         }
 7020:                     } 
 7021:                 }
 7022:             }
 7023:             my %roleshash;
 7024:             my @courses_and_groups = @courses;
 7025:             push(@courses_and_groups,@groups); 
 7026:             if (@courses_and_groups > 0) {
 7027:                 my (%allgroups,%allroles); 
 7028:                 my ($start,$end,$role,$sec,$group);
 7029:                 foreach my $envkey (%env) {
 7030:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7031:                         my $cid = $2.'_'.$3; 
 7032:                         if ($1 eq 'gr') {
 7033:                             $group = $4;
 7034:                             $allgroups{$cid}{$group} = $env{$envkey};
 7035:                         } else {
 7036:                             if ($4 eq '') {
 7037:                                 $sec = 'none';
 7038:                             } else {
 7039:                                 $sec = $4;
 7040:                             }
 7041:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7042:                         }
 7043:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7044:                         my $cid = $2.'_'.$3;
 7045:                         if ($4 eq '') {
 7046:                             $sec = 'none';
 7047:                         } else {
 7048:                             $sec = $4;
 7049:                         }
 7050:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7051:                     }
 7052:                 }
 7053:                 if (keys(%allroles) == 0) {
 7054:                     return;
 7055:                 }
 7056:                 foreach my $key (@courses_and_groups) {
 7057:                     my %content = %{$$access_hash{$key}};
 7058:                     my $cnum = $content{'number'};
 7059:                     my $cdom = $content{'domain'};
 7060:                     my $cid = $cdom.'_'.$cnum;
 7061:                     if (!exists($allroles{$cid})) {
 7062:                         next;
 7063:                     }    
 7064:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7065:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7066:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7067:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7068:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7069:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7070:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7071:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7072:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7073:                                         if (grep/^all$/,@sections) {
 7074:                                             return 'ok';
 7075:                                         } else {
 7076:                                             if (grep/^$sec$/,@sections) {
 7077:                                                 return 'ok';
 7078:                                             }
 7079:                                         }
 7080:                                     }
 7081:                                 }
 7082:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7083:                                     if (grep/^none$/,@groups) {
 7084:                                         return 'ok';
 7085:                                     }
 7086:                                 } else {
 7087:                                     if (grep/^all$/,@groups) {
 7088:                                         return 'ok';
 7089:                                     } 
 7090:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7091:                                         if (grep/^$group$/,@groups) {
 7092:                                             return 'ok';
 7093:                                         }
 7094:                                     }
 7095:                                 } 
 7096:                             }
 7097:                         }
 7098:                     }
 7099:                 }
 7100:             }
 7101:             if ($guest) {
 7102:                 return $guest;
 7103:             }
 7104:         }
 7105:     }
 7106:     return;
 7107: }
 7108: 
 7109: sub course_group_datechecker {
 7110:     my ($dates,$now,$status) = @_;
 7111:     my ($start,$end) = split(/\./,$dates);
 7112:     if (!$start && !$end) {
 7113:         return 'ok';
 7114:     }
 7115:     if (grep/^active$/,@{$status}) {
 7116:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7117:             return 'ok';
 7118:         }
 7119:     }
 7120:     if (grep/^previous$/,@{$status}) {
 7121:         if ($end > $now ) {
 7122:             return 'ok';
 7123:         }
 7124:     }
 7125:     if (grep/^future$/,@{$status}) {
 7126:         if ($start > $now) {
 7127:             return 'ok';
 7128:         }
 7129:     }
 7130:     return; 
 7131: }
 7132: 
 7133: sub parse_portfolio_url {
 7134:     my ($url) = @_;
 7135: 
 7136:     my ($type,$udom,$unum,$group,$file_name);
 7137:     
 7138:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7139: 	$type = 1;
 7140:         $udom = $1;
 7141:         $unum = $2;
 7142:         $file_name = $3;
 7143:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7144: 	$type = 2;
 7145:         $udom = $1;
 7146:         $unum = $2;
 7147:         $group = $3;
 7148:         $file_name = $3.'/'.$4;
 7149:     }
 7150:     if (wantarray) {
 7151: 	return ($type,$udom,$unum,$file_name,$group);
 7152:     }
 7153:     return $type;
 7154: }
 7155: 
 7156: sub is_portfolio_url {
 7157:     my ($url) = @_;
 7158:     return scalar(&parse_portfolio_url($url));
 7159: }
 7160: 
 7161: sub is_portfolio_file {
 7162:     my ($file) = @_;
 7163:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7164:         return 1;
 7165:     }
 7166:     return;
 7167: }
 7168: 
 7169: sub usertools_access {
 7170:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7171:     my ($access,%tools);
 7172:     if ($context eq '') {
 7173:         $context = 'tools';
 7174:     }
 7175:     if ($context eq 'requestcourses') {
 7176:         %tools = (
 7177:                       official   => 1,
 7178:                       unofficial => 1,
 7179:                       community  => 1,
 7180:                       textbook   => 1,
 7181:                       placement  => 1,
 7182:                       lti        => 1,
 7183:                  );
 7184:     } elsif ($context eq 'requestauthor') {
 7185:         %tools = (
 7186:                       requestauthor => 1,
 7187:                  );
 7188:     } else {
 7189:         %tools = (
 7190:                       aboutme   => 1,
 7191:                       blog      => 1,
 7192:                       webdav    => 1,
 7193:                       portfolio => 1,
 7194:                  );
 7195:     }
 7196:     return if (!defined($tools{$tool}));
 7197: 
 7198:     if (($udom eq '') || ($uname eq '')) {
 7199:         $udom = $env{'user.domain'};
 7200:         $uname = $env{'user.name'};
 7201:     }
 7202: 
 7203:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7204:         if ($action ne 'reload') {
 7205:             if ($context eq 'requestcourses') {
 7206:                 return $env{'environment.canrequest.'.$tool};
 7207:             } elsif ($context eq 'requestauthor') {
 7208:                 return $env{'environment.canrequest.author'};
 7209:             } else {
 7210:                 return $env{'environment.availabletools.'.$tool};
 7211:             }
 7212:         }
 7213:     }
 7214: 
 7215:     my ($toolstatus,$inststatus,$envkey);
 7216:     if ($context eq 'requestauthor') {
 7217:         $envkey = $context; 
 7218:     } else {
 7219:         $envkey = $context.'.'.$tool;
 7220:     }
 7221: 
 7222:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7223:          ($action ne 'reload')) {
 7224:         $toolstatus = $env{'environment.'.$envkey};
 7225:         $inststatus = $env{'environment.inststatus'};
 7226:     } else {
 7227:         if (ref($userenvref) eq 'HASH') {
 7228:             $toolstatus = $userenvref->{$envkey};
 7229:             $inststatus = $userenvref->{'inststatus'};
 7230:         } else {
 7231:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7232:             $toolstatus = $userenv{$envkey};
 7233:             $inststatus = $userenv{'inststatus'};
 7234:         }
 7235:     }
 7236: 
 7237:     if ($toolstatus ne '') {
 7238:         if ($toolstatus) {
 7239:             $access = 1;
 7240:         } else {
 7241:             $access = 0;
 7242:         }
 7243:         return $access;
 7244:     }
 7245: 
 7246:     my ($is_adv,%domdef);
 7247:     if (ref($is_advref) eq 'HASH') {
 7248:         $is_adv = $is_advref->{'is_adv'};
 7249:     } else {
 7250:         $is_adv = &is_advanced_user($udom,$uname);
 7251:     }
 7252:     if (ref($domdefref) eq 'HASH') {
 7253:         %domdef = %{$domdefref};
 7254:     } else {
 7255:         %domdef = &get_domain_defaults($udom);
 7256:     }
 7257:     if (ref($domdef{$tool}) eq 'HASH') {
 7258:         if ($is_adv) {
 7259:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7260:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7261:                     $access = 1;
 7262:                 } else {
 7263:                     $access = 0;
 7264:                 }
 7265:                 return $access;
 7266:             }
 7267:         }
 7268:         if ($inststatus ne '') {
 7269:             my ($hasaccess,$hasnoaccess);
 7270:             foreach my $affiliation (split(/:/,$inststatus)) {
 7271:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7272:                     if ($domdef{$tool}{$affiliation}) {
 7273:                         $hasaccess = 1;
 7274:                     } else {
 7275:                         $hasnoaccess = 1;
 7276:                     }
 7277:                 }
 7278:             }
 7279:             if ($hasaccess || $hasnoaccess) {
 7280:                 if ($hasaccess) {
 7281:                     $access = 1;
 7282:                 } elsif ($hasnoaccess) {
 7283:                     $access = 0; 
 7284:                 }
 7285:                 return $access;
 7286:             }
 7287:         } else {
 7288:             if ($domdef{$tool}{'default'} ne '') {
 7289:                 if ($domdef{$tool}{'default'}) {
 7290:                     $access = 1;
 7291:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7292:                     $access = 0;
 7293:                 }
 7294:                 return $access;
 7295:             }
 7296:         }
 7297:     } else {
 7298:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7299:             $access = 1;
 7300:         } else {
 7301:             $access = 0;
 7302:         }
 7303:         return $access;
 7304:     }
 7305: }
 7306: 
 7307: sub is_course_owner {
 7308:     my ($cdom,$cnum,$udom,$uname) = @_;
 7309:     if (($udom eq '') || ($uname eq '')) {
 7310:         $udom = $env{'user.domain'};
 7311:         $uname = $env{'user.name'};
 7312:     }
 7313:     unless (($udom eq '') || ($uname eq '')) {
 7314:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7315:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7316:                 return 1;
 7317:             } else {
 7318:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7319:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7320:                     return 1;
 7321:                 }
 7322:             }
 7323:         }
 7324:     }
 7325:     return;
 7326: }
 7327: 
 7328: sub is_advanced_user {
 7329:     my ($udom,$uname) = @_;
 7330:     if ($udom ne '' && $uname ne '') {
 7331:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7332:             if (wantarray) {
 7333:                 return ($env{'user.adv'},$env{'user.author'});
 7334:             } else {
 7335:                 return $env{'user.adv'};
 7336:             }
 7337:         }
 7338:     }
 7339:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7340:     my %allroles;
 7341:     my ($is_adv,$is_author);
 7342:     foreach my $role (keys(%roleshash)) {
 7343:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7344:         my $area = '/'.$tdomain.'/'.$trest;
 7345:         if ($sec ne '') {
 7346:             $area .= '/'.$sec;
 7347:         }
 7348:         if (($area ne '') && ($trole ne '')) {
 7349:             my $spec=$trole.'.'.$area;
 7350:             if ($trole =~ /^cr\//) {
 7351:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7352:             } elsif ($trole ne 'gr') {
 7353:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7354:             }
 7355:             if ($trole eq 'au') {
 7356:                 $is_author = 1;
 7357:             }
 7358:         }
 7359:     }
 7360:     foreach my $role (keys(%allroles)) {
 7361:         last if ($is_adv);
 7362:         foreach my $item (split(/:/,$allroles{$role})) {
 7363:             if ($item ne '') {
 7364:                 my ($privilege,$restrictions)=split(/&/,$item);
 7365:                 if ($privilege eq 'adv') {
 7366:                     $is_adv = 1;
 7367:                     last;
 7368:                 }
 7369:             }
 7370:         }
 7371:     }
 7372:     if (wantarray) {
 7373:         return ($is_adv,$is_author);
 7374:     }
 7375:     return $is_adv;
 7376: }
 7377: 
 7378: sub check_can_request {
 7379:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7380:     my $canreq = 0;
 7381:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7382:         $uname = $env{'user.name'};
 7383:         $udom = $env{'user.domain'};
 7384:     }
 7385:     my ($types,$typename) = &Apache::loncommon::course_types();
 7386:     my @options = ('approval','validate','autolimit');
 7387:     my $optregex = join('|',@options);
 7388:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7389:         foreach my $type (@{$types}) {
 7390:             if (&usertools_access($uname,$udom,$type,undef,
 7391:                                   'requestcourses')) {
 7392:                 $canreq ++;
 7393:                 if (ref($request_domains) eq 'HASH') {
 7394:                     push(@{$request_domains->{$type}},$udom);
 7395:                 }
 7396:                 if ($dom eq $udom) {
 7397:                     $can_request->{$type} = 1;
 7398:                 }
 7399:             }
 7400:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7401:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7402:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7403:                 if (@curr > 0) {
 7404:                     foreach my $item (@curr) {
 7405:                         if (ref($request_domains) eq 'HASH') {
 7406:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7407:                             if ($otherdom ne '') {
 7408:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7409:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7410:                                         push(@{$request_domains->{$type}},$otherdom);
 7411:                                     }
 7412:                                 } else {
 7413:                                     push(@{$request_domains->{$type}},$otherdom);
 7414:                                 }
 7415:                             }
 7416:                         }
 7417:                     }
 7418:                     unless ($dom eq $env{'user.domain'}) {
 7419:                         $canreq ++;
 7420:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7421:                             $can_request->{$type} = 1;
 7422:                         }
 7423:                     }
 7424:                 }
 7425:             }
 7426:         }
 7427:     }
 7428:     return $canreq;
 7429: }
 7430: 
 7431: # ---------------------------------------------- Custom access rule evaluation
 7432: 
 7433: sub customaccess {
 7434:     my ($priv,$uri)=@_;
 7435:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7436:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7437:     $udom = &LONCAPA::clean_domain($udom);
 7438:     $ucrs = &LONCAPA::clean_username($ucrs);
 7439:     my $access=0;
 7440:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7441: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7442: 	if ($type eq 'user') {
 7443: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7444: 		my ($tdom,$tuname)=split(m{/},$scope);
 7445: 		if ($tdom) {
 7446: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7447: 		}
 7448: 		if ($tuname) {
 7449: 		    if ($tuname ne $env{'user.name'}) { next; }
 7450: 		}
 7451: 		$access=($effect eq 'allow');
 7452: 		last;
 7453: 	    }
 7454: 	} else {
 7455: 	    if ($role) {
 7456: 		if ($role ne $urole) { next; }
 7457: 	    }
 7458: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7459: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7460: 		if ($tdom) {
 7461: 		    if ($tdom ne $udom) { next; }
 7462: 		}
 7463: 		if ($tcrs) {
 7464: 		    if ($tcrs ne $ucrs) { next; }
 7465: 		}
 7466: 		if ($tsec) {
 7467: 		    if ($tsec ne $usec) { next; }
 7468: 		}
 7469: 		$access=($effect eq 'allow');
 7470: 		last;
 7471: 	    }
 7472: 	    if ($realm eq '' && $role eq '') {
 7473: 		$access=($effect eq 'allow');
 7474: 	    }
 7475: 	}
 7476:     }
 7477:     return $access;
 7478: }
 7479: 
 7480: # ------------------------------------------------- Check for a user privilege
 7481: 
 7482: sub allowed {
 7483:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7484:     my $ver_orguri=$uri;
 7485:     $uri=&deversion($uri);
 7486:     my $orguri=$uri;
 7487:     $uri=&declutter($uri);
 7488: 
 7489:     if ($priv eq 'evb') {
 7490: # Evade communication block restrictions for specified role in a course
 7491:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7492:             return $1;
 7493:         } else {
 7494:             return;
 7495:         }
 7496:     }
 7497: 
 7498:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7499: # Free bre access to adm and meta resources
 7500:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7501: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7502: 	&& ($priv eq 'bre')) {
 7503: 	return 'F';
 7504:     }
 7505: 
 7506: # Free bre access to user's own portfolio contents
 7507:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7508:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7509: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7510:         my %setters;
 7511:         my ($startblock,$endblock) = 
 7512:             &Apache::loncommon::blockcheck(\%setters,'port');
 7513:         if ($startblock && $endblock) {
 7514:             return 'B';
 7515:         } else {
 7516:             return 'F';
 7517:         }
 7518:     }
 7519: 
 7520: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7521:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7522:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7523:         if (exists($env{'request.course.id'})) {
 7524:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7525:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7526:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7527:                 my $courseprivid=$env{'request.course.id'};
 7528:                 $courseprivid=~s/\_/\//;
 7529:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7530:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7531:                     return $1; 
 7532:                 } else {
 7533:                     if ($env{'request.course.sec'}) {
 7534:                         $courseprivid.='/'.$env{'request.course.sec'};
 7535:                     }
 7536:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7537:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7538:                         return $2;
 7539:                     }
 7540:                 }
 7541:             }
 7542:         }
 7543:     }
 7544: 
 7545: # Free bre to public access
 7546: 
 7547:     if ($priv eq 'bre') {
 7548:         my $copyright;
 7549:         unless ($uri =~ /ext\.tool/) {
 7550:             $copyright=&metadata($uri,'copyright');
 7551:         }
 7552: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7553:            return 'F'; 
 7554:         }
 7555:         if ($copyright eq 'priv') {
 7556:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7557: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7558: 		return '';
 7559:             }
 7560:         }
 7561:         if ($copyright eq 'domain') {
 7562:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7563: 	    unless (($env{'user.domain'} eq $1) ||
 7564:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7565: 		return '';
 7566:             }
 7567:         }
 7568:         if ($env{'request.role'}=~ /li\.\//) {
 7569:             # Library role, so allow browsing of resources in this domain.
 7570:             return 'F';
 7571:         }
 7572:         if ($copyright eq 'custom') {
 7573: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7574:         }
 7575:     }
 7576:     # Domain coordinator is trying to create a course
 7577:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7578:         # uri is the requested domain in this case.
 7579:         # comparison to 'request.role.domain' shows if the user has selected
 7580:         # a role of dc for the domain in question.
 7581:         return 'F' if ($uri eq $env{'request.role.domain'});
 7582:     }
 7583: 
 7584:     my $thisallowed='';
 7585:     my $statecond=0;
 7586:     my $courseprivid='';
 7587: 
 7588:     my $ownaccess;
 7589:     # Community Coordinator or Assistant Co-author browsing resource space.
 7590:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7591:         if ($uri eq '') {
 7592:             $ownaccess = 1;
 7593:         } else {
 7594:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7595:                 my $udom = $env{'user.domain'};
 7596:                 my $uname = $env{'user.name'};
 7597:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7598:                     $ownaccess = 1;
 7599:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7600:                     unless ($uri =~ m{\.\./}) {
 7601:                         $ownaccess = 1;
 7602:                     }
 7603:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7604:                     my $now = time;
 7605:                     if ($uri =~ m{^([^/]+)/?$}) {
 7606:                         my $adom = $1;
 7607:                         foreach my $key (keys(%env)) {
 7608:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7609:                                 my ($start,$end) = split('.',$env{$key});
 7610:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7611:                                     $ownaccess = 1;
 7612:                                     last;
 7613:                                 }
 7614:                             }
 7615:                         }
 7616:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7617:                         my $adom = $1;
 7618:                         my $aname = $2;
 7619:                         foreach my $role ('ca','aa') { 
 7620:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7621:                                 my ($start,$end) =
 7622:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7623:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7624:                                     $ownaccess = 1;
 7625:                                     last;
 7626:                                 }
 7627:                             }
 7628:                         }
 7629:                     }
 7630:                 }
 7631:             }
 7632:         }
 7633:     }
 7634: 
 7635: # Course
 7636: 
 7637:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7638:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7639:             $thisallowed.=$1;
 7640:         }
 7641:     }
 7642: 
 7643: # Domain
 7644: 
 7645:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7646:        =~/\Q$priv\E\&([^\:]*)/) {
 7647:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7648:             $thisallowed.=$1;
 7649:         }
 7650:     }
 7651: 
 7652: # User who is not author or co-author might still be able to edit
 7653: # resource of an author in the domain (e.g., if Domain Coordinator).
 7654:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7655:         (&allowed('mdc',$env{'request.course.id'}))) {
 7656:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7657:             $thisallowed.=$1;
 7658:         }
 7659:     }
 7660: 
 7661: # Course: uri itself is a course
 7662:     my $courseuri=$uri;
 7663:     $courseuri=~s/\_(\d)/\/$1/;
 7664:     $courseuri=~s/^([^\/])/\/$1/;
 7665: 
 7666:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7667:        =~/\Q$priv\E\&([^\:]*)/) {
 7668:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7669:             $thisallowed.=$1;
 7670:         }
 7671:     }
 7672: 
 7673: # URI is an uploaded document for this course, default permissions don't matter
 7674: # not allowing 'edit' access (editupload) to uploaded course docs
 7675:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7676: 	$thisallowed='';
 7677:         my ($match)=&is_on_map($uri);
 7678:         if ($match) {
 7679:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7680:                   =~/\Q$priv\E\&([^\:]*)/) {
 7681:                 my $value = $1;
 7682:                 if ($noblockcheck) {
 7683:                     $thisallowed.=$value;
 7684:                 } else {
 7685:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7686:                     if (@blockers > 0) {
 7687:                         $thisallowed = 'B';
 7688:                     } else {
 7689:                         $thisallowed.=$value;
 7690:                     }
 7691:                 }
 7692:             }
 7693:         } else {
 7694:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7695:             if ($refuri) {
 7696:                 if ($refuri =~ m|^/adm/|) {
 7697:                     $thisallowed='F';
 7698:                 } else {
 7699:                     $refuri=&declutter($refuri);
 7700:                     my ($match) = &is_on_map($refuri);
 7701:                     if ($match) {
 7702:                         if ($noblockcheck) {
 7703:                             $thisallowed='F';
 7704:                         } else {
 7705:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7706:                             if (@blockers > 0) {
 7707:                                 $thisallowed = 'B';
 7708:                             } else {
 7709:                                 $thisallowed='F';
 7710:                             }
 7711:                         }
 7712:                     }
 7713:                 }
 7714:             }
 7715:         }
 7716:     }
 7717: 
 7718:     if ($priv eq 'bre'
 7719: 	&& $thisallowed ne 'F' 
 7720: 	&& $thisallowed ne '2'
 7721: 	&& &is_portfolio_url($uri)) {
 7722: 	$thisallowed = &portfolio_access($uri,$clientip);
 7723:     }
 7724: 
 7725: # Full access at system, domain or course-wide level? Exit.
 7726:     if ($thisallowed=~/F/) {
 7727: 	return 'F';
 7728:     }
 7729: 
 7730: # If this is generating or modifying users, exit with special codes
 7731: 
 7732:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7733: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7734: 	    my ($audom,$auname)=split('/',$uri);
 7735: # no author name given, so this just checks on the general right to make a co-author in this domain
 7736: 	    unless ($auname) { return $thisallowed; }
 7737: # an author name is given, so we are about to actually make a co-author for a certain account
 7738: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7739: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7740: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7741: 	}
 7742: 	return $thisallowed;
 7743:     }
 7744: #
 7745: # Gathered so far: system, domain and course wide privileges
 7746: #
 7747: # Course: See if uri or referer is an individual resource that is part of 
 7748: # the course
 7749: 
 7750:     if ($env{'request.course.id'}) {
 7751: 
 7752:        $courseprivid=$env{'request.course.id'};
 7753:        if ($env{'request.course.sec'}) {
 7754:           $courseprivid.='/'.$env{'request.course.sec'};
 7755:        }
 7756:        $courseprivid=~s/\_/\//;
 7757:        my $checkreferer=1;
 7758:        my ($match,$cond)=&is_on_map($uri);
 7759:        if ($match) {
 7760:            $statecond=$cond;
 7761:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7762:                =~/\Q$priv\E\&([^\:]*)/) {
 7763:                my $value = $1;
 7764:                if ($priv eq 'bre') {
 7765:                    if ($noblockcheck) {
 7766:                        $thisallowed.=$value;
 7767:                    } else {
 7768:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7769:                        if (@blockers > 0) {
 7770:                            $thisallowed = 'B';
 7771:                        } else {
 7772:                            $thisallowed.=$value;
 7773:                        }
 7774:                    }
 7775:                } else {
 7776:                    $thisallowed.=$value;
 7777:                }
 7778:                $checkreferer=0;
 7779:            }
 7780:        }
 7781:        
 7782:        if ($checkreferer) {
 7783: 	  my $refuri=$env{'httpref.'.$orguri};
 7784:             unless ($refuri) {
 7785:                 foreach my $key (keys(%env)) {
 7786: 		    if ($key=~/^httpref\..*\*/) {
 7787: 			my $pattern=$key;
 7788:                         $pattern=~s/^httpref\.\/res\///;
 7789:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7790:                         $pattern=~s/\//\\\//g;
 7791:                         if ($orguri=~/$pattern/) {
 7792: 			    $refuri=$env{$key};
 7793:                         }
 7794:                     }
 7795:                 }
 7796:             }
 7797: 
 7798:          if ($refuri) { 
 7799: 	  $refuri=&declutter($refuri);
 7800:           my ($match,$cond)=&is_on_map($refuri);
 7801:             if ($match) {
 7802:               my $refstatecond=$cond;
 7803:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7804:                   =~/\Q$priv\E\&([^\:]*)/) {
 7805:                   my $value = $1;
 7806:                   if ($priv eq 'bre') {
 7807:                       if ($noblockcheck) {
 7808:                           $thisallowed.=$value;
 7809:                       } else {
 7810:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7811:                           if (@blockers > 0) {
 7812:                               $thisallowed = 'B';
 7813:                           } else {
 7814:                               $thisallowed.=$value;
 7815:                           }
 7816:                       }
 7817:                   } else {
 7818:                       $thisallowed.=$value;
 7819:                   }
 7820:                   $uri=$refuri;
 7821:                   $statecond=$refstatecond;
 7822:               }
 7823:           }
 7824:         }
 7825:        }
 7826:    }
 7827: 
 7828: #
 7829: # Gathered now: all privileges that could apply, and condition number
 7830: # 
 7831: #
 7832: # Full or no access?
 7833: #
 7834: 
 7835:     if ($thisallowed=~/F/) {
 7836: 	return 'F';
 7837:     }
 7838: 
 7839:     unless ($thisallowed) {
 7840:         return '';
 7841:     }
 7842: 
 7843: # Restrictions exist, deal with them
 7844: #
 7845: #   C:according to course preferences
 7846: #   R:according to resource settings
 7847: #   L:unless locked
 7848: #   X:according to user session state
 7849: #
 7850: 
 7851: # Possibly locked functionality, check all courses
 7852: # Locks might take effect only after 10 minutes cache expiration for other
 7853: # courses, and 2 minutes for current course
 7854: 
 7855:     my $envkey;
 7856:     if ($thisallowed=~/L/) {
 7857:         foreach $envkey (keys(%env)) {
 7858:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7859:                my $courseid=$2;
 7860:                my $roleid=$1.'.'.$2;
 7861:                $courseid=~s/^\///;
 7862:                my $expiretime=600;
 7863:                if ($env{'request.role'} eq $roleid) {
 7864: 		  $expiretime=120;
 7865:                }
 7866: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7867:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7868:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7869: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7870:                }
 7871:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7872:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7873: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7874:                        &log($env{'user.domain'},$env{'user.name'},
 7875:                             $env{'user.home'},
 7876:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7877:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7878:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7879: 		       return '';
 7880:                    }
 7881:                }
 7882:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7883:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7884: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7885:                        &log($env{'user.domain'},$env{'user.name'},
 7886:                             $env{'user.home'},
 7887:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7888:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7889:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7890: 		       return '';
 7891:                    }
 7892:                }
 7893: 	   }
 7894:        }
 7895:     }
 7896:    
 7897: #
 7898: # Rest of the restrictions depend on selected course
 7899: #
 7900: 
 7901:     unless ($env{'request.course.id'}) {
 7902: 	if ($thisallowed eq 'A') {
 7903: 	    return 'A';
 7904:         } elsif ($thisallowed eq 'B') {
 7905:             return 'B';
 7906: 	} else {
 7907: 	    return '1';
 7908: 	}
 7909:     }
 7910: 
 7911: #
 7912: # Now user is definitely in a course
 7913: #
 7914: 
 7915: 
 7916: # Course preferences
 7917: 
 7918:    if ($thisallowed=~/C/) {
 7919:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7920:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7921:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7922: 	   =~/\Q$rolecode\E/) {
 7923: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7924: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7925: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7926: 			$env{'request.course.id'});
 7927: 	   }
 7928:            return '';
 7929:        }
 7930: 
 7931:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7932: 	   =~/\Q$unamedom\E/) {
 7933: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7934: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7935: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7936: 			$env{'request.course.id'});
 7937: 	   }
 7938:            return '';
 7939:        }
 7940:    }
 7941: 
 7942: # Resource preferences
 7943: 
 7944:    if ($thisallowed=~/R/) {
 7945:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7946:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7947: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7948: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7949: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7950: 	   }
 7951: 	   return '';
 7952:        }
 7953:    }
 7954: 
 7955: # Restricted by state or randomout?
 7956: 
 7957:    if ($thisallowed=~/X/) {
 7958:       if ($env{'acc.randomout'}) {
 7959: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7960:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7961:             return ''; 
 7962:          }
 7963:       }
 7964:       if (&condval($statecond)) {
 7965: 	 return '2';
 7966:       } else {
 7967:          return '';
 7968:       }
 7969:    }
 7970: 
 7971:     if ($thisallowed eq 'A') {
 7972: 	return 'A';
 7973:     } elsif ($thisallowed eq 'B') {
 7974:         return 'B';
 7975:     }
 7976:    return 'F';
 7977: }
 7978: 
 7979: # ------------------------------------------- Check construction space access
 7980: 
 7981: sub constructaccess {
 7982:     my ($url,$setpriv)=@_;
 7983: 
 7984: # We do not allow editing of previous versions of files
 7985:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7986: 
 7987: # Get username and domain from URL
 7988:     my ($ownername,$ownerdomain,$ownerhome);
 7989: 
 7990:     ($ownerdomain,$ownername) =
 7991:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 7992: 
 7993: # The URL does not really point to any authorspace, forget it
 7994:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7995: 
 7996: # Now we need to see if the user has access to the authorspace of
 7997: # $ownername at $ownerdomain
 7998: 
 7999:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8000: # Real author for this?
 8001:        $ownerhome = $env{'user.home'};
 8002:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8003:           return ($ownername,$ownerdomain,$ownerhome);
 8004:        }
 8005:     } else {
 8006: # Co-author for this?
 8007:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8008:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8009:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8010:             return ($ownername,$ownerdomain,$ownerhome);
 8011:         }
 8012:         if ($env{'request.course.id'}) {
 8013:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8014:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8015:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8016:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8017:                     return ($ownername,$ownerdomain,$ownerhome);
 8018:                 }
 8019:             }
 8020:         }
 8021:     }
 8022: 
 8023: # We don't have any access right now. If we are not possibly going to do anything about this,
 8024: # we might as well leave
 8025:    unless ($setpriv) { return ''; }
 8026: 
 8027: # Backdoor access?
 8028:     my $allowed=&allowed('eco',$ownerdomain);
 8029: # Nope
 8030:     unless ($allowed) { return ''; }
 8031: # Looks like we may have access, but could be locked by the owner of the construction space
 8032:     if ($allowed eq 'U') {
 8033:         my %blocked=&get('environment',['domcoord.author'],
 8034:                          $ownerdomain,$ownername);
 8035: # Is blocked by owner
 8036:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8037:     }
 8038:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8039: # Grant temporary access
 8040:         my $then=$env{'user.login.time'};
 8041:         my $update=$env{'user.update.time'};
 8042:         if (!$update) { $update = $then; }
 8043:         my $refresh=$env{'user.refresh.time'};
 8044:         if (!$refresh) { $refresh = $update; }
 8045:         my $now = time;
 8046:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8047:                            $now,'ca','constructaccess');
 8048:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8049:         return($ownername,$ownerdomain,$ownerhome);
 8050:     }
 8051: # No business here
 8052:     return '';
 8053: }
 8054: 
 8055: # ----------------------------------------------------------- Content Blocking
 8056: 
 8057: {
 8058: # Caches for faster Course Contents display where content blocking
 8059: # is in operation (i.e., interval param set) for timed quiz.
 8060: #
 8061: # User for whom data are being temporarily cached.
 8062: my $cacheduser='';
 8063: # Cached blockers for this user (a hash of blocking items). 
 8064: my %cachedblockers=();
 8065: # When the data were last cached.
 8066: my $cachedlast='';
 8067: 
 8068: sub load_all_blockers {
 8069:     my ($uname,$udom,$blocks)=@_;
 8070:     if (($uname ne '') && ($udom ne '')) { 
 8071:         if (($cacheduser eq $uname.':'.$udom) &&
 8072:             (abs($cachedlast-time)<5)) {
 8073:             return;
 8074:         }
 8075:     }
 8076:     $cachedlast=time;
 8077:     $cacheduser=$uname.':'.$udom;
 8078:     %cachedblockers = &get_commblock_resources($blocks);
 8079: }
 8080: 
 8081: sub get_comm_blocks {
 8082:     my ($cdom,$cnum) = @_;
 8083:     if ($cdom eq '' || $cnum eq '') {
 8084:         return unless ($env{'request.course.id'});
 8085:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8086:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8087:     }
 8088:     my %commblocks;
 8089:     my $hashid=$cdom.'_'.$cnum;
 8090:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8091:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8092:         %commblocks = %{$blocksref};
 8093:     } else {
 8094:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8095:         my $cachetime = 600;
 8096:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8097:     }
 8098:     return %commblocks;
 8099: }
 8100: 
 8101: sub get_commblock_resources {
 8102:     my ($blocks) = @_;
 8103:     my %blockers = ();
 8104:     return %blockers unless ($env{'request.course.id'});
 8105:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8106:     my %commblocks;
 8107:     if (ref($blocks) eq 'HASH') {
 8108:         %commblocks = %{$blocks};
 8109:     } else {
 8110:         %commblocks = &get_comm_blocks();
 8111:     }
 8112:     return %blockers unless (keys(%commblocks) > 0); 
 8113:     my $navmap = Apache::lonnavmaps::navmap->new();
 8114:     return %blockers unless (ref($navmap));
 8115:     my $now = time;
 8116:     foreach my $block (keys(%commblocks)) {
 8117:         if ($block =~ /^(\d+)____(\d+)$/) {
 8118:             my ($start,$end) = ($1,$2);
 8119:             if ($start <= $now && $end >= $now) {
 8120:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8121:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8122:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8123:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8124:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8125:                             }
 8126:                         }
 8127:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8128:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8129:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8130:                             }
 8131:                         }
 8132:                     }
 8133:                 }
 8134:             }
 8135:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8136:             my $item = $1;
 8137:             my @to_test;
 8138:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8139:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8140:                     my @interval;
 8141:                     my $type = 'map';
 8142:                     if ($item eq 'course') {
 8143:                         $type = 'course';
 8144:                         @interval=&EXT("resource.0.interval");
 8145:                     } else {
 8146:                         if ($item =~ /___\d+___/) {
 8147:                             $type = 'resource';
 8148:                             @interval=&EXT("resource.0.interval",$item);
 8149:                             if (ref($navmap)) {                        
 8150:                                 my $res = $navmap->getBySymb($item); 
 8151:                                 push(@to_test,$res);
 8152:                             }
 8153:                         } else {
 8154:                             my $mapsymb = &symbread($item,1);
 8155:                             if ($mapsymb) {
 8156:                                 if (ref($navmap)) {
 8157:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8158:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8159:                                     foreach my $res (@to_test) {
 8160:                                         my $symb = $res->symb();
 8161:                                         next if ($symb eq $mapsymb);
 8162:                                         if ($symb ne '') {
 8163:                                             @interval=&EXT("resource.0.interval",$symb);
 8164:                                             if ($interval[1] eq 'map') {
 8165:                                                 last;
 8166:                                             }
 8167:                                         }
 8168:                                     }
 8169:                                 }
 8170:                             }
 8171:                         }
 8172:                     }
 8173:                     if ($interval[0] =~ /^(\d+)/) {
 8174:                         my $timelimit = $1; 
 8175:                         my $first_access;
 8176:                         if ($type eq 'resource') {
 8177:                             $first_access=&get_first_access($interval[1],$item);
 8178:                         } elsif ($type eq 'map') {
 8179:                             $first_access=&get_first_access($interval[1],undef,$item);
 8180:                         } else {
 8181:                             $first_access=&get_first_access($interval[1]);
 8182:                         }
 8183:                         if ($first_access) {
 8184:                             my $timesup = $first_access+$timelimit;
 8185:                             if ($timesup > $now) {
 8186:                                 my $activeblock;
 8187:                                 foreach my $res (@to_test) {
 8188:                                     if ($res->answerable()) {
 8189:                                         $activeblock = 1;
 8190:                                         last;
 8191:                                     }
 8192:                                 }
 8193:                                 if ($activeblock) {
 8194:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8195:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8196:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8197:                                          }
 8198:                                     }
 8199:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8200:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8201:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8202:                                         }
 8203:                                     }
 8204:                                 }
 8205:                             }
 8206:                         }
 8207:                     }
 8208:                 }
 8209:             }
 8210:         }
 8211:     }
 8212:     return %blockers;
 8213: }
 8214: 
 8215: sub has_comm_blocking {
 8216:     my ($priv,$symb,$uri,$blocks) = @_;
 8217:     my @blockers;
 8218:     return unless ($env{'request.course.id'});
 8219:     return unless ($priv eq 'bre');
 8220:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8221:     return if ($env{'request.state'} eq 'construct');
 8222:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8223:     return unless (keys(%cachedblockers) > 0);
 8224:     my (%possibles,@symbs);
 8225:     if (!$symb) {
 8226:         $symb = &symbread($uri,1,1,1,\%possibles);
 8227:     }
 8228:     if ($symb) {
 8229:         @symbs = ($symb);
 8230:     } elsif (keys(%possibles)) { 
 8231:         @symbs = keys(%possibles);
 8232:     }
 8233:     my $noblock;
 8234:     foreach my $symb (@symbs) {
 8235:         last if ($noblock);
 8236:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8237:         foreach my $block (keys(%cachedblockers)) {
 8238:             if ($block =~ /^firstaccess____(.+)$/) {
 8239:                 my $item = $1;
 8240:                 if (($item eq $map) || ($item eq $symb)) {
 8241:                     $noblock = 1;
 8242:                     last;
 8243:                 }
 8244:             }
 8245:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8246:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8247:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8248:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8249:                             push(@blockers,$block);
 8250:                         }
 8251:                     }
 8252:                 }
 8253:             }
 8254:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8255:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8256:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8257:                         push(@blockers,$block);
 8258:                     }
 8259:                 }
 8260:             }
 8261:         }
 8262:     }
 8263:     return if ($noblock);
 8264:     return @blockers;
 8265: }
 8266: }
 8267: 
 8268: # -------------------------------- Deversion and split uri into path an filename   
 8269: 
 8270: #
 8271: #   Removes the version from a URI and
 8272: #   splits it in to its filename and path to the filename.
 8273: #   Seems like File::Basename could have done this more clearly.
 8274: #   Parameters:
 8275: #      $uri   - input URI
 8276: #   Returns:
 8277: #     Two element list consisting of 
 8278: #     $pathname  - the URI up to and excluding the trailing /
 8279: #     $filename  - The part of the URI following the last /
 8280: #  NOTE:
 8281: #    Another realization of this is simply:
 8282: #    use File::Basename;
 8283: #    ...
 8284: #    $uri = shift;
 8285: #    $filename = basename($uri);
 8286: #    $path     = dirname($uri);
 8287: #    return ($filename, $path);
 8288: #
 8289: #     The implementation below is probably faster however.
 8290: #
 8291: sub split_uri_for_cond {
 8292:     my $uri=&deversion(&declutter(shift));
 8293:     my @uriparts=split(/\//,$uri);
 8294:     my $filename=pop(@uriparts);
 8295:     my $pathname=join('/',@uriparts);
 8296:     return ($pathname,$filename);
 8297: }
 8298: # --------------------------------------------------- Is a resource on the map?
 8299: 
 8300: sub is_on_map {
 8301:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8302:     #Trying to find the conditional for the file
 8303:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8304: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8305:     if ($match) {
 8306: 	return (1,$1);
 8307:     } else {
 8308: 	return (0,0);
 8309:     }
 8310: }
 8311: 
 8312: # --------------------------------------------------------- Get symb from alias
 8313: 
 8314: sub get_symb_from_alias {
 8315:     my $symb=shift;
 8316:     my ($map,$resid,$url)=&decode_symb($symb);
 8317: # Already is a symb
 8318:     if ($url) { return $symb; }
 8319: # Must be an alias
 8320:     my $aliassymb='';
 8321:     my %bighash;
 8322:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8323:                             &GDBM_READER(),0640)) {
 8324:         my $rid=$bighash{'mapalias_'.$symb};
 8325: 	if ($rid) {
 8326: 	    my ($mapid,$resid)=split(/\./,$rid);
 8327: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8328: 				    $resid,$bighash{'src_'.$rid});
 8329: 	}
 8330:         untie %bighash;
 8331:     }
 8332:     return $aliassymb;
 8333: }
 8334: 
 8335: # ----------------------------------------------------------------- Define Role
 8336: 
 8337: sub definerole {
 8338:   if (allowed('mcr','/')) {
 8339:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8340:     foreach my $role (split(':',$sysrole)) {
 8341: 	my ($crole,$cqual)=split(/\&/,$role);
 8342:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8343:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8344: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8345:                return "refused:s:$crole&$cqual"; 
 8346:             }
 8347:         }
 8348:     }
 8349:     foreach my $role (split(':',$domrole)) {
 8350: 	my ($crole,$cqual)=split(/\&/,$role);
 8351:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8352:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8353: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8354:                return "refused:d:$crole&$cqual"; 
 8355:             }
 8356:         }
 8357:     }
 8358:     foreach my $role (split(':',$courole)) {
 8359: 	my ($crole,$cqual)=split(/\&/,$role);
 8360:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8361:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8362: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8363:                return "refused:c:$crole&$cqual"; 
 8364:             }
 8365:         }
 8366:     }
 8367:     my $uhome;
 8368:     if (($uname ne '') && ($udom ne '')) {
 8369:         $uhome = &homeserver($uname,$udom);
 8370:         return $uhome if ($uhome eq 'no_host');
 8371:     } else {
 8372:         $uname = $env{'user.name'};
 8373:         $udom = $env{'user.domain'};
 8374:         $uhome = $env{'user.home'};
 8375:     }
 8376:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8377:                 "$udom:$uname:rolesdef_$rolename=".
 8378:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8379:     return reply($command,$uhome);
 8380:   } else {
 8381:     return 'refused';
 8382:   }
 8383: }
 8384: 
 8385: # ---------------- Make a metadata query against the network of library servers
 8386: 
 8387: sub metadata_query {
 8388:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8389:     my %rhash;
 8390:     my %libserv = &all_library();
 8391:     my @server_list = (defined($server_array) ? @$server_array
 8392:                                               : keys(%libserv) );
 8393:     for my $server (@server_list) {
 8394:         my $domains = ''; 
 8395:         if (ref($domains_hash) eq 'HASH') {
 8396:             $domains = $domains_hash->{$server}; 
 8397:         }
 8398: 	unless ($custom or $customshow) {
 8399: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8400: 	    $rhash{$server}=$reply;
 8401: 	}
 8402: 	else {
 8403: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8404: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8405: 			     $server);
 8406: 	    $rhash{$server}=$reply;
 8407: 	}
 8408:     }
 8409:     return \%rhash;
 8410: }
 8411: 
 8412: # ----------------------------------------- Send log queries and wait for reply
 8413: 
 8414: sub log_query {
 8415:     my ($uname,$udom,$query,%filters)=@_;
 8416:     my $uhome=&homeserver($uname,$udom);
 8417:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8418:     my $uhost=&hostname($uhome);
 8419:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8420:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8421:                        $uhome);
 8422:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8423:     return get_query_reply($queryid);
 8424: }
 8425: 
 8426: # -------------------------- Update MySQL table for portfolio file
 8427: 
 8428: sub update_portfolio_table {
 8429:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8430:     if ($group ne '') {
 8431:         $file_name =~s /^\Q$group\E//;
 8432:     }
 8433:     my $homeserver = &homeserver($uname,$udom);
 8434:     my $queryid=
 8435:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8436:                ':'.&escape($file_name).':'.$action,$homeserver);
 8437:     my $reply = &get_query_reply($queryid);
 8438:     return $reply;
 8439: }
 8440: 
 8441: # -------------------------- Update MySQL allusers table
 8442: 
 8443: sub update_allusers_table {
 8444:     my ($uname,$udom,$names) = @_;
 8445:     my $homeserver = &homeserver($uname,$udom);
 8446:     my $queryid=
 8447:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8448:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8449:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8450:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8451:                'generation='.&escape($names->{'generation'}).'%%'.
 8452:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8453:                'id='.&escape($names->{'id'}),$homeserver);
 8454:     return;
 8455: }
 8456: 
 8457: # ------- Request retrieval of institutional classlists for course(s)
 8458: 
 8459: sub fetch_enrollment_query {
 8460:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8461:     my ($homeserver,$sleep,$loopmax);
 8462:     my $maxtries = 1;
 8463:     if ($context eq 'automated') {
 8464:         $homeserver = $perlvar{'lonHostID'};
 8465:         $sleep = 2;
 8466:         $loopmax = 100;
 8467:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8468:     } else {
 8469:         $homeserver = &homeserver($cnum,$dom);
 8470:     }
 8471:     my $host=&hostname($homeserver);
 8472:     my $cmd = '';
 8473:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8474:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8475:     }
 8476:     $cmd =~ s/%%$//;
 8477:     $cmd = &escape($cmd);
 8478:     my $query = 'fetchenrollment';
 8479:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8480:     unless ($queryid=~/^\Q$host\E\_/) { 
 8481:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8482:         return 'error: '.$queryid;
 8483:     }
 8484:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8485:     my $tries = 1;
 8486:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8487:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8488:         $tries ++;
 8489:     }
 8490:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8491:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8492:     } else {
 8493:         my @responses = split(/:/,$reply);
 8494:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8495:             foreach my $line (@responses) {
 8496:                 my ($key,$value) = split(/=/,$line,2);
 8497:                 $$replyref{$key} = $value;
 8498:             }
 8499:         } else {
 8500:             my $pathname = LONCAPA::tempdir();
 8501:             foreach my $line (@responses) {
 8502:                 my ($key,$value) = split(/=/,$line);
 8503:                 $$replyref{$key} = $value;
 8504:                 if ($value > 0) {
 8505:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8506:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8507:                         my $destname = $pathname.'/'.$filename;
 8508:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8509:                         if ($xml_classlist =~ /^error/) {
 8510:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8511:                         } else {
 8512:                             if ( open(FILE,">",$destname) ) {
 8513:                                 print FILE &unescape($xml_classlist);
 8514:                                 close(FILE);
 8515:                             } else {
 8516:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8517:                             }
 8518:                         }
 8519:                     }
 8520:                 }
 8521:             }
 8522:         }
 8523:         return 'ok';
 8524:     }
 8525:     return 'error';
 8526: }
 8527: 
 8528: sub get_query_reply {
 8529:     my ($queryid,$sleep,$loopmax) = @_;;
 8530:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8531:         $sleep = 0.2;
 8532:     }
 8533:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8534:         $loopmax = 100;
 8535:     }
 8536:     my $replyfile=LONCAPA::tempdir().$queryid;
 8537:     my $reply='';
 8538:     for (1..$loopmax) {
 8539: 	sleep($sleep);
 8540:         if (-e $replyfile.'.end') {
 8541: 	    if (open(my $fh,"<",$replyfile)) {
 8542: 		$reply = join('',<$fh>);
 8543: 		close($fh);
 8544: 	   } else { return 'error: reply_file_error'; }
 8545:            return &unescape($reply);
 8546: 	}
 8547:     }
 8548:     return 'timeout:'.$queryid;
 8549: }
 8550: 
 8551: sub courselog_query {
 8552: #
 8553: # possible filters:
 8554: # url: url or symb
 8555: # username
 8556: # domain
 8557: # action: view, submit, grade
 8558: # start: timestamp
 8559: # end: timestamp
 8560: #
 8561:     my (%filters)=@_;
 8562:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8563:     if ($filters{'url'}) {
 8564: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8565:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8566:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8567:     }
 8568:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8569:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8570:     return &log_query($cname,$cdom,'courselog',%filters);
 8571: }
 8572: 
 8573: sub userlog_query {
 8574: #
 8575: # possible filters:
 8576: # action: log check role
 8577: # start: timestamp
 8578: # end: timestamp
 8579: #
 8580:     my ($uname,$udom,%filters)=@_;
 8581:     return &log_query($uname,$udom,'userlog',%filters);
 8582: }
 8583: 
 8584: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8585: 
 8586: sub auto_run {
 8587:     my ($cnum,$cdom) = @_;
 8588:     my $response = 0;
 8589:     my $settings;
 8590:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8591:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8592:         $settings = $domconfig{'autoenroll'};
 8593:         if ($settings->{'run'} eq '1') {
 8594:             $response = 1;
 8595:         }
 8596:     } else {
 8597:         my $homeserver;
 8598:         if (&is_course($cdom,$cnum)) {
 8599:             $homeserver = &homeserver($cnum,$cdom);
 8600:         } else {
 8601:             $homeserver = &domain($cdom,'primary');
 8602:         }
 8603:         if ($homeserver ne 'no_host') {
 8604:             $response = &reply('autorun:'.$cdom,$homeserver);
 8605:         }
 8606:     }
 8607:     return $response;
 8608: }
 8609: 
 8610: sub auto_get_sections {
 8611:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8612:     my $homeserver;
 8613:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8614:         $homeserver = &homeserver($cnum,$cdom);
 8615:     }
 8616:     if (!defined($homeserver)) { 
 8617:         if ($cdom =~ /^$match_domain$/) {
 8618:             $homeserver = &domain($cdom,'primary');
 8619:         }
 8620:     }
 8621:     my @secs;
 8622:     if (defined($homeserver)) {
 8623:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8624:         unless ($response eq 'refused') {
 8625:             @secs = split(/:/,$response);
 8626:         }
 8627:     }
 8628:     return @secs;
 8629: }
 8630: 
 8631: sub auto_new_course {
 8632:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8633:     my $homeserver = &homeserver($cnum,$cdom);
 8634:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8635:     return $response;
 8636: }
 8637: 
 8638: sub auto_validate_courseID {
 8639:     my ($cnum,$cdom,$inst_course_id) = @_;
 8640:     my $homeserver = &homeserver($cnum,$cdom);
 8641:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8642:     return $response;
 8643: }
 8644: 
 8645: sub auto_validate_instcode {
 8646:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8647:     my ($homeserver,$response);
 8648:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8649:         $homeserver = &homeserver($cnum,$cdom);
 8650:     }
 8651:     if (!defined($homeserver)) {
 8652:         if ($cdom =~ /^$match_domain$/) {
 8653:             $homeserver = &domain($cdom,'primary');
 8654:         }
 8655:     }
 8656:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8657:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8658:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8659:     return ($outcome,$description,$defaultcredits);
 8660: }
 8661: 
 8662: sub auto_create_password {
 8663:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8664:     my ($homeserver,$response);
 8665:     my $create_passwd = 0;
 8666:     my $authchk = '';
 8667:     if ($udom =~ /^$match_domain$/) {
 8668:         $homeserver = &domain($udom,'primary');
 8669:     }
 8670:     if ($homeserver eq '') {
 8671:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8672:             $homeserver = &homeserver($cnum,$cdom);
 8673:         }
 8674:     }
 8675:     if ($homeserver eq '') {
 8676:         $authchk = 'nodomain';
 8677:     } else {
 8678:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8679:         if ($response eq 'refused') {
 8680:             $authchk = 'refused';
 8681:         } else {
 8682:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8683:         }
 8684:     }
 8685:     return ($authparam,$create_passwd,$authchk);
 8686: }
 8687: 
 8688: sub auto_photo_permission {
 8689:     my ($cnum,$cdom,$students) = @_;
 8690:     my $homeserver = &homeserver($cnum,$cdom);
 8691:     my ($outcome,$perm_reqd,$conditions) = 
 8692: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8693:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8694: 	return (undef,undef);
 8695:     }
 8696:     return ($outcome,$perm_reqd,$conditions);
 8697: }
 8698: 
 8699: sub auto_checkphotos {
 8700:     my ($uname,$udom,$pid) = @_;
 8701:     my $homeserver = &homeserver($uname,$udom);
 8702:     my ($result,$resulttype);
 8703:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8704: 				   &escape($uname).':'.&escape($pid),
 8705: 				   $homeserver));
 8706:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8707: 	return (undef,undef);
 8708:     }
 8709:     if ($outcome) {
 8710:         ($result,$resulttype) = split(/:/,$outcome);
 8711:     } 
 8712:     return ($result,$resulttype);
 8713: }
 8714: 
 8715: sub auto_photochoice {
 8716:     my ($cnum,$cdom) = @_;
 8717:     my $homeserver = &homeserver($cnum,$cdom);
 8718:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8719: 						       &escape($cdom),
 8720: 						       $homeserver)));
 8721:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8722: 	return (undef,undef);
 8723:     }
 8724:     return ($update,$comment);
 8725: }
 8726: 
 8727: sub auto_photoupdate {
 8728:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8729:     my $homeserver = &homeserver($cnum,$dom);
 8730:     my $host=&hostname($homeserver);
 8731:     my $cmd = '';
 8732:     my $maxtries = 1;
 8733:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8734:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8735:     }
 8736:     $cmd =~ s/%%$//;
 8737:     $cmd = &escape($cmd);
 8738:     my $query = 'institutionalphotos';
 8739:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8740:     unless ($queryid=~/^\Q$host\E\_/) {
 8741:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8742:         return 'error: '.$queryid;
 8743:     }
 8744:     my $reply = &get_query_reply($queryid);
 8745:     my $tries = 1;
 8746:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8747:         $reply = &get_query_reply($queryid);
 8748:         $tries ++;
 8749:     }
 8750:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8751:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8752:     } else {
 8753:         my @responses = split(/:/,$reply);
 8754:         my $outcome = shift(@responses); 
 8755:         foreach my $item (@responses) {
 8756:             my ($key,$value) = split(/=/,$item);
 8757:             $$photo{$key} = $value;
 8758:         }
 8759:         return $outcome;
 8760:     }
 8761:     return 'error';
 8762: }
 8763: 
 8764: sub auto_instcode_format {
 8765:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8766: 	$cat_order) = @_;
 8767:     my $courses = '';
 8768:     my @homeservers;
 8769:     if ($caller eq 'global') {
 8770: 	my %servers = &get_servers($codedom,'library');
 8771: 	foreach my $tryserver (keys(%servers)) {
 8772: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8773: 		push(@homeservers,$tryserver);
 8774: 	    }
 8775:         }
 8776:     } elsif ($caller eq 'requests') {
 8777:         if ($codedom =~ /^$match_domain$/) {
 8778:             my $chome = &domain($codedom,'primary');
 8779:             unless ($chome eq 'no_host') {
 8780:                 push(@homeservers,$chome);
 8781:             }
 8782:         }
 8783:     } else {
 8784:         push(@homeservers,&homeserver($caller,$codedom));
 8785:     }
 8786:     foreach my $code (keys(%{$instcodes})) {
 8787:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8788:     }
 8789:     chop($courses);
 8790:     my $ok_response = 0;
 8791:     my $response;
 8792:     while (@homeservers > 0 && $ok_response == 0) {
 8793:         my $server = shift(@homeservers); 
 8794:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8795:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8796:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8797: 		split(/:/,$response);
 8798:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8799:             push(@{$codetitles},&str2array($codetitles_str));
 8800:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8801:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8802:             $ok_response = 1;
 8803:         }
 8804:     }
 8805:     if ($ok_response) {
 8806:         return 'ok';
 8807:     } else {
 8808:         return $response;
 8809:     }
 8810: }
 8811: 
 8812: sub auto_instcode_defaults {
 8813:     my ($domain,$returnhash,$code_order) = @_;
 8814:     my @homeservers;
 8815: 
 8816:     my %servers = &get_servers($domain,'library');
 8817:     foreach my $tryserver (keys(%servers)) {
 8818: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8819: 	    push(@homeservers,$tryserver);
 8820: 	}
 8821:     }
 8822: 
 8823:     my $response;
 8824:     foreach my $server (@homeservers) {
 8825:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8826:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8827: 	
 8828: 	foreach my $pair (split(/\&/,$response)) {
 8829: 	    my ($name,$value)=split(/\=/,$pair);
 8830: 	    if ($name eq 'code_order') {
 8831: 		@{$code_order} = split(/\&/,&unescape($value));
 8832: 	    } else {
 8833: 		$returnhash->{&unescape($name)}=&unescape($value);
 8834: 	    }
 8835: 	}
 8836: 	return 'ok';
 8837:     }
 8838: 
 8839:     return $response;
 8840: }
 8841: 
 8842: sub auto_possible_instcodes {
 8843:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8844:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8845:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8846:         return;
 8847:     }
 8848:     my (@homeservers,$uhome);
 8849:     if (defined(&domain($domain,'primary'))) {
 8850:         $uhome=&domain($domain,'primary');
 8851:         push(@homeservers,&domain($domain,'primary'));
 8852:     } else {
 8853:         my %servers = &get_servers($domain,'library');
 8854:         foreach my $tryserver (keys(%servers)) {
 8855:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8856:                 push(@homeservers,$tryserver);
 8857:             }
 8858:         }
 8859:     }
 8860:     my $response;
 8861:     foreach my $server (@homeservers) {
 8862:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8863:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8864:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8865:             split(':',$response);
 8866:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8867:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8868:         foreach my $item (split('&',$cat_title)) {   
 8869:             my ($name,$value)=split('=',$item);
 8870:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8871:         }
 8872:         foreach my $item (split('&',$cat_order)) {
 8873:             my ($name,$value)=split('=',$item);
 8874:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8875:         }
 8876:         return 'ok';
 8877:     }
 8878:     return $response;
 8879: }
 8880: 
 8881: sub auto_courserequest_checks {
 8882:     my ($dom) = @_;
 8883:     my ($homeserver,%validations);
 8884:     if ($dom =~ /^$match_domain$/) {
 8885:         $homeserver = &domain($dom,'primary');
 8886:     }
 8887:     unless ($homeserver eq 'no_host') {
 8888:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8889:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8890:             my @items = split(/&/,$response);
 8891:             foreach my $item (@items) {
 8892:                 my ($key,$value) = split('=',$item);
 8893:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8894:             }
 8895:         }
 8896:     }
 8897:     return %validations; 
 8898: }
 8899: 
 8900: sub auto_courserequest_validation {
 8901:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8902:     my ($homeserver,$response);
 8903:     if ($dom =~ /^$match_domain$/) {
 8904:         $homeserver = &domain($dom,'primary');
 8905:     }
 8906:     unless ($homeserver eq 'no_host') {
 8907:         my $customdata;
 8908:         if (ref($custominfo) eq 'HASH') {
 8909:             $customdata = &freeze_escape($custominfo);
 8910:         }
 8911:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8912:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8913:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8914:                                     $customdata,$homeserver));
 8915:     }
 8916:     return $response;
 8917: }
 8918: 
 8919: sub auto_validate_class_sec {
 8920:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8921:     my $homeserver = &homeserver($cnum,$cdom);
 8922:     my $ownerlist;
 8923:     if (ref($owners) eq 'ARRAY') {
 8924:         $ownerlist = join(',',@{$owners});
 8925:     } else {
 8926:         $ownerlist = $owners;
 8927:     }
 8928:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8929:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8930:     return $response;
 8931: }
 8932: 
 8933: sub auto_validate_instclasses {
 8934:     my ($cdom,$cnum,$owners,$classesref) = @_;
 8935:     my ($homeserver,%validations);
 8936:     $homeserver = &homeserver($cnum,$cdom);
 8937:     unless ($homeserver eq 'no_host') {
 8938:         my $ownerlist;
 8939:         if (ref($owners) eq 'ARRAY') {
 8940:             $ownerlist = join(',',@{$owners});
 8941:         } else {
 8942:             $ownerlist = $owners;
 8943:         }
 8944:         if (ref($classesref) eq 'HASH') {
 8945:             my $classes = &freeze_escape($classesref);
 8946:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 8947:                                 ':'.$cdom.':'.$classes,$homeserver);
 8948:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8949:                 my @items = split(/&/,$response);
 8950:                 foreach my $item (@items) {
 8951:                     my ($key,$value) = split('=',$item);
 8952:                     $validations{&unescape($key)} = &thaw_unescape($value);
 8953:                 }
 8954:             }
 8955:         }
 8956:     }
 8957:     return %validations;
 8958: }
 8959: 
 8960: sub auto_crsreq_update {
 8961:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8962:         $code,$accessstart,$accessend,$inbound) = @_;
 8963:     my ($homeserver,%crsreqresponse);
 8964:     if ($cdom =~ /^$match_domain$/) {
 8965:         $homeserver = &domain($cdom,'primary');
 8966:     }
 8967:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8968:         my $info;
 8969:         if (ref($inbound) eq 'HASH') {
 8970:             $info = &freeze_escape($inbound);
 8971:         }
 8972:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8973:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8974:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8975:                             &escape($title).':'.&escape($code).':'.
 8976:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8977:                             $homeserver);
 8978:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8979:             my @items = split(/&/,$response);
 8980:             foreach my $item (@items) {
 8981:                 my ($key,$value) = split('=',$item);
 8982:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8983:             }
 8984:         }
 8985:     }
 8986:     return \%crsreqresponse;
 8987: }
 8988: 
 8989: sub auto_export_grades {
 8990:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 8991:     my ($homeserver,%exportresponse);
 8992:     if ($cdom =~ /^$match_domain$/) {
 8993:         $homeserver = &domain($cdom,'primary');
 8994:     }
 8995:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8996:         my $info;
 8997:         if (ref($inforef) eq 'HASH') {
 8998:             $info = &freeze_escape($inforef);
 8999:         }
 9000:         if (ref($gradesref) eq 'HASH') {
 9001:             my $grades = &freeze_escape($gradesref);
 9002:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9003:                                 $info.':'.$grades,$homeserver);
 9004:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9005:                 my @items = split(/&/,$response);
 9006:                 foreach my $item (@items) {
 9007:                     my ($key,$value) = split('=',$item);
 9008:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9009:                 }
 9010:             }
 9011:         }
 9012:     }
 9013:     return \%exportresponse;
 9014: }
 9015: 
 9016: sub check_instcode_cloning {
 9017:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9018:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9019:         return;
 9020:     }
 9021:     my $canclone;
 9022:     if (@{$code_order} > 0) {
 9023:         my $instcoderegexp ='^';
 9024:         my @clonecodes = split(/\&/,$cloner);
 9025:         foreach my $item (@{$code_order}) {
 9026:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9027:                 foreach my $pair (@clonecodes) {
 9028:                     my ($key,$val) = split(/\=/,$pair,2);
 9029:                     $val = &unescape($val);
 9030:                     if ($key eq $item) {
 9031:                         $instcoderegexp .= '('.$val.')';
 9032:                         last;
 9033:                     }
 9034:                 }
 9035:             } else {
 9036:                 $instcoderegexp .= $codedefaults->{$item};
 9037:             }
 9038:         }
 9039:         $instcoderegexp .= '$';
 9040:         my (@from,@to);
 9041:         eval {
 9042:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9043:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9044:         };
 9045:         if ((@from > 0) && (@to > 0)) {
 9046:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9047:             if (!@diffs) {
 9048:                 $canclone = 1;
 9049:             }
 9050:         }
 9051:     }
 9052:     return $canclone;
 9053: }
 9054: 
 9055: sub default_instcode_cloning {
 9056:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9057:     my (%codedefaults,@code_order,$canclone);
 9058:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9059:         %codedefaults = %{$codedefaultsref};
 9060:         @code_order = @{$codeorderref};
 9061:     } elsif ($clonedom) {
 9062:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9063:     }
 9064:     if (($domdefclone) && (@code_order)) {
 9065:         my @clonecodes = split(/\+/,$domdefclone);
 9066:         my $instcoderegexp ='^';
 9067:         foreach my $item (@code_order) {
 9068:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9069:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9070:             } else {
 9071:                 $instcoderegexp .= $codedefaults{$item};
 9072:             }
 9073:         }
 9074:         $instcoderegexp .= '$';
 9075:         my (@from,@to);
 9076:         eval {
 9077:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9078:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9079:         };
 9080:         if ((@from > 0) && (@to > 0)) {
 9081:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9082:             if (!@diffs) {
 9083:                 $canclone = 1;
 9084:             }
 9085:         }
 9086:     }
 9087:     return $canclone;
 9088: }
 9089: 
 9090: # ------------------------------------------------------- Course Group routines
 9091: 
 9092: sub get_coursegroups {
 9093:     my ($cdom,$cnum,$group,$namespace) = @_;
 9094:     return(&dump($namespace,$cdom,$cnum,$group));
 9095: }
 9096: 
 9097: sub modify_coursegroup {
 9098:     my ($cdom,$cnum,$groupsettings) = @_;
 9099:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9100: }
 9101: 
 9102: sub toggle_coursegroup_status {
 9103:     my ($cdom,$cnum,$group,$action) = @_;
 9104:     my ($from_namespace,$to_namespace);
 9105:     if ($action eq 'delete') {
 9106:         $from_namespace = 'coursegroups';
 9107:         $to_namespace = 'deleted_groups';
 9108:     } else {
 9109:         $from_namespace = 'deleted_groups';
 9110:         $to_namespace = 'coursegroups';
 9111:     }
 9112:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9113:     if (my $tmp = &error(%curr_group)) {
 9114:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9115:         return ('read error',$tmp);
 9116:     } else {
 9117:         my %savedsettings = %curr_group; 
 9118:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9119:         my $deloutcome;
 9120:         if ($result eq 'ok') {
 9121:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9122:         } else {
 9123:             return ('write error',$result);
 9124:         }
 9125:         if ($deloutcome eq 'ok') {
 9126:             return 'ok';
 9127:         } else {
 9128:             return ('delete error',$deloutcome);
 9129:         }
 9130:     }
 9131: }
 9132: 
 9133: sub modify_group_roles {
 9134:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9135:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9136:     my $role = 'gr/'.&escape($userprivs);
 9137:     my ($uname,$udom) = split(/:/,$user);
 9138:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9139:     if ($result eq 'ok') {
 9140:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9141:     }
 9142:     return $result;
 9143: }
 9144: 
 9145: sub modify_coursegroup_membership {
 9146:     my ($cdom,$cnum,$membership) = @_;
 9147:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9148:     return $result;
 9149: }
 9150: 
 9151: sub get_active_groups {
 9152:     my ($udom,$uname,$cdom,$cnum) = @_;
 9153:     my $now = time;
 9154:     my %groups = ();
 9155:     foreach my $key (keys(%env)) {
 9156:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9157:             my ($start,$end) = split(/\./,$env{$key});
 9158:             if (($end!=0) && ($end<$now)) { next; }
 9159:             if (($start!=0) && ($start>$now)) { next; }
 9160:             if ($1 eq $cdom && $2 eq $cnum) {
 9161:                 $groups{$3} = $env{$key} ;
 9162:             }
 9163:         }
 9164:     }
 9165:     return %groups;
 9166: }
 9167: 
 9168: sub get_group_membership {
 9169:     my ($cdom,$cnum,$group) = @_;
 9170:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9171: }
 9172: 
 9173: sub get_users_groups {
 9174:     my ($udom,$uname,$courseid) = @_;
 9175:     my @usersgroups;
 9176:     my $cachetime=1800;
 9177: 
 9178:     my $hashid="$udom:$uname:$courseid";
 9179:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9180:     if (defined($cached)) {
 9181:         @usersgroups = split(/:/,$grouplist);
 9182:     } else {  
 9183:         $grouplist = '';
 9184:         my $courseurl = &courseid_to_courseurl($courseid);
 9185:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9186:         my $access_end = $env{'course.'.$courseid.
 9187:                               '.default_enrollment_end_date'};
 9188:         my $now = time;
 9189:         foreach my $key (keys(%roleshash)) {
 9190:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9191:                 my $group = $1;
 9192:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9193:                     my $start = $2;
 9194:                     my $end = $1;
 9195:                     if ($start == -1) { next; } # deleted from group
 9196:                     if (($start!=0) && ($start>$now)) { next; }
 9197:                     if (($end!=0) && ($end<$now)) {
 9198:                         if ($access_end && $access_end < $now) {
 9199:                             if ($access_end - $end < 86400) {
 9200:                                 push(@usersgroups,$group);
 9201:                             }
 9202:                         }
 9203:                         next;
 9204:                     }
 9205:                     push(@usersgroups,$group);
 9206:                 }
 9207:             }
 9208:         }
 9209:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9210:         $grouplist = join(':',@usersgroups);
 9211:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9212:     }
 9213:     return @usersgroups;
 9214: }
 9215: 
 9216: sub devalidate_getgroups_cache {
 9217:     my ($udom,$uname,$cdom,$cnum)=@_;
 9218:     my $courseid = $cdom.'_'.$cnum;
 9219: 
 9220:     my $hashid="$udom:$uname:$courseid";
 9221:     &devalidate_cache_new('getgroups',$hashid);
 9222: }
 9223: 
 9224: # ------------------------------------------------------------------ Plain Text
 9225: 
 9226: sub plaintext {
 9227:     my ($short,$type,$cid,$forcedefault) = @_;
 9228:     if ($short =~ m{^cr/}) {
 9229: 	return (split('/',$short))[-1];
 9230:     }
 9231:     if (!defined($cid)) {
 9232:         $cid = $env{'request.course.id'};
 9233:     }
 9234:     my %rolenames = (
 9235:                       Course    => 'std',
 9236:                       Community => 'alt1',
 9237:                       Placement => 'std',
 9238:                     );
 9239:     if ($cid ne '') {
 9240:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9241:             unless ($forcedefault) {
 9242:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9243:                 &Apache::lonlocal::mt_escape(\$roletext);
 9244:                 return &Apache::lonlocal::mt($roletext);
 9245:             }
 9246:         }
 9247:     }
 9248:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9249:         (defined($rolenames{$type})) && 
 9250:         (defined($prp{$short}{$rolenames{$type}}))) {
 9251:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9252:     } elsif ($cid ne '') {
 9253:         my $crstype = $env{'course.'.$cid.'.type'};
 9254:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9255:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9256:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9257:         }
 9258:     }
 9259:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9260: }
 9261: 
 9262: # ----------------------------------------------------------------- Assign Role
 9263: 
 9264: sub assignrole {
 9265:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9266:         $context)=@_;
 9267:     my $mrole;
 9268:     if ($role =~ /^cr\//) {
 9269:         my $cwosec=$url;
 9270:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9271: 	unless (&allowed('ccr',$cwosec)) {
 9272:            my $refused = 1;
 9273:            if ($context eq 'requestcourses') {
 9274:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9275:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9276:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9277:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9278:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9279:                            if ($crsenv{'internal.courseowner'} eq
 9280:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9281:                                $refused = '';
 9282:                            }
 9283:                        }
 9284:                    }
 9285:                }
 9286:            }
 9287:            if ($refused) {
 9288:                &logthis('Refused custom assignrole: '.
 9289:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9290:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9291:                return 'refused';
 9292:            }
 9293:         }
 9294:         $mrole='cr';
 9295:     } elsif ($role =~ /^gr\//) {
 9296:         my $cwogrp=$url;
 9297:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9298:         unless (&allowed('mdg',$cwogrp)) {
 9299:             &logthis('Refused group assignrole: '.
 9300:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9301:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9302:             return 'refused';
 9303:         }
 9304:         $mrole='gr';
 9305:     } else {
 9306:         my $cwosec=$url;
 9307:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9308:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9309:             my $refused;
 9310:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9311:                 if (!(&allowed('c'.$role,$url))) {
 9312:                     $refused = 1;
 9313:                 }
 9314:             } else {
 9315:                 $refused = 1;
 9316:             }
 9317:             if ($refused) {
 9318:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9319:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9320:                     my %crsenv;
 9321:                     if ($role eq 'cc' || $role eq 'co') {
 9322:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9323:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9324:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9325:                                 if ($crsenv{'internal.courseowner'} eq 
 9326:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9327:                                     $refused = '';
 9328:                                 }
 9329:                             }
 9330:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9331:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9332:                                 if ($crsenv{'internal.courseowner'} eq 
 9333:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9334:                                     $refused = '';
 9335:                                 }
 9336:                             }
 9337:                         }
 9338:                     }
 9339:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9340:                     if ($role eq 'st') {
 9341:                         $refused = '';
 9342:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9343:                         $refused = '';
 9344:                     }
 9345:                 } elsif ($context eq 'requestcourses') {
 9346:                     my @possroles = ('st','ta','ep','in','cc','co');
 9347:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9348:                         my $wrongcc;
 9349:                         if ($cnum =~ /^$match_community$/) {
 9350:                             $wrongcc = 1 if ($role eq 'cc');
 9351:                         } else {
 9352:                             $wrongcc = 1 if ($role eq 'co');
 9353:                         }
 9354:                         unless ($wrongcc) {
 9355:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9356:                             if ($crsenv{'internal.courseowner'} eq 
 9357:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9358:                                 $refused = '';
 9359:                             }
 9360:                         }
 9361:                     }
 9362:                 } elsif ($context eq 'requestauthor') {
 9363:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9364:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9365:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9366:                             $refused = '';
 9367:                         } else {
 9368:                             my %domdefaults = &get_domain_defaults($udom);
 9369:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9370:                                 my $checkbystatus;
 9371:                                 if ($env{'user.adv'}) { 
 9372:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9373:                                     if ($disposition eq 'automatic') {
 9374:                                         $refused = '';
 9375:                                     } elsif ($disposition eq '') {
 9376:                                         $checkbystatus = 1;
 9377:                                     } 
 9378:                                 } else {
 9379:                                     $checkbystatus = 1;
 9380:                                 }
 9381:                                 if ($checkbystatus) {
 9382:                                     if ($env{'environment.inststatus'}) {
 9383:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9384:                                         foreach my $type (@inststatuses) {
 9385:                                             if (($type ne '') &&
 9386:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9387:                                                 $refused = '';
 9388:                                             }
 9389:                                         }
 9390:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9391:                                         $refused = '';
 9392:                                     }
 9393:                                 }
 9394:                             }
 9395:                         }
 9396:                     }
 9397:                 }
 9398:                 if ($refused) {
 9399:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9400:                              ' '.$role.' '.$end.' '.$start.' by '.
 9401: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9402:                     return 'refused';
 9403:                 }
 9404:             }
 9405:         } elsif ($role eq 'au') {
 9406:             if ($url ne '/'.$udom.'/') {
 9407:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9408:                          ' to assign author role for '.$uname.':'.$udom.
 9409:                          ' in domain: '.$url.' refused (wrong domain).');
 9410:                 return 'refused';
 9411:             }
 9412:         }
 9413:         $mrole=$role;
 9414:     }
 9415:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9416:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9417:     if ($end) { $command.='_'.$end; }
 9418:     if ($start) {
 9419: 	if ($end) { 
 9420:            $command.='_'.$start; 
 9421:         } else {
 9422:            $command.='_0_'.$start;
 9423:         }
 9424:     }
 9425:     my $origstart = $start;
 9426:     my $origend = $end;
 9427:     my $delflag;
 9428: # actually delete
 9429:     if ($deleteflag) {
 9430: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9431: # modify command to delete the role
 9432:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9433:                 "$udom:$uname:$url".'_'."$mrole";
 9434: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9435: # set start and finish to negative values for userrolelog
 9436:            $start=-1;
 9437:            $end=-1;
 9438:            $delflag = 1;
 9439:         }
 9440:     }
 9441: # send command
 9442:     my $answer=&reply($command,&homeserver($uname,$udom));
 9443: # log new user role if status is ok
 9444:     if ($answer eq 'ok') {
 9445: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9446:         if (($role eq 'cc') || ($role eq 'in') ||
 9447:             ($role eq 'ep') || ($role eq 'ad') ||
 9448:             ($role eq 'ta') || ($role eq 'st') ||
 9449:             ($role=~/^cr/) || ($role eq 'gr') ||
 9450:             ($role eq 'co')) {
 9451: # for course roles, perform group memberships changes triggered by role change.
 9452:             unless ($role =~ /^gr/) {
 9453:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9454:                                                  $origstart,$selfenroll,$context);
 9455:             }
 9456:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9457:                            $selfenroll,$context);
 9458:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9459:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9460:                  ($role eq 'da')) {
 9461:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9462:                            $context);
 9463:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9464:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9465:                              $context); 
 9466:         }
 9467:         if ($role eq 'cc') {
 9468:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9469:         }
 9470:     }
 9471:     return $answer;
 9472: }
 9473: 
 9474: sub autoupdate_coowners {
 9475:     my ($url,$end,$start,$uname,$udom) = @_;
 9476:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9477:     if (($cdom ne '') && ($cnum ne '')) {
 9478:         my $now = time;
 9479:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9480:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9481:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9482:             my $instcode = $coursehash{'internal.coursecode'};
 9483:             if ($instcode ne '') {
 9484:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9485:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9486:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9487:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9488:                         if ($result eq 'valid') {
 9489:                             if ($coursehash{'internal.co-owners'}) {
 9490:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9491:                                     push(@newcoowners,$coowner);
 9492:                                 }
 9493:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9494:                                     push(@newcoowners,$uname.':'.$udom);
 9495:                                 }
 9496:                                 @newcoowners = sort(@newcoowners);
 9497:                             } else {
 9498:                                 push(@newcoowners,$uname.':'.$udom);
 9499:                             }
 9500:                         } else {
 9501:                             if ($coursehash{'internal.co-owners'}) {
 9502:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9503:                                     unless ($coowner eq $uname.':'.$udom) {
 9504:                                         push(@newcoowners,$coowner);
 9505:                                     }
 9506:                                 }
 9507:                                 unless (@newcoowners > 0) {
 9508:                                     $delcoowners = 1;
 9509:                                     $coowners = '';
 9510:                                 }
 9511:                             }
 9512:                         }
 9513:                         if (@newcoowners || $delcoowners) {
 9514:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9515:                                             $delcoowners,@newcoowners);
 9516:                         }
 9517:                     }
 9518:                 }
 9519:             }
 9520:         }
 9521:     }
 9522: }
 9523: 
 9524: sub store_coowners {
 9525:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9526:     my $cid = $cdom.'_'.$cnum;
 9527:     my ($coowners,$delresult,$putresult);
 9528:     if (@newcoowners) {
 9529:         $coowners = join(',',@newcoowners);
 9530:         my %coownershash = (
 9531:                             'internal.co-owners' => $coowners,
 9532:                            );
 9533:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9534:         if ($putresult eq 'ok') {
 9535:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9536:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9537:             }
 9538:         }
 9539:     }
 9540:     if ($delcoowners) {
 9541:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9542:         if ($delresult eq 'ok') {
 9543:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9544:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9545:             }
 9546:         }
 9547:     }
 9548:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9549:         my %crsinfo =
 9550:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9551:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9552:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9553:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9554:         }
 9555:     }
 9556: }
 9557: 
 9558: # -------------------------------------------------- Modify user authentication
 9559: # Overrides without validation
 9560: 
 9561: sub modifyuserauth {
 9562:     my ($udom,$uname,$umode,$upass)=@_;
 9563:     my $uhome=&homeserver($uname,$udom);
 9564:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9565:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9566:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9567:              ' in domain '.$env{'request.role.domain'});  
 9568:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9569: 		     &escape($upass),$uhome);
 9570:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9571:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9572:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9573:     &log($udom,,$uname,$uhome,
 9574:         'Authentication changed by '.$env{'user.domain'}.', '.
 9575:                                      $env{'user.name'}.', '.$umode.
 9576:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9577:     unless ($reply eq 'ok') {
 9578:         &logthis('Authentication mode error: '.$reply);
 9579: 	return 'error: '.$reply;
 9580:     }   
 9581:     return 'ok';
 9582: }
 9583: 
 9584: # --------------------------------------------------------------- Modify a user
 9585: 
 9586: sub modifyuser {
 9587:     my ($udom,    $uname, $uid,
 9588:         $umode,   $upass, $first,
 9589:         $middle,  $last,  $gene,
 9590:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9591:     $udom= &LONCAPA::clean_domain($udom);
 9592:     $uname=&LONCAPA::clean_username($uname);
 9593:     my $showcandelete = 'none';
 9594:     if (ref($candelete) eq 'ARRAY') {
 9595:         if (@{$candelete} > 0) {
 9596:             $showcandelete = join(', ',@{$candelete});
 9597:         }
 9598:     }
 9599:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9600:              $umode.', '.$first.', '.$middle.', '.
 9601: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9602:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9603:                                      ' desiredhome not specified'). 
 9604:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9605:              ' in domain '.$env{'request.role.domain'});
 9606:     my $uhome=&homeserver($uname,$udom,'true');
 9607:     my $newuser;
 9608:     if ($uhome eq 'no_host') {
 9609:         $newuser = 1;
 9610:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
 9611:                 ($umode eq 'lti')) {
 9612:             return 'error: more information needed to create new user';
 9613:         }
 9614:     }
 9615: # ----------------------------------------------------------------- Create User
 9616:     if (($uhome eq 'no_host') && 
 9617: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
 9618:         my $unhome='';
 9619:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9620:             $unhome = $desiredhome;
 9621: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9622: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9623:         } else { # load balancing routine for determining $unhome
 9624:             my $loadm=10000000;
 9625: 	    my %servers = &get_servers($udom,'library');
 9626: 	    foreach my $tryserver (keys(%servers)) {
 9627: 		my $answer=reply('load',$tryserver);
 9628: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9629: 		    $loadm=$answer;
 9630: 		    $unhome=$tryserver;
 9631: 		}
 9632: 	    }
 9633:         }
 9634:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9635: 	    return 'error: unable to find a home server for '.$uname.
 9636:                    ' in domain '.$udom;
 9637:         }
 9638:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9639:                          &escape($upass),$unhome);
 9640: 	unless ($reply eq 'ok') {
 9641:             return 'error: '.$reply;
 9642:         }   
 9643:         $uhome=&homeserver($uname,$udom,'true');
 9644:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9645: 	    return 'error: unable verify users home machine.';
 9646:         }
 9647:     }   # End of creation of new user
 9648: # ---------------------------------------------------------------------- Add ID
 9649:     if ($uid) {
 9650:        $uid=~tr/A-Z/a-z/;
 9651:        my %uidhash=&idrget($udom,$uname);
 9652:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9653:          && (!$forceid)) {
 9654: 	  unless ($uid eq $uidhash{$uname}) {
 9655: 	      return 'error: user id "'.$uid.'" does not match '.
 9656:                   'current user id "'.$uidhash{$uname}.'".';
 9657:           }
 9658:        } else {
 9659: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9660:        }
 9661:     }
 9662: # -------------------------------------------------------------- Add names, etc
 9663:     my @tmp=&get('environment',
 9664: 		   ['firstname','middlename','lastname','generation','id',
 9665:                     'permanentemail','inststatus'],
 9666: 		   $udom,$uname);
 9667:     my (%names,%oldnames);
 9668:     if ($tmp[0] =~ m/^error:.*/) { 
 9669:         %names=(); 
 9670:     } else {
 9671:         %names = @tmp;
 9672:         %oldnames = %names;
 9673:     }
 9674: #
 9675: # If name, email and/or uid are blank (e.g., because an uploaded file
 9676: # of users did not contain them), do not overwrite existing values
 9677: # unless field is in $candelete array ref.  
 9678: #
 9679: 
 9680:     my @fields = ('firstname','middlename','lastname','generation',
 9681:                   'permanentemail','id');
 9682:     my %newvalues;
 9683:     if (ref($candelete) eq 'ARRAY') {
 9684:         foreach my $field (@fields) {
 9685:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9686:                 if ($field eq 'firstname') {
 9687:                     $names{$field} = $first;
 9688:                 } elsif ($field eq 'middlename') {
 9689:                     $names{$field} = $middle;
 9690:                 } elsif ($field eq 'lastname') {
 9691:                     $names{$field} = $last;
 9692:                 } elsif ($field eq 'generation') { 
 9693:                     $names{$field} = $gene;
 9694:                 } elsif ($field eq 'permanentemail') {
 9695:                     $names{$field} = $email;
 9696:                 } elsif ($field eq 'id') {
 9697:                     $names{$field}  = $uid;
 9698:                 }
 9699:             }
 9700:         }
 9701:     }
 9702:     if ($first)  { $names{'firstname'}  = $first; }
 9703:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9704:     if ($last)   { $names{'lastname'}   = $last; }
 9705:     if (defined($gene))   { $names{'generation'} = $gene; }
 9706:     if ($email) {
 9707:        $email=~s/[^\w\@\.\-\,]//gs;
 9708:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9709:     }
 9710:     if ($uid) { $names{'id'}  = $uid; }
 9711:     if (defined($inststatus)) {
 9712:         $names{'inststatus'} = '';
 9713:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9714:         if (ref($usertypes) eq 'HASH') {
 9715:             my @okstatuses; 
 9716:             foreach my $item (split(/:/,$inststatus)) {
 9717:                 if (defined($usertypes->{$item})) {
 9718:                     push(@okstatuses,$item);  
 9719:                 }
 9720:             }
 9721:             if (@okstatuses) {
 9722:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9723:             }
 9724:         }
 9725:     }
 9726:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9727:                  $umode.', '.$first.', '.$middle.', '.
 9728:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9729:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9730:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9731:     } else {
 9732:         $logmsg .= ' during self creation';
 9733:     }
 9734:     my $changed;
 9735:     if ($newuser) {
 9736:         $changed = 1;
 9737:     } else {
 9738:         foreach my $field (@fields) {
 9739:             if ($names{$field} ne $oldnames{$field}) {
 9740:                 $changed = 1;
 9741:                 last;
 9742:             }
 9743:         }
 9744:     }
 9745:     unless ($changed) {
 9746:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9747:         &logthis($logmsg);
 9748:         return 'ok';
 9749:     }
 9750:     my $reply = &put('environment', \%names, $udom,$uname);
 9751:     if ($reply ne 'ok') { 
 9752:         return 'error: '.$reply;
 9753:     }
 9754:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9755:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9756:     }
 9757:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9758:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9759:     $logmsg = 'Success modifying user '.$logmsg;
 9760:     &logthis($logmsg);
 9761:     return 'ok';
 9762: }
 9763: 
 9764: # -------------------------------------------------------------- Modify student
 9765: 
 9766: sub modifystudent {
 9767:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9768:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9769:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9770:     if (!$cid) {
 9771: 	unless ($cid=$env{'request.course.id'}) {
 9772: 	    return 'not_in_class';
 9773: 	}
 9774:     }
 9775: # --------------------------------------------------------------- Make the user
 9776:     my $reply=&modifyuser
 9777: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9778:          $desiredhome,$email,$inststatus);
 9779:     unless ($reply eq 'ok') { return $reply; }
 9780:     # This will cause &modify_student_enrollment to get the uid from the
 9781:     # student's environment
 9782:     $uid = undef if (!$forceid);
 9783:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9784:                                         $gene,$usec,$end,$start,$type,$locktype,
 9785:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9786:     return $reply;
 9787: }
 9788: 
 9789: sub modify_student_enrollment {
 9790:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9791:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9792:     my ($cdom,$cnum,$chome);
 9793:     if (!$cid) {
 9794: 	unless ($cid=$env{'request.course.id'}) {
 9795: 	    return 'not_in_class';
 9796: 	}
 9797: 	$cdom=$env{'course.'.$cid.'.domain'};
 9798: 	$cnum=$env{'course.'.$cid.'.num'};
 9799:     } else {
 9800: 	($cdom,$cnum)=split(/_/,$cid);
 9801:     }
 9802:     $chome=$env{'course.'.$cid.'.home'};
 9803:     if (!$chome) {
 9804: 	$chome=&homeserver($cnum,$cdom);
 9805:     }
 9806:     if (!$chome) { return 'unknown_course'; }
 9807:     # Make sure the user exists
 9808:     my $uhome=&homeserver($uname,$udom);
 9809:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9810: 	return 'error: no such user';
 9811:     }
 9812:     # Get student data if we were not given enough information
 9813:     if (!defined($first)  || $first  eq '' || 
 9814:         !defined($last)   || $last   eq '' || 
 9815:         !defined($uid)    || $uid    eq '' || 
 9816:         !defined($middle) || $middle eq '' || 
 9817:         !defined($gene)   || $gene   eq '') {
 9818:         # They did not supply us with enough data to enroll the student, so
 9819:         # we need to pick up more information.
 9820:         my %tmp = &get('environment',
 9821:                        ['firstname','middlename','lastname', 'generation','id']
 9822:                        ,$udom,$uname);
 9823: 
 9824:         #foreach my $key (keys(%tmp)) {
 9825:         #    &logthis("key $key = ".$tmp{$key});
 9826:         #}
 9827:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9828:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9829:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9830:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9831:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9832:     }
 9833:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9834:     my $user = "$uname:$udom";
 9835:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9836:     my $reply=cput('classlist',
 9837: 		   {$user => 
 9838: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9839: 		   $cdom,$cnum);
 9840:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9841:         &devalidate_getsection_cache($udom,$uname,$cid);
 9842:     } else { 
 9843: 	return 'error: '.$reply;
 9844:     }
 9845:     # Add student role to user
 9846:     my $uurl='/'.$cid;
 9847:     $uurl=~s/\_/\//g;
 9848:     if ($usec) {
 9849: 	$uurl.='/'.$usec;
 9850:     }
 9851:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9852:                              $selfenroll,$context);
 9853:     if ($result ne 'ok') {
 9854:         if ($old_entry{$user} ne '') {
 9855:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9856:         } else {
 9857:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9858:         }
 9859:     }
 9860:     return $result; 
 9861: }
 9862: 
 9863: sub format_name {
 9864:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9865:     my $name;
 9866:     if ($first ne 'lastname') {
 9867: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9868:     } else {
 9869: 	if ($lastname=~/\S/) {
 9870: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9871: 	    $name=~s/\s+,/,/;
 9872: 	} else {
 9873: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9874: 	}
 9875:     }
 9876:     $name=~s/^\s+//;
 9877:     $name=~s/\s+$//;
 9878:     $name=~s/\s+/ /g;
 9879:     return $name;
 9880: }
 9881: 
 9882: # ------------------------------------------------- Write to course preferences
 9883: 
 9884: sub writecoursepref {
 9885:     my ($courseid,%prefs)=@_;
 9886:     $courseid=~s/^\///;
 9887:     $courseid=~s/\_/\//g;
 9888:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9889:     my $chome=homeserver($cnum,$cdomain);
 9890:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9891: 	return 'error: no such course';
 9892:     }
 9893:     my $cstring='';
 9894:     foreach my $pref (keys(%prefs)) {
 9895: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9896:     }
 9897:     $cstring=~s/\&$//;
 9898:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9899: }
 9900: 
 9901: # ---------------------------------------------------------- Make/modify course
 9902: 
 9903: sub createcourse {
 9904:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9905:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9906:     $url=&declutter($url);
 9907:     my $cid='';
 9908:     if ($context eq 'requestcourses') {
 9909:         my $can_create = 0;
 9910:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9911:         if ($udom eq $ownerdom) {
 9912:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9913:                                   $context)) {
 9914:                 $can_create = 1;
 9915:             }
 9916:         } else {
 9917:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9918:                                            $category);
 9919:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9920:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9921:                 if (@curr > 0) {
 9922:                     my @options = qw(approval validate autolimit);
 9923:                     my $optregex = join('|',@options);
 9924:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9925:                         $can_create = 1;
 9926:                     }
 9927:                 }
 9928:             }
 9929:         }
 9930:         if ($can_create) {
 9931:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 9932:                 unless (&allowed('ccc',$udom)) {
 9933:                     return 'refused'; 
 9934:                 }
 9935:             }
 9936:         } else {
 9937:             return 'refused';
 9938:         }
 9939:     } elsif (!&allowed('ccc',$udom)) {
 9940:         return 'refused';
 9941:     }
 9942: # --------------------------------------------------------------- Get Unique ID
 9943:     my $uname;
 9944:     if ($cnum =~ /^$match_courseid$/) {
 9945:         my $chome=&homeserver($cnum,$udom,'true');
 9946:         if (($chome eq '') || ($chome eq 'no_host')) {
 9947:             $uname = $cnum;
 9948:         } else {
 9949:             $uname = &generate_coursenum($udom,$crstype);
 9950:         }
 9951:     } else {
 9952:         $uname = &generate_coursenum($udom,$crstype);
 9953:     }
 9954:     return $uname if ($uname =~ /^error/);
 9955: # -------------------------------------------------- Check supplied server name
 9956:     if (!defined($course_server)) {
 9957:         if (defined(&domain($udom,'primary'))) {
 9958:             $course_server = &domain($udom,'primary');
 9959:         } else {
 9960:             $course_server = $env{'user.home'}; 
 9961:         }
 9962:     }
 9963:     my %host_servers =
 9964:         &Apache::lonnet::get_servers($udom,'library');
 9965:     unless ($host_servers{$course_server}) {
 9966:         return 'error: invalid home server for course: '.$course_server;
 9967:     }
 9968: # ------------------------------------------------------------- Make the course
 9969:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 9970:                       $course_server);
 9971:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 9972:     my $uhome=&homeserver($uname,$udom,'true');
 9973:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9974: 	return 'error: no such course';
 9975:     }
 9976: # ----------------------------------------------------------------- Course made
 9977: # log existence
 9978:     my $now = time;
 9979:     my $newcourse = {
 9980:                     $udom.'_'.$uname => {
 9981:                                      description => $description,
 9982:                                      inst_code   => $inst_code,
 9983:                                      owner       => $course_owner,
 9984:                                      type        => $crstype,
 9985:                                      creator     => $env{'user.name'}.':'.
 9986:                                                     $env{'user.domain'},
 9987:                                      created     => $now,
 9988:                                      context     => $context,
 9989:                                                 },
 9990:                     };
 9991:     &courseidput($udom,$newcourse,$uhome,'notime');
 9992: # set toplevel url
 9993:     my $topurl=$url;
 9994:     unless ($nonstandard) {
 9995: # ------------------------------------------ For standard courses, make top url
 9996:         my $mapurl=&clutter($url);
 9997:         if ($mapurl eq '/res/') { $mapurl=''; }
 9998:         $env{'form.initmap'}=(<<ENDINITMAP);
 9999: <map>
10000: <resource id="1" type="start"></resource>
10001: <resource id="2" src="$mapurl"></resource>
10002: <resource id="3" type="finish"></resource>
10003: <link index="1" from="1" to="2"></link>
10004: <link index="2" from="2" to="3"></link>
10005: </map>
10006: ENDINITMAP
10007:         $topurl=&declutter(
10008:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10009:                           );
10010:     }
10011: # ----------------------------------------------------------- Write preferences
10012:     &writecoursepref($udom.'_'.$uname,
10013:                      ('description'              => $description,
10014:                       'url'                      => $topurl,
10015:                       'internal.creator'         => $env{'user.name'}.':'.
10016:                                                     $env{'user.domain'},
10017:                       'internal.created'         => $now,
10018:                       'internal.creationcontext' => $context)
10019:                     );
10020:     return '/'.$udom.'/'.$uname;
10021: }
10022: 
10023: # ------------------------------------------------------------------- Create ID
10024: sub generate_coursenum {
10025:     my ($udom,$crstype) = @_;
10026:     my $domdesc = &domain($udom);
10027:     return 'error: invalid domain' if ($domdesc eq '');
10028:     my $first;
10029:     if ($crstype eq 'Community') {
10030:         $first = '0';
10031:     } else {
10032:         $first = int(1+rand(9)); 
10033:     } 
10034:     my $uname=$first.
10035:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10036:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10037:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10038: # ----------------------------------------------- Make sure that does not exist
10039:     my $uhome=&homeserver($uname,$udom,'true');
10040:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10041:         if ($crstype eq 'Community') {
10042:             $first = '0';
10043:         } else {
10044:             $first = int(1+rand(9));
10045:         }
10046:         $uname=$first.
10047:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10048:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10049:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10050:         $uhome=&homeserver($uname,$udom,'true');
10051:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10052:             return 'error: unable to generate unique course-ID';
10053:         }
10054:     }
10055:     return $uname;
10056: }
10057: 
10058: sub is_course {
10059:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10060:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10061: 
10062:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10063:     my $uhome=&homeserver($cnum,$cdom);
10064:     my $iscourse;
10065:     if (grep { $_ eq $uhome } current_machine_ids()) {
10066:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10067:     } else {
10068:         my $hashid = $cdom.':'.$cnum;
10069:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10070:         unless (defined($cached)) {
10071:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10072:                                         $cnum,undef,undef,'.');
10073:             $iscourse = 0;
10074:             if (exists($courses{$cdom.'_'.$cnum})) {
10075:                 $iscourse = 1;
10076:             }
10077:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10078:         }
10079:     }
10080:     return unless ($iscourse);
10081:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10082: }
10083: 
10084: sub store_userdata {
10085:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10086:     my $result;
10087:     if ($datakey ne '') {
10088:         if (ref($storehash) eq 'HASH') {
10089:             if ($udom eq '' || $uname eq '') {
10090:                 $udom = $env{'user.domain'};
10091:                 $uname = $env{'user.name'};
10092:             }
10093:             my $uhome=&homeserver($uname,$udom);
10094:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10095:                 $result = 'error: no_host';
10096:             } else {
10097:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10098:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10099: 
10100:                 my $namevalue='';
10101:                 foreach my $key (keys(%{$storehash})) {
10102:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10103:                 }
10104:                 $namevalue=~s/\&$//;
10105:                 unless ($namespace eq 'courserequests') {
10106:                     $datakey = &escape($datakey);
10107:                 }
10108:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10109:                                   $namevalue,$uhome);
10110:             }
10111:         } else {
10112:             $result = 'error: data to store was not a hash reference'; 
10113:         }
10114:     } else {
10115:         $result= 'error: invalid requestkey'; 
10116:     }
10117:     return $result;
10118: }
10119: 
10120: # ---------------------------------------------------------- Assign Custom Role
10121: 
10122: sub assigncustomrole {
10123:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10124:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10125:                        $end,$start,$deleteflag,$selfenroll,$context);
10126: }
10127: 
10128: # ----------------------------------------------------------------- Revoke Role
10129: 
10130: sub revokerole {
10131:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10132:     my $now=time;
10133:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10134: }
10135: 
10136: # ---------------------------------------------------------- Revoke Custom Role
10137: 
10138: sub revokecustomrole {
10139:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10140:     my $now=time;
10141:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10142:            $deleteflag,$selfenroll,$context);
10143: }
10144: 
10145: # ------------------------------------------------------------ Disk usage
10146: sub diskusage {
10147:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10148:     $directorypath =~ s/\/$//;
10149:     my $listing=&reply('du2:'.&escape($directorypath).':'
10150:                        .&escape($getpropath).':'.&escape($uname).':'
10151:                        .&escape($udom),homeserver($uname,$udom));
10152:     if ($listing eq 'unknown_cmd') {
10153:         if ($getpropath) {
10154:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10155:         }
10156:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10157:     }
10158:     return $listing;
10159: }
10160: 
10161: sub is_locked {
10162:     my ($file_name, $domain, $user, $which) = @_;
10163:     my @check;
10164:     my $is_locked;
10165:     push (@check,$file_name);
10166:     my %locked = &get('file_permissions',\@check,
10167: 		      $env{'user.domain'},$env{'user.name'});
10168:     my ($tmp)=keys(%locked);
10169:     if ($tmp=~/^error:/) { undef(%locked); }
10170:     
10171:     if (ref($locked{$file_name}) eq 'ARRAY') {
10172:         $is_locked = 'false';
10173:         foreach my $entry (@{$locked{$file_name}}) {
10174:            if (ref($entry) eq 'ARRAY') {
10175:                $is_locked = 'true';
10176:                if (ref($which) eq 'ARRAY') {
10177:                    push(@{$which},$entry);
10178:                } else {
10179:                    last;
10180:                }
10181:            }
10182:        }
10183:     } else {
10184:         $is_locked = 'false';
10185:     }
10186:     return $is_locked;
10187: }
10188: 
10189: sub declutter_portfile {
10190:     my ($file) = @_;
10191:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10192:     return $file;
10193: }
10194: 
10195: # ------------------------------------------------------------- Mark as Read Only
10196: 
10197: sub mark_as_readonly {
10198:     my ($domain,$user,$files,$what) = @_;
10199:     my %current_permissions = &dump('file_permissions',$domain,$user);
10200:     my ($tmp)=keys(%current_permissions);
10201:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10202:     foreach my $file (@{$files}) {
10203: 	$file = &declutter_portfile($file);
10204:         push(@{$current_permissions{$file}},$what);
10205:     }
10206:     &put('file_permissions',\%current_permissions,$domain,$user);
10207:     return;
10208: }
10209: 
10210: # ------------------------------------------------------------Save Selected Files
10211: 
10212: sub save_selected_files {
10213:     my ($user, $path, @files) = @_;
10214:     my $filename = $user."savedfiles";
10215:     my @other_files = &files_not_in_path($user, $path);
10216:     open (OUT,'>',LONCAPA::tempdir().$filename);
10217:     foreach my $file (@files) {
10218:         print (OUT $env{'form.currentpath'}.$file."\n");
10219:     }
10220:     foreach my $file (@other_files) {
10221:         print (OUT $file."\n");
10222:     }
10223:     close (OUT);
10224:     return 'ok';
10225: }
10226: 
10227: sub clear_selected_files {
10228:     my ($user) = @_;
10229:     my $filename = $user."savedfiles";
10230:     open (OUT,'>',LONCAPA::tempdir().$filename);
10231:     print (OUT undef);
10232:     close (OUT);
10233:     return ("ok");    
10234: }
10235: 
10236: sub files_in_path {
10237:     my ($user, $path) = @_;
10238:     my $filename = $user."savedfiles";
10239:     my %return_files;
10240:     open (IN,'<',LONCAPA::tempdir().$filename);
10241:     while (my $line_in = <IN>) {
10242:         chomp ($line_in);
10243:         my @paths_and_file = split (m!/!, $line_in);
10244:         my $file_part = pop (@paths_and_file);
10245:         my $path_part = join ('/', @paths_and_file);
10246:         $path_part.='/';
10247:         my $path_and_file = $path_part.$file_part;
10248:         if ($path_part eq $path) {
10249:             $return_files{$file_part}= 'selected';
10250:         }
10251:     }
10252:     close (IN);
10253:     return (\%return_files);
10254: }
10255: 
10256: # called in portfolio select mode, to show files selected NOT in current directory
10257: sub files_not_in_path {
10258:     my ($user, $path) = @_;
10259:     my $filename = $user."savedfiles";
10260:     my @return_files;
10261:     my $path_part;
10262:     open(IN, '<',LONCAPA::tempdir().$filename);
10263:     while (my $line = <IN>) {
10264:         #ok, I know it's clunky, but I want it to work
10265:         my @paths_and_file = split(m|/|, $line);
10266:         my $file_part = pop(@paths_and_file);
10267:         chomp($file_part);
10268:         my $path_part = join('/', @paths_and_file);
10269:         $path_part .= '/';
10270:         my $path_and_file = $path_part.$file_part;
10271:         if ($path_part ne $path) {
10272:             push(@return_files, ($path_and_file));
10273:         }
10274:     }
10275:     close(OUT);
10276:     return (@return_files);
10277: }
10278: 
10279: #------------------------------Submitted/Handedback Portfolio Files Versioning
10280:  
10281: sub portfiles_versioning {
10282:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10283:     my $portfolio_root = '/userfiles/portfolio';
10284:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10285:     foreach my $file (@{$portfiles}) {
10286:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10287:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10288:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10289:         my $getpropath = 1;
10290:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10291:                                              $stu_name,$getpropath);
10292:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10293:         my $new_answer = 
10294:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10295:         if ($new_answer ne 'problem getting file') {
10296:             push(@{$versioned_portfiles}, $directory.$new_answer);
10297:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10298:                               [$symb,$env{'request.course.id'},'graded']);
10299:         }
10300:     }
10301: }
10302: 
10303: sub get_next_version {
10304:     my ($answer_name, $answer_ext, $dir_list) = @_;
10305:     my $version;
10306:     if (ref($dir_list) eq 'ARRAY') {
10307:         foreach my $row (@{$dir_list}) {
10308:             my ($file) = split(/\&/,$row,2);
10309:             my ($file_name,$file_version,$file_ext) =
10310:                 &file_name_version_ext($file);
10311:             if (($file_name eq $answer_name) &&
10312:                 ($file_ext eq $answer_ext)) {
10313:                      # gets here if filename and extension match,
10314:                      # regardless of version
10315:                 if ($file_version ne '') {
10316:                     # a versioned file is found  so save it for later
10317:                     if ($file_version > $version) {
10318:                         $version = $file_version;
10319:                     }
10320:                 }
10321:             }
10322:         }
10323:     }
10324:     $version ++;
10325:     return($version);
10326: }
10327: 
10328: sub version_selected_portfile {
10329:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10330:     my ($answer_name,$answer_ver,$answer_ext) =
10331:         &file_name_version_ext($file_name);
10332:     my $new_answer;
10333:     $env{'form.copy'} =
10334:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10335:     if($env{'form.copy'} eq '-1') {
10336:         $new_answer = 'problem getting file';
10337:     } else {
10338:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10339:         my $copy_result = 
10340:             &finishuserfileupload($stu_name,$domain,'copy',
10341:                                   '/portfolio'.$directory.$new_answer);
10342:     }
10343:     undef($env{'form.copy'});
10344:     return ($new_answer);
10345: }
10346: 
10347: sub file_name_version_ext {
10348:     my ($file)=@_;
10349:     my @file_parts = split(/\./, $file);
10350:     my ($name,$version,$ext);
10351:     if (@file_parts > 1) {
10352:         $ext=pop(@file_parts);
10353:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10354:             $version=pop(@file_parts);
10355:         }
10356:         $name=join('.',@file_parts);
10357:     } else {
10358:         $name=join('.',@file_parts);
10359:     }
10360:     return($name,$version,$ext);
10361: }
10362: 
10363: #----------------------------------------------Get portfolio file permissions
10364: 
10365: sub get_portfile_permissions {
10366:     my ($domain,$user) = @_;
10367:     my %current_permissions = &dump('file_permissions',$domain,$user);
10368:     my ($tmp)=keys(%current_permissions);
10369:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10370:     return \%current_permissions;
10371: }
10372: 
10373: #---------------------------------------------Get portfolio file access controls
10374: 
10375: sub get_access_controls {
10376:     my ($current_permissions,$group,$file) = @_;
10377:     my %access;
10378:     my $real_file = $file;
10379:     $file =~ s/\.meta$//;
10380:     if (defined($file)) {
10381:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10382:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10383:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10384:             }
10385:         }
10386:     } else {
10387:         foreach my $key (keys(%{$current_permissions})) {
10388:             if ($key =~ /\0accesscontrol$/) {
10389:                 if (defined($group)) {
10390:                     if ($key !~ m-^\Q$group\E/-) {
10391:                         next;
10392:                     }
10393:                 }
10394:                 my ($fullpath) = split(/\0/,$key);
10395:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10396:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10397:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10398:                     }
10399:                 }
10400:             }
10401:         }
10402:     }
10403:     return %access;
10404: }
10405: 
10406: sub modify_access_controls {
10407:     my ($file_name,$changes,$domain,$user)=@_;
10408:     my ($outcome,$deloutcome);
10409:     my %store_permissions;
10410:     my %new_values;
10411:     my %new_control;
10412:     my %translation;
10413:     my @deletions = ();
10414:     my $now = time;
10415:     if (exists($$changes{'activate'})) {
10416:         if (ref($$changes{'activate'}) eq 'HASH') {
10417:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10418:             my $numnew = scalar(@newitems);
10419:             for (my $i=0; $i<$numnew; $i++) {
10420:                 my $newkey = $newitems[$i];
10421:                 my $newid = &Apache::loncommon::get_cgi_id();
10422:                 if ($newkey =~ /^\d+:/) { 
10423:                     $newkey =~ s/^(\d+)/$newid/;
10424:                     $translation{$1} = $newid;
10425:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10426:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10427:                     $translation{$1} = $newid;
10428:                 }
10429:                 $new_values{$file_name."\0".$newkey} = 
10430:                                           $$changes{'activate'}{$newitems[$i]};
10431:                 $new_control{$newkey} = $now;
10432:             }
10433:         }
10434:     }
10435:     my %todelete;
10436:     my %changed_items;
10437:     foreach my $action ('delete','update') {
10438:         if (exists($$changes{$action})) {
10439:             if (ref($$changes{$action}) eq 'HASH') {
10440:                 foreach my $key (keys(%{$$changes{$action}})) {
10441:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10442:                     if ($action eq 'delete') { 
10443:                         $todelete{$itemnum} = 1;
10444:                     } else {
10445:                         $changed_items{$itemnum} = $key;
10446:                     }
10447:                 }
10448:             }
10449:         }
10450:     }
10451:     # get lock on access controls for file.
10452:     my $lockhash = {
10453:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10454:                                                        ':'.$env{'user.domain'},
10455:                    }; 
10456:     my $tries = 0;
10457:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10458:    
10459:     while (($gotlock ne 'ok') && $tries < 10) {
10460:         $tries ++;
10461:         sleep(0.1);
10462:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10463:     }
10464:     if ($gotlock eq 'ok') {
10465:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10466:         my ($tmp)=keys(%curr_permissions);
10467:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10468:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10469:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10470:             if (ref($curr_controls) eq 'HASH') {
10471:                 foreach my $control_item (keys(%{$curr_controls})) {
10472:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10473:                     if (defined($todelete{$itemnum})) {
10474:                         push(@deletions,$file_name."\0".$control_item);
10475:                     } else {
10476:                         if (defined($changed_items{$itemnum})) {
10477:                             $new_control{$changed_items{$itemnum}} = $now;
10478:                             push(@deletions,$file_name."\0".$control_item);
10479:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10480:                         } else {
10481:                             $new_control{$control_item} = $$curr_controls{$control_item};
10482:                         }
10483:                     }
10484:                 }
10485:             }
10486:         }
10487:         my ($group);
10488:         if (&is_course($domain,$user)) {
10489:             ($group,my $file) = split(/\//,$file_name,2);
10490:         }
10491:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10492:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10493:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10494:         #  remove lock
10495:         my @del_lock = ($file_name."\0".'locked_access_records');
10496:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10497:         my $sqlresult =
10498:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10499:                                     $group);
10500:     } else {
10501:         $outcome = "error: could not obtain lockfile\n";  
10502:     }
10503:     return ($outcome,$deloutcome,\%new_values,\%translation);
10504: }
10505: 
10506: sub make_public_indefinitely {
10507:     my (@requrl) = @_;
10508:     return &automated_portfile_access('public',\@requrl);
10509: }
10510: 
10511: sub automated_portfile_access {
10512:     my ($accesstype,$addsref,$delsref,$info) = @_;
10513:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10514:         return 'invalid';
10515:     }
10516:     my %urls;
10517:     if (ref($addsref) eq 'ARRAY') {
10518:         foreach my $requrl (@{$addsref}) {
10519:             if (&is_portfolio_url($requrl)) {
10520:                 unless (exists($urls{$requrl})) {
10521:                     $urls{$requrl} = 'add';
10522:                 }
10523:             }
10524:         }
10525:     }
10526:     if (ref($delsref) eq 'ARRAY') {
10527:         foreach my $requrl (@{$delsref}) { 
10528:             if (&is_portfolio_url($requrl)) {
10529:                 unless (exists($urls{$requrl})) {
10530:                     $urls{$requrl} = 'delete'; 
10531:                 }
10532:             }
10533:         }
10534:     }
10535:     unless (keys(%urls)) {
10536:         return 'invalid';
10537:     }
10538:     my $ip;
10539:     if ($accesstype eq 'ip') {
10540:         if (ref($info) eq 'HASH') {
10541:             if ($info->{'ip'} ne '') {
10542:                 $ip = $info->{'ip'};
10543:             }
10544:         }
10545:         if ($ip eq '') {
10546:             return 'invalid';
10547:         }
10548:     }
10549:     my $errors;
10550:     my $now = time;
10551:     my %current_perms;
10552:     foreach my $requrl (sort(keys(%urls))) {
10553:         my $action;
10554:         if ($urls{$requrl} eq 'add') {
10555:             $action = 'activate';
10556:         } else {
10557:             $action = 'none';
10558:         }
10559:         my $aclnum = 0;
10560:         my (undef,$udom,$unum,$file_name,$group) =
10561:             &parse_portfolio_url($requrl);
10562:         unless (exists($current_perms{$unum.':'.$udom})) {
10563:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10564:         }
10565:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10566:                                                    $group,$file_name);
10567:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10568:             my ($num,$scope,$end,$start) = 
10569:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10570:             if ($scope eq $accesstype) {
10571:                 if (($start <= $now) && ($end == 0)) {
10572:                     if ($accesstype eq 'ip') {
10573:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10574:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10575:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10576:                                     if ($urls{$requrl} eq 'add') {
10577:                                         $action = 'none';
10578:                                         last;
10579:                                     } else {
10580:                                         $action = 'delete';
10581:                                         $aclnum = $num;
10582:                                         last;
10583:                                     }
10584:                                 }
10585:                             }
10586:                         }
10587:                     } elsif ($accesstype eq 'public') {
10588:                         if ($urls{$requrl} eq 'add') {
10589:                             $action = 'none';
10590:                             last;
10591:                         } else {
10592:                             $action = 'delete';
10593:                             $aclnum = $num;
10594:                             last;
10595:                         }
10596:                     }
10597:                 } elsif ($accesstype eq 'public') {
10598:                     $action = 'update';
10599:                     $aclnum = $num;
10600:                     last;
10601:                 }
10602:             }
10603:         }
10604:         if ($action eq 'none') {
10605:             next;
10606:         } else {
10607:             my %changes;
10608:             my $newend = 0;
10609:             my $newstart = $now;
10610:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10611:             $changes{$action}{$newkey} = {
10612:                 type => $accesstype,
10613:                 time => {
10614:                     start => $newstart,
10615:                     end   => $newend,
10616:                 },
10617:             };
10618:             if ($accesstype eq 'ip') {
10619:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10620:             }
10621:             my ($outcome,$deloutcome,$new_values,$translation) =
10622:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10623:             unless ($outcome eq 'ok') {
10624:                 $errors .= $outcome.' ';
10625:             }
10626:         }
10627:     }
10628:     if ($errors) {
10629:         $errors =~ s/\s$//;
10630:         return $errors;
10631:     } else {
10632:         return 'ok';
10633:     }
10634: }
10635: 
10636: #------------------------------------------------------Get Marked as Read Only
10637: 
10638: sub get_marked_as_readonly {
10639:     my ($domain,$user,$what,$group) = @_;
10640:     my $current_permissions = &get_portfile_permissions($domain,$user);
10641:     my @readonly_files;
10642:     my $cmp1=$what;
10643:     if (ref($what)) { $cmp1=join('',@{$what}) };
10644:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10645:         if (defined($group)) {
10646:             if ($file_name !~ m-^\Q$group\E/-) {
10647:                 next;
10648:             }
10649:         }
10650:         if (ref($value) eq "ARRAY"){
10651:             foreach my $stored_what (@{$value}) {
10652:                 my $cmp2=$stored_what;
10653:                 if (ref($stored_what) eq 'ARRAY') {
10654:                     $cmp2=join('',@{$stored_what});
10655:                 }
10656:                 if ($cmp1 eq $cmp2) {
10657:                     push(@readonly_files, $file_name);
10658:                     last;
10659:                 } elsif (!defined($what)) {
10660:                     push(@readonly_files, $file_name);
10661:                     last;
10662:                 }
10663:             }
10664:         }
10665:     }
10666:     return @readonly_files;
10667: }
10668: #-----------------------------------------------------------Get Marked as Read Only Hash
10669: 
10670: sub get_marked_as_readonly_hash {
10671:     my ($current_permissions,$group,$what) = @_;
10672:     my %readonly_files;
10673:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10674:         if (defined($group)) {
10675:             if ($file_name !~ m-^\Q$group\E/-) {
10676:                 next;
10677:             }
10678:         }
10679:         if (ref($value) eq "ARRAY"){
10680:             foreach my $stored_what (@{$value}) {
10681:                 if (ref($stored_what) eq 'ARRAY') {
10682:                     foreach my $lock_descriptor(@{$stored_what}) {
10683:                         if ($lock_descriptor eq 'graded') {
10684:                             $readonly_files{$file_name} = 'graded';
10685:                         } elsif ($lock_descriptor eq 'handback') {
10686:                             $readonly_files{$file_name} = 'handback';
10687:                         } else {
10688:                             if (!exists($readonly_files{$file_name})) {
10689:                                 $readonly_files{$file_name} = 'locked';
10690:                             }
10691:                         }
10692:                     }
10693:                 } 
10694:             }
10695:         } 
10696:     }
10697:     return %readonly_files;
10698: }
10699: # ------------------------------------------------------------ Unmark as Read Only
10700: 
10701: sub unmark_as_readonly {
10702:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10703:     # for portfolio submissions, $what contains [$symb,$crsid] 
10704:     my ($domain,$user,$what,$file_name,$group) = @_;
10705:     $file_name = &declutter_portfile($file_name);
10706:     my $symb_crs = $what;
10707:     if (ref($what)) { $symb_crs=join('',@$what); }
10708:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10709:     my ($tmp)=keys(%current_permissions);
10710:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10711:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10712:     foreach my $file (@readonly_files) {
10713: 	my $clean_file = &declutter_portfile($file);
10714: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10715: 	my $current_locks = $current_permissions{$file};
10716:         my @new_locks;
10717:         my @del_keys;
10718:         if (ref($current_locks) eq "ARRAY"){
10719:             foreach my $locker (@{$current_locks}) {
10720:                 my $compare=$locker;
10721:                 if (ref($locker) eq 'ARRAY') {
10722:                     $compare=join('',@{$locker});
10723:                     if ($compare ne $symb_crs) {
10724:                         push(@new_locks, $locker);
10725:                     }
10726:                 }
10727:             }
10728:             if (scalar(@new_locks) > 0) {
10729:                 $current_permissions{$file} = \@new_locks;
10730:             } else {
10731:                 push(@del_keys, $file);
10732:                 &del('file_permissions',\@del_keys, $domain, $user);
10733:                 delete($current_permissions{$file});
10734:             }
10735:         }
10736:     }
10737:     &put('file_permissions',\%current_permissions,$domain,$user);
10738:     return;
10739: }
10740: 
10741: # ------------------------------------------------------------ Directory lister
10742: 
10743: sub dirlist {
10744:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10745:     $uri=~s/^\///;
10746:     $uri=~s/\/$//;
10747:     my ($udom, $uname);
10748:     if ($getuserdir) {
10749:         $udom = $userdomain;
10750:         $uname = $username;
10751:     } else {
10752:         (undef,$udom,$uname)=split(/\//,$uri);
10753:         if(defined($userdomain)) {
10754:             $udom = $userdomain;
10755:         }
10756:         if(defined($username)) {
10757:             $uname = $username;
10758:         }
10759:     }
10760:     my ($dirRoot,$listing,@listing_results);
10761: 
10762:     $dirRoot = $perlvar{'lonDocRoot'};
10763:     if (defined($getpropath)) {
10764:         $dirRoot = &propath($udom,$uname);
10765:         $dirRoot =~ s/\/$//;
10766:     } elsif (defined($getuserdir)) {
10767:         my $subdir=$uname.'__';
10768:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10769:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10770:                    ."/$udom/$subdir/$uname";
10771:     } elsif (defined($alternateRoot)) {
10772:         $dirRoot = $alternateRoot;
10773:     }
10774: 
10775:     if($udom) {
10776:         if($uname) {
10777:             my $uhome = &homeserver($uname,$udom);
10778:             if ($uhome eq 'no_host') {
10779:                 return ([],'no_host');
10780:             }
10781:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10782:                               .$getuserdir.':'.&escape($dirRoot)
10783:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10784:             if ($listing eq 'unknown_cmd') {
10785:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10786:             } else {
10787:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10788:             }
10789:             if ($listing eq 'unknown_cmd') {
10790:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10791:                 @listing_results = split(/:/,$listing);
10792:             } else {
10793:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10794:             }
10795:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10796:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10797:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10798:                 return ([],$listing);
10799:             } else {
10800:                 return (\@listing_results);
10801:             }
10802:         } elsif(!$alternateRoot) {
10803:             my (%allusers,%listerror);
10804: 	    my %servers = &get_servers($udom,'library');
10805:  	    foreach my $tryserver (keys(%servers)) {
10806:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10807:                                   &escape($udom),$tryserver);
10808:                 if ($listing eq 'unknown_cmd') {
10809: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10810: 				      $udom, $tryserver);
10811:                 } else {
10812:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10813:                 }
10814: 		if ($listing eq 'unknown_cmd') {
10815: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10816: 				      $udom, $tryserver);
10817: 		    @listing_results = split(/:/,$listing);
10818: 		} else {
10819: 		    @listing_results =
10820: 			map { &unescape($_); } split(/:/,$listing);
10821: 		}
10822:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10823:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10824:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10825:                     $listerror{$tryserver} = $listing;
10826:                 } else {
10827: 		    foreach my $line (@listing_results) {
10828: 			my ($entry) = split(/&/,$line,2);
10829: 			$allusers{$entry} = 1;
10830: 		    }
10831: 		}
10832:             }
10833:             my @alluserslist=();
10834:             foreach my $user (sort(keys(%allusers))) {
10835:                 push(@alluserslist,$user.'&user');
10836:             }
10837: 
10838:             if (!%listerror) {
10839:                 # no errors
10840:                 return (\@alluserslist);
10841:             } elsif (scalar(keys(%servers)) == 1) {
10842:                 # one library server, one error 
10843:                 my ($key) = keys(%listerror);
10844:                 return (\@alluserslist, $listerror{$key});
10845:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10846:                 # con_lost indicates that we might miss data from at least one
10847:                 # library server
10848:                 return (\@alluserslist, 'con_lost');
10849:             } else {
10850:                 # multiple library servers and no con_lost -> data should be
10851:                 # complete. 
10852:                 return (\@alluserslist);
10853:             }
10854: 
10855:         } else {
10856:             return ([],'missing username');
10857:         }
10858:     } elsif(!defined($getpropath)) {
10859:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10860:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10861:         return (\@all_domains);
10862:     } else {
10863:         return ([],'missing domain');
10864:     }
10865: }
10866: 
10867: # --------------------------------------------- GetFileTimestamp
10868: # This function utilizes dirlist and returns the date stamp for
10869: # when it was last modified.  It will also return an error of -1
10870: # if an error occurs
10871: 
10872: sub GetFileTimestamp {
10873:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10874:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10875:     $studentName   = &LONCAPA::clean_username($studentName);
10876:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10877:                                     undef,$getuserdir);
10878:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10879:         return -1;
10880:     }
10881:     if (ref($fileref) eq 'ARRAY') {
10882:         my @stats = split('&',$fileref->[0]);
10883:         # @stats contains first the filename, then the stat output
10884:         return $stats[10]; # so this is 10 instead of 9.
10885:     } else {
10886:         return -1;
10887:     }
10888: }
10889: 
10890: sub stat_file {
10891:     my ($uri) = @_;
10892:     $uri = &clutter_with_no_wrapper($uri);
10893: 
10894:     my ($udom,$uname,$file);
10895:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10896: 	($udom,$uname,$file) =
10897: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10898: 	$file = 'userfiles/'.$file;
10899:     }
10900:     if ($uri =~ m-^/res/-) {
10901: 	($udom,$uname) = 
10902: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10903: 	$file = $uri;
10904:     }
10905: 
10906:     if (!$udom || !$uname || !$file) {
10907: 	# unable to handle the uri
10908: 	return ();
10909:     }
10910:     my $getpropath;
10911:     if ($file =~ /^userfiles\//) {
10912:         $getpropath = 1;
10913:     }
10914:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10915:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10916:         return ();
10917:     } else {
10918:         if (ref($listref) eq 'ARRAY') {
10919:             my @stats = split('&',$listref->[0]);
10920: 	    shift(@stats); #filename is first
10921: 	    return @stats;
10922:         }
10923:     }
10924:     return ();
10925: }
10926: 
10927: # --------------------------------------------------------- recursedirs
10928: # Recursive function to traverse either a specific user's Authoring Space
10929: # or corresponding Published Resource Space, and populate the hash ref:
10930: # $dirhashref with URLs of all directories, and if $filehashref hash
10931: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10932: # or .rights files in resource space, and .meta, .save, .log, and .bak
10933: # files in Authoring Space.
10934: #
10935: # Inputs:
10936: #
10937: # $is_home - true if current server is home server for user's space
10938: # $context - either: priv, or res respectively for Authoring or Resource Space.
10939: # $docroot - Document root (i.e., /home/httpd/html
10940: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10941: # $relpath - Current path (relative to top level).
10942: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10943: # $filehashref - reference to hash to populate with URLs of files (Optional)
10944: #
10945: # Returns: nothing
10946: #
10947: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10948: #
10949: # Currently used by interface/londocs.pm to create linked select boxes for
10950: # directory and filename to import a Course "Author" resource into a course, and
10951: # also to create linked select boxes for Authoring Space and Directory to choose
10952: # save location for creation of a new "standard" problem from the Course Editor.
10953: #
10954: 
10955: sub recursedirs {
10956:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10957:     return unless (ref($dirhashref) eq 'HASH');
10958:     my $currpath = $docroot.$toppath;
10959:     if ($relpath) {
10960:         $currpath .= "/$relpath";
10961:     }
10962:     my $savefile;
10963:     if (ref($filehashref)) {
10964:         $savefile = 1;
10965:     }
10966:     if ($is_home) {
10967:         if (opendir(my $dirh,$currpath)) {
10968:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10969:                 next if ($item eq '');
10970:                 if (-d "$currpath/$item") {
10971:                     my $newpath;
10972:                     if ($relpath) {
10973:                         $newpath = "$relpath/$item";
10974:                     } else {
10975:                         $newpath = $item;
10976:                     }
10977:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10978:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10979:                 } elsif ($savefile) {
10980:                     if ($context eq 'priv') {
10981:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10982:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10983:                         }
10984:                     } else {
10985:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10986:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10987:                         }
10988:                     }
10989:                 }
10990:             }
10991:             closedir($dirh);
10992:         }
10993:     } else {
10994:         my ($dirlistref,$listerror) =
10995:             &dirlist($toppath.$relpath);
10996:         my @dir_lines;
10997:         my $dirptr=16384;
10998:         if (ref($dirlistref) eq 'ARRAY') {
10999:             foreach my $dir_line (sort
11000:                               {
11001:                                   my ($afile)=split('&',$a,2);
11002:                                   my ($bfile)=split('&',$b,2);
11003:                                   return (lc($afile) cmp lc($bfile));
11004:                               } (@{$dirlistref})) {
11005:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11006:                     split(/\&/,$dir_line,16);
11007:                 $item =~ s/\s+$//;
11008:                 next if (($item =~ /^\.\.?$/) || ($obs));
11009:                 if ($dirptr&$testdir) {
11010:                     my $newpath;
11011:                     if ($relpath) {
11012:                         $newpath = "$relpath/$item";
11013:                     } else {
11014:                         $relpath = '/';
11015:                         $newpath = $item;
11016:                     }
11017:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11018:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11019:                 } elsif ($savefile) {
11020:                     if ($context eq 'priv') {
11021:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11022:                             $filehashref->{$relpath}{$item} = 1;
11023:                         }
11024:                     } else {
11025:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11026:                             $filehashref->{$relpath}{$item} = 1;
11027:                         }
11028:                     }
11029:                 }
11030:             }
11031:         }
11032:     }
11033:     return;
11034: }
11035: 
11036: # -------------------------------------------------------- Value of a Condition
11037: 
11038: # gets the value of a specific preevaluated condition
11039: #    stored in the string  $env{user.state.<cid>}
11040: # or looks up a condition reference in the bighash and if if hasn't
11041: # already been evaluated recurses into docondval to get the value of
11042: # the condition, then memoizing it to 
11043: #   $env{user.state.<cid>.<condition>}
11044: sub directcondval {
11045:     my $number=shift;
11046:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11047: 	&Apache::lonuserstate::evalstate();
11048:     }
11049:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11050: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11051:     } elsif ($number =~ /^_/) {
11052: 	my $sub_condition;
11053: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11054: 		&GDBM_READER(),0640)) {
11055: 	    $sub_condition=$bighash{'conditions'.$number};
11056: 	    untie(%bighash);
11057: 	}
11058: 	my $value = &docondval($sub_condition);
11059: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11060: 	return $value;
11061:     }
11062:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11063:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11064:     } else {
11065:        return 2;
11066:     }
11067: }
11068: 
11069: # get the collection of conditions for this resource
11070: sub condval {
11071:     my $condidx=shift;
11072:     my $allpathcond='';
11073:     foreach my $cond (split(/\|/,$condidx)) {
11074: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11075: 	    $allpathcond.=
11076: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11077: 	}
11078:     }
11079:     $allpathcond=~s/\|$//;
11080:     return &docondval($allpathcond);
11081: }
11082: 
11083: #evaluates an expression of conditions
11084: sub docondval {
11085:     my ($allpathcond) = @_;
11086:     my $result=0;
11087:     if ($env{'request.course.id'}
11088: 	&& defined($allpathcond)) {
11089: 	my $operand='|';
11090: 	my @stack;
11091: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11092: 	    if ($chunk eq '(') {
11093: 		push @stack,($operand,$result);
11094: 	    } elsif ($chunk eq ')') {
11095: 		my $before=pop @stack;
11096: 		if (pop @stack eq '&') {
11097: 		    $result=$result>$before?$before:$result;
11098: 		} else {
11099: 		    $result=$result>$before?$result:$before;
11100: 		}
11101: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11102: 		$operand=$chunk;
11103: 	    } else {
11104: 		my $new=directcondval($chunk);
11105: 		if ($operand eq '&') {
11106: 		    $result=$result>$new?$new:$result;
11107: 		} else {
11108: 		    $result=$result>$new?$result:$new;
11109: 		}
11110: 	    }
11111: 	}
11112:     }
11113:     return $result;
11114: }
11115: 
11116: # ---------------------------------------------------- Devalidate courseresdata
11117: 
11118: sub devalidatecourseresdata {
11119:     my ($coursenum,$coursedomain)=@_;
11120:     my $hashid=$coursenum.':'.$coursedomain;
11121:     &devalidate_cache_new('courseres',$hashid);
11122: }
11123: 
11124: 
11125: # --------------------------------------------------- Course Resourcedata Query
11126: #
11127: #  Parameters:
11128: #      $coursenum    - Number of the course.
11129: #      $coursedomain - Domain at which the course was created.
11130: #  Returns:
11131: #     A hash of the course parameters along (I think) with timestamps
11132: #     and version info.
11133: 
11134: sub get_courseresdata {
11135:     my ($coursenum,$coursedomain)=@_;
11136:     my $coursehom=&homeserver($coursenum,$coursedomain);
11137:     my $hashid=$coursenum.':'.$coursedomain;
11138:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11139:     my %dumpreply;
11140:     unless (defined($cached)) {
11141: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11142: 	$result=\%dumpreply;
11143: 	my ($tmp) = keys(%dumpreply);
11144: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11145: 	    &do_cache_new('courseres',$hashid,$result,600);
11146: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11147: 	    return $tmp;
11148: 	} elsif ($tmp =~ /^(error)/) {
11149: 	    $result=undef;
11150: 	    &do_cache_new('courseres',$hashid,$result,600);
11151: 	}
11152:     }
11153:     return $result;
11154: }
11155: 
11156: sub devalidateuserresdata {
11157:     my ($uname,$udom)=@_;
11158:     my $hashid="$udom:$uname";
11159:     &devalidate_cache_new('userres',$hashid);
11160: }
11161: 
11162: sub get_userresdata {
11163:     my ($uname,$udom)=@_;
11164:     #most student don\'t have any data set, check if there is some data
11165:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11166: 
11167:     my $hashid="$udom:$uname";
11168:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11169:     if (!defined($cached)) {
11170: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11171: 	$result=\%resourcedata;
11172: 	&do_cache_new('userres',$hashid,$result,600);
11173:     }
11174:     my ($tmp)=keys(%$result);
11175:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11176: 	return $result;
11177:     }
11178:     #error 2 occurs when the .db doesn't exist
11179:     if ($tmp!~/error: 2 /) {
11180:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11181: 	    &logthis("<font color=\"blue\">WARNING:".
11182: 		     " Trying to get resource data for ".
11183: 		     $uname." at ".$udom.": ".
11184: 		     $tmp."</font>");
11185:         }
11186:     } elsif ($tmp=~/error: 2 /) {
11187: 	#&EXT_cache_set($udom,$uname);
11188: 	&do_cache_new('userres',$hashid,undef,600);
11189: 	undef($tmp); # not really an error so don't send it back
11190:     }
11191:     return $tmp;
11192: }
11193: #----------------------------------------------- resdata - return resource data
11194: #  Purpose:
11195: #    Return resource data for either users or for a course.
11196: #  Parameters:
11197: #     $name      - Course/user name.
11198: #     $domain    - Name of the domain the user/course is registered on.
11199: #     $type      - Type of thing $name is (must be 'course' or 'user')
11200: #     $mapp      - decluttered URL of enclosing map  
11201: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11202: #     $recurseup - Ref to array of map URLs, starting with map containing
11203: #                  $mapp up through hierarchy of nested maps to top level map.  
11204: #     $courseid  - CourseID (first part of param identifier).
11205: #     $modifier  - Middle part of param identifier.
11206: #     $what      - Last part of param identifier.
11207: #     @which     - Array of names of resources desired.
11208: #  Returns:
11209: #     The value of the first reasource in @which that is found in the
11210: #     resource hash.
11211: #  Exceptional Conditions:
11212: #     If the $type passed in is not valid (not the string 'course' or 
11213: #     'user', an undefined  reference is returned.
11214: #     If none of the resources are found, an undef is returned
11215: sub resdata {
11216:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11217:         $modifier,$what,@which)=@_;
11218:     my $result;
11219:     if ($type eq 'course') {
11220: 	$result=&get_courseresdata($name,$domain);
11221:     } elsif ($type eq 'user') {
11222: 	$result=&get_userresdata($name,$domain);
11223:     }
11224:     if (!ref($result)) { return $result; }    
11225:     foreach my $item (@which) {
11226:         if ($item->[1] eq 'course') {
11227:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11228:                 unless ($$recursed) {
11229:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11230:                     $$recursed = 1;
11231:                 }
11232:                 foreach my $item (@${recurseup}) {
11233:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11234:                     last if (defined($result->{$norecursechk}));
11235:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11236:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11237:                 }
11238:             }
11239:         }
11240:         if (defined($result->{$item->[0]})) {
11241: 	    return [$result->{$item->[0]},$item->[1]];
11242: 	}
11243:     }
11244:     return undef;
11245: }
11246: 
11247: sub get_domain_lti {
11248:     my ($cdom,$context) = @_;
11249:     my ($name,%lti);
11250:     if ($context eq 'consumer') {
11251:         $name = 'ltitools';
11252:     } elsif ($context eq 'provider') {
11253:         $name = 'lti';
11254:     } else {
11255:         return %lti;
11256:     }
11257:     my ($result,$cached)=&is_cached_new($name,$cdom);
11258:     if (defined($cached)) {
11259:         if (ref($result) eq 'HASH') {
11260:             %lti = %{$result};
11261:         }
11262:     } else {
11263:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11264:         if (ref($domconfig{$name}) eq 'HASH') {
11265:             %lti = %{$domconfig{$name}};
11266:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11267:             if (ref($encdomconfig{$name}) eq 'HASH') {
11268:                 foreach my $id (keys(%lti)) {
11269:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11270:                         foreach my $item ('key','secret') {
11271:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11272:                         }
11273:                     }
11274:                 }
11275:             }
11276:         }
11277:         my $cachetime = 24*60*60;
11278:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11279:     }
11280:     return %lti;
11281: }
11282: 
11283: sub get_numsuppfiles {
11284:     my ($cnum,$cdom,$ignorecache)=@_;
11285:     my $hashid=$cnum.':'.$cdom;
11286:     my ($suppcount,$cached);
11287:     unless ($ignorecache) {
11288:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11289:     }
11290:     unless (defined($cached)) {
11291:         my $chome=&homeserver($cnum,$cdom);
11292:         unless ($chome eq 'no_host') {
11293:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11294:             my $suppmap = 'supplemental.sequence';
11295:             ($suppcount,$supptools,$errors) =
11296:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11297:                                                          $supptools,$errors);
11298:         }
11299:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11300:     }
11301:     return $suppcount;
11302: }
11303: 
11304: #
11305: # EXT resource caching routines
11306: #
11307: 
11308: {
11309: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11310: #
11311: # The course for which we cache
11312: my $cachedmapkey='';
11313: # The cached recursive maps for this course
11314: my %cachedmaps=();
11315: # When this was last done
11316: my $cachedmaptime='';
11317: 
11318: sub clear_EXT_cache_status {
11319:     &delenv('cache.EXT.');
11320: }
11321: 
11322: sub EXT_cache_status {
11323:     my ($target_domain,$target_user) = @_;
11324:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11325:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11326:         # We know already the user has no data
11327:         return 1;
11328:     } else {
11329:         return 0;
11330:     }
11331: }
11332: 
11333: sub EXT_cache_set {
11334:     my ($target_domain,$target_user) = @_;
11335:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11336:     #&appenv({$cachename => time});
11337: }
11338: 
11339: # --------------------------------------------------------- Value of a Variable
11340: sub EXT {
11341: 
11342:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11343:     unless ($varname) { return ''; }
11344:     #get real user name/domain, courseid and symb
11345:     my $courseid;
11346:     my $publicuser;
11347:     if ($symbparm) {
11348: 	$symbparm=&get_symb_from_alias($symbparm);
11349:     }
11350:     if (!($uname && $udom)) {
11351:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11352:       if (!$symbparm) {	$symbparm=$cursymb; }
11353:     } else {
11354: 	$courseid=$env{'request.course.id'};
11355:     }
11356:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11357:     my $rest;
11358:     if (defined($therest[0])) {
11359:        $rest=join('.',@therest);
11360:     } else {
11361:        $rest='';
11362:     }
11363: 
11364:     my $qualifierrest=$qualifier;
11365:     if ($rest) { $qualifierrest.='.'.$rest; }
11366:     my $spacequalifierrest=$space;
11367:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11368:     if ($realm eq 'user') {
11369: # --------------------------------------------------------------- user.resource
11370: 	if ($space eq 'resource') {
11371: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11372: 		  || defined($Apache::lonhomework::parsing_a_task))
11373: 		 &&
11374: 		 ($symbparm eq &symbread()) ) {	
11375: 		# if we are in the middle of processing the resource the
11376: 		# get the value we are planning on committing
11377:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11378:                     return $Apache::lonhomework::results{$qualifierrest};
11379:                 } else {
11380:                     return $Apache::lonhomework::history{$qualifierrest};
11381:                 }
11382: 	    } else {
11383: 		my %restored;
11384: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11385: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11386: 		} else {
11387: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11388: 		}
11389: 		return $restored{$qualifierrest};
11390: 	    }
11391: # ----------------------------------------------------------------- user.access
11392:         } elsif ($space eq 'access') {
11393: 	    # FIXME - not supporting calls for a specific user
11394:             return &allowed($qualifier,$rest);
11395: # ------------------------------------------ user.preferences, user.environment
11396:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11397: 	    if (($uname eq $env{'user.name'}) &&
11398: 		($udom eq $env{'user.domain'})) {
11399: 		return $env{join('.',('environment',$qualifierrest))};
11400: 	    } else {
11401: 		my %returnhash;
11402: 		if (!$publicuser) {
11403: 		    %returnhash=&userenvironment($udom,$uname,
11404: 						 $qualifierrest);
11405: 		}
11406: 		return $returnhash{$qualifierrest};
11407: 	    }
11408: # ----------------------------------------------------------------- user.course
11409:         } elsif ($space eq 'course') {
11410: 	    # FIXME - not supporting calls for a specific user
11411:             return $env{join('.',('request.course',$qualifier))};
11412: # ------------------------------------------------------------------- user.role
11413:         } elsif ($space eq 'role') {
11414: 	    # FIXME - not supporting calls for a specific user
11415:             my ($role,$where)=split(/\./,$env{'request.role'});
11416:             if ($qualifier eq 'value') {
11417: 		return $role;
11418:             } elsif ($qualifier eq 'extent') {
11419:                 return $where;
11420:             }
11421: # ----------------------------------------------------------------- user.domain
11422:         } elsif ($space eq 'domain') {
11423:             return $udom;
11424: # ------------------------------------------------------------------- user.name
11425:         } elsif ($space eq 'name') {
11426:             return $uname;
11427: # ---------------------------------------------------- Any other user namespace
11428:         } else {
11429: 	    my %reply;
11430: 	    if (!$publicuser) {
11431: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11432: 	    }
11433: 	    return $reply{$qualifierrest};
11434:         }
11435:     } elsif ($realm eq 'query') {
11436: # ---------------------------------------------- pull stuff out of query string
11437:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11438: 						[$spacequalifierrest]);
11439: 	return $env{'form.'.$spacequalifierrest}; 
11440:    } elsif ($realm eq 'request') {
11441: # ------------------------------------------------------------- request.browser
11442:         if ($space eq 'browser') {
11443:             return $env{'browser.'.$qualifier};
11444: # ------------------------------------------------------------ request.filename
11445:         } else {
11446:             return $env{'request.'.$spacequalifierrest};
11447:         }
11448:     } elsif ($realm eq 'course') {
11449: # ---------------------------------------------------------- course.description
11450:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11451:     } elsif ($realm eq 'resource') {
11452: 
11453: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11454: 	    if (!$symbparm) { $symbparm=&symbread(); }
11455: 	}
11456: 
11457:         if ($qualifier eq '') {
11458: 	    if ($space eq 'title') {
11459: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11460: 	        return &gettitle($symbparm);
11461: 	    }
11462: 	
11463: 	    if ($space eq 'map') {
11464: 	        my ($map) = &decode_symb($symbparm);
11465: 	        return &symbread($map);
11466: 	    }
11467:             if ($space eq 'maptitle') {
11468:                 my ($map) = &decode_symb($symbparm);
11469:                 return &gettitle($map);
11470:             }
11471: 	    if ($space eq 'filename') {
11472: 	        if ($symbparm) {
11473: 		    return &clutter((&decode_symb($symbparm))[2]);
11474: 	        }
11475: 	        return &hreflocation('',$env{'request.filename'});
11476: 	    }
11477: 
11478:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11479:                 if ($space eq 'visibleparts') {
11480:                     my $navmap = Apache::lonnavmaps::navmap->new();
11481:                     my $item;
11482:                     if (ref($navmap)) {
11483:                         my $res = $navmap->getBySymb($symbparm);
11484:                         my $parts = $res->parts();
11485:                         if (ref($parts) eq 'ARRAY') {
11486:                             $item = join(',',@{$parts});
11487:                         }
11488:                         undef($navmap);
11489:                     }
11490:                     return $item;
11491:                 }
11492:             }
11493:         }
11494: 
11495: 	my ($section, $group, @groups, @recurseup, $recursed);
11496: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11497:         if (($courseid eq '') && ($cid)) {
11498:             $courseid = $cid;
11499:         }
11500: 	if (($symbparm && $courseid) && 
11501: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11502: 
11503: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11504: 
11505: # ----------------------------------------------------- Cascading lookup scheme
11506: 	    my $symbp=$symbparm;
11507: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11508: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11509:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11510: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11511: 	    if (($env{'user.name'} eq $uname) &&
11512: 		($env{'user.domain'} eq $udom)) {
11513: 		$section=$env{'request.course.sec'};
11514:                 @groups = split(/:/,$env{'request.course.groups'});  
11515:                 @groups=&sort_course_groups($courseid,@groups); 
11516: 	    } else {
11517: 		if (! defined($usection)) {
11518: 		    $section=&getsection($udom,$uname,$courseid);
11519: 		} else {
11520: 		    $section = $usection;
11521: 		}
11522:                 @groups = &get_users_groups($udom,$uname,$courseid);
11523: 	    }
11524: 
11525: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11526: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11527:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11528: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11529: 
11530: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11531: 	    my $courselevelr=$courseid.'.'.$symbparm;
11532:             $courseleveli=$courseid.'.'.$recurseparm;
11533: 	    $courselevelm=$courseid.'.'.$mapparm;
11534: 
11535: # ----------------------------------------------------------- first, check user
11536: 
11537: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11538:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11539: 				       ([$courselevelr,'resource'],
11540: 					[$courselevelm,'map'     ],
11541:                                         [$courseleveli,'map'     ],
11542: 					[$courselevel, 'course'  ]));
11543: 	    if (defined($userreply)) { return &get_reply($userreply); }
11544: 
11545: # ------------------------------------------------ second, check some of course
11546:             my $coursereply;
11547:             if (@groups > 0) {
11548:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11549:                                        $recurseparm,$mapparm,$spacequalifierrest,
11550:                                        $mapp,\$recursed,\@recurseup);
11551:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11552:             }
11553: 
11554: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11555: 				  $env{'course.'.$courseid.'.domain'},
11556: 				  'course',$mapp,\$recursed,\@recurseup,
11557:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11558: 				  ([$seclevelr,   'resource'],
11559: 				   [$seclevelm,   'map'     ],
11560:                                    [$secleveli,   'map'     ],
11561: 				   [$seclevel,    'course'  ],
11562: 				   [$courselevelr,'resource']));
11563: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11564: 
11565: # ------------------------------------------------------ third, check map parms
11566: 	    my %parmhash=();
11567: 	    my $thisparm='';
11568: 	    if (tie(%parmhash,'GDBM_File',
11569: 		    $env{'request.course.fn'}.'_parms.db',
11570: 		    &GDBM_READER(),0640)) {
11571: 		$thisparm=$parmhash{$symbparm};
11572: 		untie(%parmhash);
11573: 	    }
11574: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11575: 	}
11576: # ------------------------------------------ fourth, look in resource metadata
11577:  
11578:         my $what = $spacequalifierrest;
11579: 	$what=~s/\./\_/;
11580: 	my $filename;
11581: 	if (!$symbparm) { $symbparm=&symbread(); }
11582: 	if ($symbparm) {
11583: 	    $filename=(&decode_symb($symbparm))[2];
11584: 	} else {
11585: 	    $filename=$env{'request.filename'};
11586: 	}
11587:         my $toolsymb;
11588:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
11589:             $toolsymb = $symbparm;
11590:         }
11591: 	my $metadata=&metadata($filename,$what,$toolsymb);
11592: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11593: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
11594: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11595: 
11596: # ----------------------------------------------- fifth, look in rest of course
11597: 	if ($symbparm && defined($courseid) && 
11598: 	    $courseid eq $env{'request.course.id'}) {
11599: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11600: 				     $env{'course.'.$courseid.'.domain'},
11601: 				     'course',$mapp,\$recursed,\@recurseup,
11602:                                      $courseid,'.',$spacequalifierrest,
11603: 				     ([$courselevelm,'map'   ],
11604:                                       [$courseleveli,'map'   ],
11605: 				      [$courselevel, 'course']));
11606: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11607: 	}
11608: # ------------------------------------------------------------------ Cascade up
11609: 	unless ($space eq '0') {
11610: 	    my @parts=split(/_/,$space);
11611: 	    my $id=pop(@parts);
11612: 	    my $part=join('_',@parts);
11613: 	    if ($part eq '') { $part='0'; }
11614: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11615: 				 $symbparm,$udom,$uname,$section,1);
11616: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11617: 	}
11618: 	if ($recurse) { return undef; }
11619: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
11620: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11621: # ---------------------------------------------------- Any other user namespace
11622:     } elsif ($realm eq 'environment') {
11623: # ----------------------------------------------------------------- environment
11624: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11625: 	    return $env{'environment.'.$spacequalifierrest};
11626: 	} else {
11627: 	    if ($uname eq 'anonymous' && $udom eq '') {
11628: 		return '';
11629: 	    }
11630: 	    my %returnhash=&userenvironment($udom,$uname,
11631: 					    $spacequalifierrest);
11632: 	    return $returnhash{$spacequalifierrest};
11633: 	}
11634:     } elsif ($realm eq 'system') {
11635: # ----------------------------------------------------------------- system.time
11636: 	if ($space eq 'time') {
11637: 	    return time;
11638:         }
11639:     } elsif ($realm eq 'server') {
11640: # ----------------------------------------------------------------- system.time
11641: 	if ($space eq 'name') {
11642: 	    return $ENV{'SERVER_NAME'};
11643:         }
11644:     }
11645:     return '';
11646: }
11647: 
11648: sub get_reply {
11649:     my ($reply_value) = @_;
11650:     if (ref($reply_value) eq 'ARRAY') {
11651:         if (wantarray) {
11652: 	    return @$reply_value;
11653:         }
11654:         return $reply_value->[0];
11655:     } else {
11656:         return $reply_value;
11657:     }
11658: }
11659: 
11660: sub check_group_parms {
11661:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11662:         $recursed,$recurseupref) = @_;
11663:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11664:                   [$what,'course']);
11665:     my $coursereply;
11666:     foreach my $group (@{$groups}) {
11667:         my @groupitems = ();
11668:         foreach my $level (@levels) {
11669:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11670:              push(@groupitems,[$item,$level->[1]]);
11671:         }
11672:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11673:                                    $env{'course.'.$courseid.'.domain'},
11674:                                    'course',$mapp,$recursed,$recurseupref,
11675:                                    $courseid,'.['.$group.'].',$what,
11676:                                    @groupitems);
11677:         last if (defined($coursereply));
11678:     }
11679:     return $coursereply;
11680: }
11681: 
11682: sub get_map_hierarchy {
11683:     my ($mapname,$courseid) = @_;
11684:     my @recurseup = ();
11685:     if ($mapname) {
11686:         if (($cachedmapkey eq $courseid) &&
11687:             (abs($cachedmaptime-time)<5)) {
11688:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11689:                 return @{$cachedmaps{$mapname}};
11690:             }
11691:         }
11692:         my $navmap = Apache::lonnavmaps::navmap->new();
11693:         if (ref($navmap)) {
11694:             @recurseup = $navmap->recurseup_maps($mapname);
11695:             undef($navmap);
11696:             $cachedmaps{$mapname} = \@recurseup;
11697:             $cachedmaptime=time;
11698:             $cachedmapkey=$courseid;
11699:         }
11700:     }
11701:     return @recurseup;
11702: }
11703: 
11704: }
11705: 
11706: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11707:     my ($courseid,@groups) = @_;
11708:     @groups = sort(@groups);
11709:     return @groups;
11710: }
11711: 
11712: sub packages_tab_default {
11713:     my ($uri,$varname,$toolsymb)=@_;
11714:     my (undef,$part,$name)=split(/\./,$varname);
11715: 
11716:     my (@extension,@specifics,$do_default);
11717:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
11718: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11719: 	if ($pack_type eq 'default') {
11720: 	    $do_default=1;
11721: 	} elsif ($pack_type eq 'extension') {
11722: 	    push(@extension,[$package,$pack_type,$pack_part]);
11723: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11724: 	    # only look at packages defaults for packages that this id is
11725: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11726: 	}
11727:     }
11728:     # first look for a package that matches the requested part id
11729:     foreach my $package (@specifics) {
11730: 	my (undef,$pack_type,$pack_part)=@{$package};
11731: 	next if ($pack_part ne $part);
11732: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11733: 	    return $packagetab{"$pack_type&$name&default"};
11734: 	}
11735:     }
11736:     # look for any possible matching non extension_ package
11737:     foreach my $package (@specifics) {
11738: 	my (undef,$pack_type,$pack_part)=@{$package};
11739: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11740: 	    return $packagetab{"$pack_type&$name&default"};
11741: 	}
11742: 	if ($pack_type eq 'part') { $pack_part='0'; }
11743: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11744: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11745: 	}
11746:     }
11747:     # look for any posible extension_ match
11748:     foreach my $package (@extension) {
11749: 	my ($package,$pack_type)=@{$package};
11750: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11751: 	    return $packagetab{"$pack_type&$name&default"};
11752: 	}
11753: 	if (defined($packagetab{$package."&$name&default"})) {
11754: 	    return $packagetab{$package."&$name&default"};
11755: 	}
11756:     }
11757:     # look for a global default setting
11758:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11759: 	return $packagetab{"default&$name&default"};
11760:     }
11761:     return undef;
11762: }
11763: 
11764: sub add_prefix_and_part {
11765:     my ($prefix,$part)=@_;
11766:     my $keyroot;
11767:     if (defined($prefix) && $prefix !~ /^__/) {
11768: 	# prefix that has a part already
11769: 	$keyroot=$prefix;
11770:     } elsif (defined($prefix)) {
11771: 	# prefix that is missing a part
11772: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11773:     } else {
11774: 	# no prefix at all
11775: 	if (defined($part)) { $keyroot='_'.$part; }
11776:     }
11777:     return $keyroot;
11778: }
11779: 
11780: # ---------------------------------------------------------------- Get metadata
11781: 
11782: my %metaentry;
11783: my %importedpartids;
11784: my %importedrespids;
11785: sub metadata {
11786:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
11787:     $uri=&declutter($uri);
11788:     # if it is a non metadata possible uri return quickly
11789:     if (($uri eq '') || 
11790: 	(($uri =~ m|^/*adm/|) && 
11791: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11792:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11793: 	return undef;
11794:     }
11795:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11796: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11797: 	return undef;
11798:     }
11799:     my $filename=$uri;
11800:     $uri=~s/\.meta$//;
11801: #
11802: # Is the metadata already cached?
11803: # Look at timestamp of caching
11804: # Everything is cached by the main uri, libraries are never directly cached
11805: #
11806:     if (!defined($liburi)) {
11807: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11808: 	if (defined($cached)) { return $result->{':'.$what}; }
11809:     }
11810: 
11811: #
11812: # If the uri is for an external tool the file from
11813: # which metadata should be retrieved depends on whether
11814: # the tool had been configured to be gradable (set in the Course
11815: # Editor or Resource Editor).
11816: #
11817: # If a valid symb has been included as the third arg in the call
11818: # to &metadata() that can be used to retrieve the value of
11819: # parameter_0_gradable set for the resource, and included in the
11820: # uploaded map containing the tool. The value is retrieved via
11821: # &EXT(), if a valid symb is available.  Otherwise the value of
11822: # gradable in the exttool_$marker.db file for the tool instance
11823: # is retrieved via &get().
11824: #
11825: # When lonuserstate::traceroute() calls lonnet::EXT() for 
11826: # hiddenresource and encrypturl (during course initialization)
11827: # the map-level parameter for resource.0.gradable included in the 
11828: # uploaded map containing the tool will not yet have been stored
11829: # in the user_course_parms.db file for the user's session, so in 
11830: # this case fall back to retrieving gradable status from the
11831: # exttool_$marker.db file.
11832: #
11833: # In order to avoid an infinite loop, &metadata() will return
11834: # before a call to &EXT(), if the uri is for an external tool
11835: # and the $what for which metadata is being requested is
11836: # parameter_0_gradable or 0_gradable.
11837: #
11838: 
11839:     if ($uri =~ /ext\.tool$/) {
11840:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
11841:             return;
11842:         } else {
11843:             my ($checked,$use_passback);
11844:             if ($toolsymb ne '') {
11845:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
11846:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
11847:                     $checked = 1;
11848:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
11849:                         $use_passback = 1;
11850:                     }
11851:                 }
11852:             }
11853:             unless ($checked) {
11854:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
11855:                 $marker=~s/\D//g;
11856:                 if ($marker) {
11857:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
11858:                     $use_passback = $toolsettings{'gradable'};
11859:                 }
11860:             }
11861:             if ($use_passback) {
11862:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
11863:             } else {
11864:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
11865:             }
11866:         }
11867:     }
11868: 
11869:     {
11870: # Imported parts would go here
11871:         my @origfiletagids=();
11872:         my $importedparts=0;
11873: 
11874: # Imported responseids would go here
11875:         my $importedresponses=0;
11876: #
11877: # Is this a recursive call for a library?
11878: #
11879: #	if (! exists($metacache{$uri})) {
11880: #	    $metacache{$uri}={};
11881: #	}
11882: 	my $cachetime = 60*60;
11883:         if ($liburi) {
11884: 	    $liburi=&declutter($liburi);
11885:             $filename=$liburi;
11886:         } else {
11887: 	    &devalidate_cache_new('meta',$uri);
11888: 	    undef(%metaentry);
11889: 	}
11890:         my %metathesekeys=();
11891:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11892: 	my $metastring;
11893: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11894: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11895: 	    $metastring = 
11896: 		&Apache::lonnet::ssi_body($which,
11897: 					  ('grade_target' => 'meta'));
11898: 	    $cachetime = 1; # only want this cached in the child not long term
11899: 	} elsif (($uri !~ m -^(editupload)/-) && 
11900:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11901: 	    my $file=&filelocation('',&clutter($filename));
11902: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11903: 	    $metastring=&getfile($file);
11904: 	}
11905:         my $parser=HTML::LCParser->new(\$metastring);
11906:         my $token;
11907:         undef %metathesekeys;
11908:         while ($token=$parser->get_token) {
11909: 	    if ($token->[0] eq 'S') {
11910: 		if (defined($token->[2]->{'package'})) {
11911: #
11912: # This is a package - get package info
11913: #
11914: 		    my $package=$token->[2]->{'package'};
11915: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11916: 		    if (defined($token->[2]->{'id'})) { 
11917: 			$keyroot.='_'.$token->[2]->{'id'}; 
11918: 		    }
11919: 		    if ($metaentry{':packages'}) {
11920: 			$metaentry{':packages'}.=','.$package.$keyroot;
11921: 		    } else {
11922: 			$metaentry{':packages'}=$package.$keyroot;
11923: 		    }
11924: 		    foreach my $pack_entry (keys(%packagetab)) {
11925: 			my $part=$keyroot;
11926: 			$part=~s/^\_//;
11927: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11928: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11929: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11930: 			    # ignore package.tab specified default values
11931:                             # here &package_tab_default() will fetch those
11932: 			    if ($subp eq 'default') { next; }
11933: 			    my $value=$packagetab{$pack_entry};
11934: 			    my $unikey;
11935: 			    if ($pack =~ /_0$/) {
11936: 				$unikey='parameter_0_'.$name;
11937: 				$part=0;
11938: 			    } else {
11939: 				$unikey='parameter'.$keyroot.'_'.$name;
11940: 			    }
11941: 			    if ($subp eq 'display') {
11942: 				$value.=' [Part: '.$part.']';
11943: 			    }
11944: 			    $metaentry{':'.$unikey.'.part'}=$part;
11945: 			    $metathesekeys{$unikey}=1;
11946: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11947: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11948: 			    }
11949: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11950: 				$metaentry{':'.$unikey}=
11951: 				    $metaentry{':'.$unikey.'.default'};
11952: 			    }
11953: 			}
11954: 		    }
11955: 		} else {
11956: #
11957: # This is not a package - some other kind of start tag
11958: #
11959: 		    my $entry=$token->[1];
11960: 		    my $unikey='';
11961: 
11962: 		    if ($entry eq 'import') {
11963: #
11964: # Importing a library here
11965: #
11966:                         my $location=$parser->get_text('/import');
11967:                         my $dir=$filename;
11968:                         $dir=~s|[^/]*$||;
11969:                         $location=&filelocation($dir,$location);
11970: 
11971:                         my $importid=$token->[2]->{'id'};
11972:                         my $importmode=$token->[2]->{'importmode'};
11973: #
11974: # Check metadata for imported file to
11975: # see if it contained response items
11976: #
11977:                         my ($origfile,@libfilekeys);
11978:                         my %currmetaentry = %metaentry;
11979:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
11980:                                                            $depthcount+1));
11981:                         if (grep(/^responseorder$/,@libfilekeys)) {
11982:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
11983:                                                              undef,$depthcount+1);
11984:                             if ($libresponseorder ne '') {
11985:                                 if ($#origfiletagids<0) {
11986:                                     undef(%importedrespids);
11987:                                     undef(%importedpartids);
11988:                                 }
11989:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
11990:                                 if (@respids) {
11991:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
11992:                                 }
11993:                                 if ($importedrespids{$importid} ne '') {
11994:                                     $importedresponses = 1;
11995: # We need to get the original file and the imported file to get the response order correct
11996: # Load and inspect original file
11997:                                     if ($#origfiletagids<0) {
11998:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11999:                                         $origfile=&getfile($origfilelocation);
12000:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12001:                                     }
12002:                                 }
12003:                             }
12004:                         }
12005: # Do not overwrite contents of %metaentry hash for resource itself with 
12006: # hash populated for imported library file
12007:                         %metaentry = %currmetaentry;
12008:                         undef(%currmetaentry);
12009:                         if ($importmode eq 'part') {
12010: # Import as part(s)
12011:                            $importedparts=1;
12012: # We need to get the original file and the imported file to get the part order correct
12013: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12014: # Load and inspect original file if we didn't do that already
12015:                            if ($#origfiletagids<0) {
12016:                                undef(%importedrespids);
12017:                                undef(%importedpartids);
12018:                                if ($origfile eq '') {
12019:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12020:                                    $origfile=&getfile($origfilelocation);
12021:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12022:                                }
12023:                            }
12024:                            my @impfilepartids;
12025: # If <partorder> tag is included in metadata for the imported file
12026: # get the parts in the imported file from that.
12027:                            if (grep(/^partorder$/,@libfilekeys)) {
12028:                                %currmetaentry = %metaentry;
12029:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12030:                                                             $depthcount+1);
12031:                                %metaentry = %currmetaentry;
12032:                                undef(%currmetaentry);
12033:                                if ($libpartorder ne '') {
12034:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12035:                                }
12036:                            } else {
12037: # If no <partorder> tag available, load and inspect imported file
12038:                                my $impfile=&getfile($location);
12039:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12040:                            }
12041:                            if ($#impfilepartids>=0) {
12042: # This problem had parts
12043:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12044:                            } else {
12045: # Importing by turning a single problem into a problem part
12046: # It gets the import-tags ID as part-ID
12047:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12048:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12049:                            }
12050:                         } else {
12051: # Import as problem or as normal import
12052:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12053:                             unless ($importmode eq 'problem') {
12054: # Normal import
12055:                                 if (defined($token->[2]->{'id'})) {
12056:                                     $unikey.='_'.$token->[2]->{'id'};
12057:                                 }
12058:                             }
12059: # Check metadata for imported file to
12060: # see if it contained parts
12061:                             if (grep(/^partorder$/,@libfilekeys)) {
12062:                                 %currmetaentry = %metaentry;
12063:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12064:                                                              $depthcount+1);
12065:                                 %metaentry = %currmetaentry;
12066:                                 undef(%currmetaentry);
12067:                                 if ($libpartorder ne '') {
12068:                                     $importedparts = 1;
12069:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12070:                                 }
12071:                             }
12072:                         }
12073: 			if ($depthcount<20) {
12074: 			    my $metadata = 
12075: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12076: 					  $depthcount+1);
12077: 			    foreach my $meta (split(',',$metadata)) {
12078: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12079: 				$metathesekeys{$meta}=1;
12080: 			    }
12081:                         }
12082: 		    } else {
12083: #
12084: # Not importing, some other kind of non-package, non-library start tag
12085: # 
12086:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12087:                         if (defined($token->[2]->{'id'})) {
12088:                             $unikey.='_'.$token->[2]->{'id'};
12089:                         }
12090: 			if (defined($token->[2]->{'name'})) { 
12091: 			    $unikey.='_'.$token->[2]->{'name'}; 
12092: 			}
12093: 			$metathesekeys{$unikey}=1;
12094: 			foreach my $param (@{$token->[3]}) {
12095: 			    $metaentry{':'.$unikey.'.'.$param} =
12096: 				$token->[2]->{$param};
12097: 			}
12098: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12099: 			my $default=$metaentry{':'.$unikey.'.default'};
12100: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12101: 		 # only ws inside the tag, and not in default, so use default
12102: 		 # as value
12103: 			    $metaentry{':'.$unikey}=$default;
12104: 			} elsif ( $internaltext =~ /\S/ ) {
12105: 		  # something interesting inside the tag
12106: 			    $metaentry{':'.$unikey}=$internaltext;
12107: 			} else {
12108: 		  # no interesting values, don't set a default
12109: 			}
12110: # end of not-a-package not-a-library import
12111: 		    }
12112: # end of not-a-package start tag
12113: 		}
12114: # the next is the end of "start tag"
12115: 	    }
12116: 	}
12117: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12118: 	$extension = lc($extension);
12119: 	if ($extension eq 'htm') { $extension='html'; }
12120: 
12121: 	foreach my $key (keys(%packagetab)) {
12122: 	    #no specific packages #how's our extension
12123: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12124: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12125: 					 \%metathesekeys);
12126: 	}
12127: 
12128: 	if (!exists($metaentry{':packages'})
12129: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12130: 	    foreach my $key (keys(%packagetab)) {
12131: 		#no specific packages well let's get default then
12132: 		if ($key!~/^default&/) { next; }
12133: 		&metadata_create_package_def($uri,$key,'default',
12134: 					     \%metathesekeys);
12135: 	    }
12136: 	}
12137: # are there custom rights to evaluate
12138: 	if ($metaentry{':copyright'} eq 'custom') {
12139: 
12140:     #
12141:     # Importing a rights file here
12142:     #
12143: 	    unless ($depthcount) {
12144: 		my $location=$metaentry{':customdistributionfile'};
12145: 		my $dir=$filename;
12146: 		$dir=~s|[^/]*$||;
12147: 		$location=&filelocation($dir,$location);
12148: 		my $rights_metadata =
12149: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12150: 			      $depthcount+1);
12151: 		foreach my $rights (split(',',$rights_metadata)) {
12152: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12153: 		    $metathesekeys{$rights}=1;
12154: 		}
12155: 	    }
12156: 	}
12157: 	# uniqifiy package listing
12158: 	my %seen;
12159: 	my @uniq_packages =
12160: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12161: 	$metaentry{':packages'} = join(',',@uniq_packages);
12162: 
12163:         if (($importedresponses) || ($importedparts)) {
12164:             if ($importedparts) {
12165: # We had imported parts and need to rebuild partorder
12166:                 $metaentry{':partorder'}='';
12167:                 $metathesekeys{'partorder'}=1;
12168:             }
12169:             if ($importedresponses) {
12170: # We had imported responses and need to rebuil responseorder
12171:                 $metaentry{':responseorder'}='';
12172:                 $metathesekeys{'responseorder'}=1;
12173:             }
12174:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12175:                 my $origid = $origfiletagids[$index+1];
12176:                 if ($origfiletagids[$index] eq 'part') {
12177: # Original part, part of the problem
12178:                     if ($importedparts) {
12179:                         $metaentry{':partorder'}.=','.$origid;
12180:                     }
12181:                 } elsif ($origfiletagids[$index] eq 'import') {
12182:                     if ($importedparts) {
12183: # We have imported parts at this position
12184:                         if ($importedpartids{$origid} ne '') {
12185:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12186:                         }
12187:                     }
12188:                     if ($importedresponses) {
12189: # We have imported responses at this position
12190:                         if ($importedrespids{$origid} ne '') {
12191:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12192:                         }
12193:                     }
12194:                 } else {
12195: # Original response item, part of the problem
12196:                     if ($importedresponses) {
12197:                         $metaentry{':responseorder'}.=','.$origid;
12198:                     }
12199:                 }
12200:             }
12201:             if ($importedparts) {
12202:                 $metaentry{':partorder'}=~s/^\,//;
12203:             }
12204:             if ($importedresponses) {
12205:                 $metaentry{':responseorder'}=~s/^\,//;
12206:             }
12207:         }
12208: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12209: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12210: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12211:         unless ($liburi) {
12212: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12213:         }
12214: # this is the end of "was not already recently cached
12215:     }
12216:     return $metaentry{':'.$what};
12217: }
12218: 
12219: sub metadata_create_package_def {
12220:     my ($uri,$key,$package,$metathesekeys)=@_;
12221:     my ($pack,$name,$subp)=split(/\&/,$key);
12222:     if ($subp eq 'default') { next; }
12223:     
12224:     if (defined($metaentry{':packages'})) {
12225: 	$metaentry{':packages'}.=','.$package;
12226:     } else {
12227: 	$metaentry{':packages'}=$package;
12228:     }
12229:     my $value=$packagetab{$key};
12230:     my $unikey;
12231:     $unikey='parameter_0_'.$name;
12232:     $metaentry{':'.$unikey.'.part'}=0;
12233:     $$metathesekeys{$unikey}=1;
12234:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12235: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12236:     }
12237:     if (defined($metaentry{':'.$unikey.'.default'})) {
12238: 	$metaentry{':'.$unikey}=
12239: 	    $metaentry{':'.$unikey.'.default'};
12240:     }
12241: }
12242: 
12243: sub metadata_generate_part0 {
12244:     my ($metadata,$metacache,$uri) = @_;
12245:     my %allnames;
12246:     foreach my $metakey (keys(%$metadata)) {
12247: 	if ($metakey=~/^parameter\_(.*)/) {
12248: 	  my $part=$$metacache{':'.$metakey.'.part'};
12249: 	  my $name=$$metacache{':'.$metakey.'.name'};
12250: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12251: 	    $allnames{$name}=$part;
12252: 	  }
12253: 	}
12254:     }
12255:     foreach my $name (keys(%allnames)) {
12256:       $$metadata{"parameter_0_$name"}=1;
12257:       my $key=":parameter_0_$name";
12258:       $$metacache{"$key.part"}='0';
12259:       $$metacache{"$key.name"}=$name;
12260:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12261: 					   $allnames{$name}.'_'.$name.
12262: 					   '.type'};
12263:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12264: 			     '.display'};
12265:       my $expr='[Part: '.$allnames{$name}.']';
12266:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12267:       $$metacache{"$key.display"}=$olddis;
12268:     }
12269: }
12270: 
12271: # ------------------------------------------------------ Devalidate title cache
12272: 
12273: sub devalidate_title_cache {
12274:     my ($url)=@_;
12275:     if (!$env{'request.course.id'}) { return; }
12276:     my $symb=&symbread($url);
12277:     if (!$symb) { return; }
12278:     my $key=$env{'request.course.id'}."\0".$symb;
12279:     &devalidate_cache_new('title',$key);
12280: }
12281: 
12282: # ------------------------------------------------- Get the title of a course
12283: 
12284: sub current_course_title {
12285:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12286: }
12287: # ------------------------------------------------- Get the title of a resource
12288: 
12289: sub gettitle {
12290:     my $urlsymb=shift;
12291:     my $symb=&symbread($urlsymb);
12292:     if ($symb) {
12293: 	my $key=$env{'request.course.id'}."\0".$symb;
12294: 	my ($result,$cached)=&is_cached_new('title',$key);
12295: 	if (defined($cached)) { 
12296: 	    return $result;
12297: 	}
12298: 	my ($map,$resid,$url)=&decode_symb($symb);
12299: 	my $title='';
12300: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12301: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12302: 	} else {
12303: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12304: 		    &GDBM_READER(),0640)) {
12305: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12306: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12307: 		untie(%bighash);
12308: 	    }
12309: 	}
12310: 	$title=~s/\&colon\;/\:/gs;
12311: 	if ($title) {
12312: # Remember both $symb and $title for dynamic metadata
12313:             $accesshash{$symb.'___crstitle'}=$title;
12314:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12315: # Cache this title and then return it
12316: 	    return &do_cache_new('title',$key,$title,600);
12317: 	}
12318: 	$urlsymb=$url;
12319:     }
12320:     my $title=&metadata($urlsymb,'title');
12321:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12322:     return $title;
12323: }
12324: 
12325: sub get_slot {
12326:     my ($which,$cnum,$cdom)=@_;
12327:     if (!$cnum || !$cdom) {
12328: 	(undef,my $courseid)=&whichuser();
12329: 	$cdom=$env{'course.'.$courseid.'.domain'};
12330: 	$cnum=$env{'course.'.$courseid.'.num'};
12331:     }
12332:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12333:     my %slotinfo;
12334:     if (exists($remembered{$key})) {
12335: 	$slotinfo{$which} = $remembered{$key};
12336:     } else {
12337: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12338: 	&Apache::lonhomework::showhash(%slotinfo);
12339: 	my ($tmp)=keys(%slotinfo);
12340: 	if ($tmp=~/^error:/) { return (); }
12341: 	$remembered{$key} = $slotinfo{$which};
12342:     }
12343:     if (ref($slotinfo{$which}) eq 'HASH') {
12344: 	return %{$slotinfo{$which}};
12345:     }
12346:     return $slotinfo{$which};
12347: }
12348: 
12349: sub get_reservable_slots {
12350:     my ($cnum,$cdom,$uname,$udom) = @_;
12351:     my $now = time;
12352:     my $reservable_info;
12353:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12354:     if (exists($remembered{$key})) {
12355:         $reservable_info = $remembered{$key};
12356:     } else {
12357:         my %resv;
12358:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12359:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12360:         $reservable_info = \%resv;
12361:         $remembered{$key} = $reservable_info;
12362:     }
12363:     return $reservable_info;
12364: }
12365: 
12366: sub get_course_slots {
12367:     my ($cnum,$cdom) = @_;
12368:     my $hashid=$cnum.':'.$cdom;
12369:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12370:     if (defined($cached)) {
12371:         if (ref($result) eq 'HASH') {
12372:             return %{$result};
12373:         }
12374:     } else {
12375:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12376:         my ($tmp) = keys(%slots);
12377:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12378:             &do_cache_new('allslots',$hashid,\%slots,600);
12379:             return %slots;
12380:         }
12381:     }
12382:     return;
12383: }
12384: 
12385: sub devalidate_slots_cache {
12386:     my ($cnum,$cdom)=@_;
12387:     my $hashid=$cnum.':'.$cdom;
12388:     &devalidate_cache_new('allslots',$hashid);
12389: }
12390: 
12391: sub get_coursechange {
12392:     my ($cdom,$cnum) = @_;
12393:     if ($cdom eq '' || $cnum eq '') {
12394:         return unless ($env{'request.course.id'});
12395:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12396:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12397:     }
12398:     my $hashid=$cdom.'_'.$cnum;
12399:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12400:     if ((defined($cached)) && ($change ne '')) {
12401:         return $change;
12402:     } else {
12403:         my %crshash;
12404:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12405:         if ($crshash{'internal.contentchange'} eq '') {
12406:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12407:             if ($change eq '') {
12408:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12409:                 $change = $crshash{'internal.created'};
12410:             }
12411:         } else {
12412:             $change = $crshash{'internal.contentchange'};
12413:         }
12414:         my $cachetime = 600;
12415:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12416:     }
12417:     return $change;
12418: }
12419: 
12420: sub devalidate_coursechange_cache {
12421:     my ($cnum,$cdom)=@_;
12422:     my $hashid=$cnum.':'.$cdom;
12423:     &devalidate_cache_new('crschange',$hashid);
12424: }
12425: 
12426: # ------------------------------------------------- Update symbolic store links
12427: 
12428: sub symblist {
12429:     my ($mapname,%newhash)=@_;
12430:     $mapname=&deversion(&declutter($mapname));
12431:     my %hash;
12432:     if (($env{'request.course.fn'}) && (%newhash)) {
12433:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12434:                       &GDBM_WRCREAT(),0640)) {
12435: 	    foreach my $url (keys(%newhash)) {
12436: 		next if ($url eq 'last_known'
12437: 			 && $env{'form.no_update_last_known'});
12438: 		$hash{declutter($url)}=&encode_symb($mapname,
12439: 						    $newhash{$url}->[1],
12440: 						    $newhash{$url}->[0]);
12441:             }
12442:             if (untie(%hash)) {
12443: 		return 'ok';
12444:             }
12445:         }
12446:     }
12447:     return 'error';
12448: }
12449: 
12450: # --------------------------------------------------------------- Verify a symb
12451: 
12452: sub symbverify {
12453:     my ($symb,$thisurl,$encstate)=@_;
12454:     my $thisfn=$thisurl;
12455:     $thisfn=&declutter($thisfn);
12456: # direct jump to resource in page or to a sequence - will construct own symbs
12457:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12458: # check URL part
12459:     my ($map,$resid,$url)=&decode_symb($symb);
12460: 
12461:     unless ($url eq $thisfn) { return 0; }
12462: 
12463:     $symb=&symbclean($symb);
12464:     $thisurl=&deversion($thisurl);
12465:     $thisfn=&deversion($thisfn);
12466: 
12467:     my %bighash;
12468:     my $okay=0;
12469: 
12470:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12471:                             &GDBM_READER(),0640)) {
12472:         my $noclutter;
12473:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12474:             $thisurl =~ s/\?.+$//;
12475:             if ($map =~ m{^uploaded/.+\.page$}) {
12476:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12477:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12478:                 $noclutter = 1;
12479:             }
12480:         }
12481:         my $ids;
12482:         if ($noclutter) {
12483:             $ids=$bighash{'ids_'.$thisurl};
12484:         } else {
12485:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12486:         }
12487:         unless ($ids) {
12488:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12489:             $ids=$bighash{$idkey};
12490:         }
12491:         if ($ids) {
12492: # ------------------------------------------------------------------- Has ID(s)
12493:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12494:                 $symb =~ s/\?.+$//;
12495:             }
12496: 	    foreach my $id (split(/\,/,$ids)) {
12497: 	       my ($mapid,$resid)=split(/\./,$id);
12498:                if (
12499:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12500:    eq $symb) {
12501:                    if (ref($encstate)) {
12502:                        $$encstate = $bighash{'encrypted_'.$id};
12503:                    }
12504: 		   if (($env{'request.role.adv'}) ||
12505: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12506:                        ($thisurl eq '/adm/navmaps')) {
12507: 		       $okay=1;
12508:                        last;
12509: 		   }
12510: 	       }
12511: 	   }
12512:         }
12513: 	untie(%bighash);
12514:     }
12515:     return $okay;
12516: }
12517: 
12518: # --------------------------------------------------------------- Clean-up symb
12519: 
12520: sub symbclean {
12521:     my $symb=shift;
12522:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12523: # remove version from map
12524:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12525: 
12526: # remove version from URL
12527:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12528: 
12529: # remove wrapper
12530: 
12531:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12532:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12533:     return $symb;
12534: }
12535: 
12536: # ---------------------------------------------- Split symb to find map and url
12537: 
12538: sub encode_symb {
12539:     my ($map,$resid,$url)=@_;
12540:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12541: }
12542: 
12543: sub decode_symb {
12544:     my $symb=shift;
12545:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12546:     my ($map,$resid,$url)=split(/___/,$symb);
12547:     return (&fixversion($map),$resid,&fixversion($url));
12548: }
12549: 
12550: sub fixversion {
12551:     my $fn=shift;
12552:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12553:     my %bighash;
12554:     my $uri=&clutter($fn);
12555:     my $key=$env{'request.course.id'}.'_'.$uri;
12556: # is this cached?
12557:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12558:     if (defined($cached)) { return $result; }
12559: # unfortunately not cached, or expired
12560:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12561: 	    &GDBM_READER(),0640)) {
12562:  	if ($bighash{'version_'.$uri}) {
12563:  	    my $version=$bighash{'version_'.$uri};
12564:  	    unless (($version eq 'mostrecent') || 
12565: 		    ($version==&getversion($uri))) {
12566:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12567:  	    }
12568:  	}
12569:  	untie %bighash;
12570:     }
12571:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12572: }
12573: 
12574: sub deversion {
12575:     my $url=shift;
12576:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12577:     return $url;
12578: }
12579: 
12580: # ------------------------------------------------------ Return symb list entry
12581: 
12582: sub symbread {
12583:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12584:     my $cache_str='request.symbread.cached.'.$thisfn;
12585:     if (defined($env{$cache_str})) {
12586:         if ($ignorecachednull) {
12587:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12588:         } else {
12589:             return $env{$cache_str};
12590:         }
12591:     }
12592: # no filename provided? try from environment
12593:     unless ($thisfn) {
12594:         if ($env{'request.symb'}) {
12595: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12596: 	}
12597: 	$thisfn=$env{'request.filename'};
12598:     }
12599:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12600: # is that filename actually a symb? Verify, clean, and return
12601:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12602: 	if (&symbverify($thisfn,$1)) {
12603: 	    return $env{$cache_str}=&symbclean($thisfn);
12604: 	}
12605:     }
12606:     $thisfn=declutter($thisfn);
12607:     my %hash;
12608:     my %bighash;
12609:     my $syval='';
12610:     if (($env{'request.course.fn'}) && ($thisfn)) {
12611:         my $targetfn = $thisfn;
12612:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12613:             $targetfn = 'adm/wrapper/'.$thisfn;
12614:         }
12615: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12616: 	    $targetfn=$1;
12617: 	}
12618:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12619:                       &GDBM_READER(),0640)) {
12620: 	    $syval=$hash{$targetfn};
12621:             untie(%hash);
12622:         }
12623: # ---------------------------------------------------------- There was an entry
12624:         if ($syval) {
12625: 	    #unless ($syval=~/\_\d+$/) {
12626: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12627: 		    #&appenv({'request.ambiguous' => $thisfn});
12628: 		    #return $env{$cache_str}='';
12629: 		#}    
12630: 		#$syval.=$1;
12631: 	    #}
12632:         } else {
12633: # ------------------------------------------------------- Was not in symb table
12634:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12635:                             &GDBM_READER(),0640)) {
12636: # ---------------------------------------------- Get ID(s) for current resource
12637:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12638:               unless ($ids) { 
12639:                  $ids=$bighash{'ids_/'.$thisfn};
12640:               }
12641:               unless ($ids) {
12642: # alias?
12643: 		  $ids=$bighash{'mapalias_'.$thisfn};
12644:               }
12645:               if ($ids) {
12646: # ------------------------------------------------------------------- Has ID(s)
12647:                  my @possibilities=split(/\,/,$ids);
12648:                  if ($#possibilities==0) {
12649: # ----------------------------------------------- There is only one possibility
12650: 		     my ($mapid,$resid)=split(/\./,$ids);
12651: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12652: 						    $resid,$thisfn);
12653:                      if (ref($possibles) eq 'HASH') {
12654:                          $possibles->{$syval} = 1;    
12655:                      }
12656:                      if ($checkforblock) {
12657:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12658:                          if (@blockers) {
12659:                              $syval = '';
12660:                              return;
12661:                          }
12662:                      }
12663:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12664: # ------------------------------------------ There is more than one possibility
12665:                      my $realpossible=0;
12666:                      foreach my $id (@possibilities) {
12667: 			 my $file=$bighash{'src_'.$id};
12668:                          my $canaccess;
12669:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12670:                              $canaccess = 1;
12671:                          } else { 
12672:                              $canaccess = &allowed('bre',$file);
12673:                          }
12674:                          if ($canaccess) {
12675:          		     my ($mapid,$resid)=split(/\./,$id);
12676:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12677:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12678: 						             $resid,$thisfn);
12679:                                  if (ref($possibles) eq 'HASH') {
12680:                                      $possibles->{$syval} = 1;
12681:                                  }
12682:                                  if ($checkforblock) {
12683:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12684:                                      unless (@blockers > 0) {
12685:                                          $syval = $poss_syval;
12686:                                          $realpossible++;
12687:                                      }
12688:                                  } else {
12689:                                      $syval = $poss_syval;
12690:                                      $realpossible++;
12691:                                  }
12692:                              }
12693: 			 }
12694:                      }
12695: 		     if ($realpossible!=1) { $syval=''; }
12696:                  } else {
12697:                      $syval='';
12698:                  }
12699: 	      }
12700:               untie(%bighash);
12701:            }
12702:         }
12703:         if ($syval) {
12704: 	    return $env{$cache_str}=$syval;
12705:         }
12706:     }
12707:     &appenv({'request.ambiguous' => $thisfn});
12708:     return $env{$cache_str}='';
12709: }
12710: 
12711: # ---------------------------------------------------------- Return random seed
12712: 
12713: sub numval {
12714:     my $txt=shift;
12715:     $txt=~tr/A-J/0-9/;
12716:     $txt=~tr/a-j/0-9/;
12717:     $txt=~tr/K-T/0-9/;
12718:     $txt=~tr/k-t/0-9/;
12719:     $txt=~tr/U-Z/0-5/;
12720:     $txt=~tr/u-z/0-5/;
12721:     $txt=~s/\D//g;
12722:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12723:     return int($txt);
12724: }
12725: 
12726: sub numval2 {
12727:     my $txt=shift;
12728:     $txt=~tr/A-J/0-9/;
12729:     $txt=~tr/a-j/0-9/;
12730:     $txt=~tr/K-T/0-9/;
12731:     $txt=~tr/k-t/0-9/;
12732:     $txt=~tr/U-Z/0-5/;
12733:     $txt=~tr/u-z/0-5/;
12734:     $txt=~s/\D//g;
12735:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12736:     my $total;
12737:     foreach my $val (@txts) { $total+=$val; }
12738:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12739:     return int($total);
12740: }
12741: 
12742: sub numval3 {
12743:     use integer;
12744:     my $txt=shift;
12745:     $txt=~tr/A-J/0-9/;
12746:     $txt=~tr/a-j/0-9/;
12747:     $txt=~tr/K-T/0-9/;
12748:     $txt=~tr/k-t/0-9/;
12749:     $txt=~tr/U-Z/0-5/;
12750:     $txt=~tr/u-z/0-5/;
12751:     $txt=~s/\D//g;
12752:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12753:     my $total;
12754:     foreach my $val (@txts) { $total+=$val; }
12755:     if ($_64bit) { $total=(($total<<32)>>32); }
12756:     return $total;
12757: }
12758: 
12759: sub digest {
12760:     my ($data)=@_;
12761:     my $digest=&Digest::MD5::md5($data);
12762:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12763:     my ($e,$f);
12764:     {
12765:         use integer;
12766:         $e=($a+$b);
12767:         $f=($c+$d);
12768:         if ($_64bit) {
12769:             $e=(($e<<32)>>32);
12770:             $f=(($f<<32)>>32);
12771:         }
12772:     }
12773:     if (wantarray) {
12774: 	return ($e,$f);
12775:     } else {
12776: 	my $g;
12777: 	{
12778: 	    use integer;
12779: 	    $g=($e+$f);
12780: 	    if ($_64bit) {
12781: 		$g=(($g<<32)>>32);
12782: 	    }
12783: 	}
12784: 	return $g;
12785:     }
12786: }
12787: 
12788: sub latest_rnd_algorithm_id {
12789:     return '64bit5';
12790: }
12791: 
12792: sub get_rand_alg {
12793:     my ($courseid)=@_;
12794:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12795:     if ($courseid) {
12796: 	return $env{"course.$courseid.rndseed"};
12797:     }
12798:     return &latest_rnd_algorithm_id();
12799: }
12800: 
12801: sub validCODE {
12802:     my ($CODE)=@_;
12803:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12804:     return 0;
12805: }
12806: 
12807: sub getCODE {
12808:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12809:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12810: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12811: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12812: 	return $Apache::lonhomework::history{'resource.CODE'};
12813:     }
12814:     return undef;
12815: }
12816: #
12817: #  Determines the random seed for a specific context:
12818: #
12819: # parameters:
12820: #   symb      - in course context the symb for the seed.
12821: #   course_id - The course id of the form domain_coursenum.
12822: #   domain    - Domain for the user.
12823: #   course    - Course for the user.
12824: #   cenv      - environment of the course.
12825: #
12826: # NOTE:
12827: #   All parameters are picked out of the environment if missing
12828: #   or not defined.
12829: #   If a symb cannot be determined the current time is used instead.
12830: #
12831: #  For a given well defined symb, courside, domain, username,
12832: #  and course environment, the seed is reproducible.
12833: #
12834: sub rndseed {
12835:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12836:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12837:     if (!defined($symb)) {
12838: 	unless ($symb=$wsymb) { return time; }
12839:     }
12840:     if (!defined $courseid) { 
12841: 	$courseid=$wcourseid; 
12842:     }
12843:     if (!defined $domain) { $domain=$wdomain; }
12844:     if (!defined $username) { $username=$wusername }
12845: 
12846:     my $which;
12847:     if (defined($cenv->{'rndseed'})) {
12848: 	$which = $cenv->{'rndseed'};
12849:     } else {
12850: 	$which =&get_rand_alg($courseid);
12851:     }
12852:     if (defined(&getCODE())) {
12853: 
12854: 	if ($which eq '64bit5') {
12855: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12856: 	} elsif ($which eq '64bit4') {
12857: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12858: 	} else {
12859: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12860: 	}
12861:     } elsif ($which eq '64bit5') {
12862: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12863:     } elsif ($which eq '64bit4') {
12864: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12865:     } elsif ($which eq '64bit3') {
12866: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12867:     } elsif ($which eq '64bit2') {
12868: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12869:     } elsif ($which eq '64bit') {
12870: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12871:     }
12872:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12873: }
12874: 
12875: sub rndseed_32bit {
12876:     my ($symb,$courseid,$domain,$username)=@_;
12877:     {
12878: 	use integer;
12879: 	my $symbchck=unpack("%32C*",$symb) << 27;
12880: 	my $symbseed=numval($symb) << 22;
12881: 	my $namechck=unpack("%32C*",$username) << 17;
12882: 	my $nameseed=numval($username) << 12;
12883: 	my $domainseed=unpack("%32C*",$domain) << 7;
12884: 	my $courseseed=unpack("%32C*",$courseid);
12885: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12886: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12887: 	#&logthis("rndseed :$num:$symb");
12888: 	if ($_64bit) { $num=(($num<<32)>>32); }
12889: 	return $num;
12890:     }
12891: }
12892: 
12893: sub rndseed_64bit {
12894:     my ($symb,$courseid,$domain,$username)=@_;
12895:     {
12896: 	use integer;
12897: 	my $symbchck=unpack("%32S*",$symb) << 21;
12898: 	my $symbseed=numval($symb) << 10;
12899: 	my $namechck=unpack("%32S*",$username);
12900: 	
12901: 	my $nameseed=numval($username) << 21;
12902: 	my $domainseed=unpack("%32S*",$domain) << 10;
12903: 	my $courseseed=unpack("%32S*",$courseid);
12904: 	
12905: 	my $num1=$symbchck+$symbseed+$namechck;
12906: 	my $num2=$nameseed+$domainseed+$courseseed;
12907: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12908: 	#&logthis("rndseed :$num:$symb");
12909: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12910: 	return "$num1,$num2";
12911:     }
12912: }
12913: 
12914: sub rndseed_64bit2 {
12915:     my ($symb,$courseid,$domain,$username)=@_;
12916:     {
12917: 	use integer;
12918: 	# strings need to be an even # of cahracters long, it it is odd the
12919:         # last characters gets thrown away
12920: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12921: 	my $symbseed=numval($symb) << 10;
12922: 	my $namechck=unpack("%32S*",$username.' ');
12923: 	
12924: 	my $nameseed=numval($username) << 21;
12925: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12926: 	my $courseseed=unpack("%32S*",$courseid.' ');
12927: 	
12928: 	my $num1=$symbchck+$symbseed+$namechck;
12929: 	my $num2=$nameseed+$domainseed+$courseseed;
12930: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12931: 	#&logthis("rndseed :$num:$symb");
12932: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12933: 	return "$num1,$num2";
12934:     }
12935: }
12936: 
12937: sub rndseed_64bit3 {
12938:     my ($symb,$courseid,$domain,$username)=@_;
12939:     {
12940: 	use integer;
12941: 	# strings need to be an even # of cahracters long, it it is odd the
12942:         # last characters gets thrown away
12943: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12944: 	my $symbseed=numval2($symb) << 10;
12945: 	my $namechck=unpack("%32S*",$username.' ');
12946: 	
12947: 	my $nameseed=numval2($username) << 21;
12948: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12949: 	my $courseseed=unpack("%32S*",$courseid.' ');
12950: 	
12951: 	my $num1=$symbchck+$symbseed+$namechck;
12952: 	my $num2=$nameseed+$domainseed+$courseseed;
12953: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12954: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12955: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12956: 	
12957: 	return "$num1:$num2";
12958:     }
12959: }
12960: 
12961: sub rndseed_64bit4 {
12962:     my ($symb,$courseid,$domain,$username)=@_;
12963:     {
12964: 	use integer;
12965: 	# strings need to be an even # of cahracters long, it it is odd the
12966:         # last characters gets thrown away
12967: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12968: 	my $symbseed=numval3($symb) << 10;
12969: 	my $namechck=unpack("%32S*",$username.' ');
12970: 	
12971: 	my $nameseed=numval3($username) << 21;
12972: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12973: 	my $courseseed=unpack("%32S*",$courseid.' ');
12974: 	
12975: 	my $num1=$symbchck+$symbseed+$namechck;
12976: 	my $num2=$nameseed+$domainseed+$courseseed;
12977: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12978: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12979: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12980: 	
12981: 	return "$num1:$num2";
12982:     }
12983: }
12984: 
12985: sub rndseed_64bit5 {
12986:     my ($symb,$courseid,$domain,$username)=@_;
12987:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12988:     return "$num1:$num2";
12989: }
12990: 
12991: sub rndseed_CODE_64bit {
12992:     my ($symb,$courseid,$domain,$username)=@_;
12993:     {
12994: 	use integer;
12995: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12996: 	my $symbseed=numval2($symb);
12997: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12998: 	my $CODEseed=numval(&getCODE());
12999: 	my $courseseed=unpack("%32S*",$courseid.' ');
13000: 	my $num1=$symbseed+$CODEchck;
13001: 	my $num2=$CODEseed+$courseseed+$symbchck;
13002: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13003: 	#&logthis("rndseed :$num1:$num2:$symb");
13004: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13005: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13006: 	return "$num1:$num2";
13007:     }
13008: }
13009: 
13010: sub rndseed_CODE_64bit4 {
13011:     my ($symb,$courseid,$domain,$username)=@_;
13012:     {
13013: 	use integer;
13014: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13015: 	my $symbseed=numval3($symb);
13016: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13017: 	my $CODEseed=numval3(&getCODE());
13018: 	my $courseseed=unpack("%32S*",$courseid.' ');
13019: 	my $num1=$symbseed+$CODEchck;
13020: 	my $num2=$CODEseed+$courseseed+$symbchck;
13021: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13022: 	#&logthis("rndseed :$num1:$num2:$symb");
13023: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13024: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13025: 	return "$num1:$num2";
13026:     }
13027: }
13028: 
13029: sub rndseed_CODE_64bit5 {
13030:     my ($symb,$courseid,$domain,$username)=@_;
13031:     my $code = &getCODE();
13032:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13033:     return "$num1:$num2";
13034: }
13035: 
13036: sub setup_random_from_rndseed {
13037:     my ($rndseed)=@_;
13038:     if ($rndseed =~/([,:])/) {
13039:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13040:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13041:             &Math::Random::random_set_seed_from_phrase($rndseed);
13042:         } else {
13043:             &Math::Random::random_set_seed($num1,$num2);
13044:         }
13045:     } else {
13046: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13047:     }
13048: }
13049: 
13050: sub latest_receipt_algorithm_id {
13051:     return 'receipt3';
13052: }
13053: 
13054: sub recunique {
13055:     my $fucourseid=shift;
13056:     my $unique;
13057:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13058: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13059: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13060:     } else {
13061: 	$unique=$perlvar{'lonReceipt'};
13062:     }
13063:     return unpack("%32C*",$unique);
13064: }
13065: 
13066: sub recprefix {
13067:     my $fucourseid=shift;
13068:     my $prefix;
13069:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13070: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13071: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13072:     } else {
13073: 	$prefix=$perlvar{'lonHostID'};
13074:     }
13075:     return unpack("%32C*",$prefix);
13076: }
13077: 
13078: sub ireceipt {
13079:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13080: 
13081:     my $return =&recprefix($fucourseid).'-';
13082: 
13083:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13084: 	$env{'request.state'} eq 'construct') {
13085: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13086: 	return $return;
13087:     }
13088: 
13089:     my $cuname=unpack("%32C*",$funame);
13090:     my $cudom=unpack("%32C*",$fudom);
13091:     my $cucourseid=unpack("%32C*",$fucourseid);
13092:     my $cusymb=unpack("%32C*",$fusymb);
13093:     my $cunique=&recunique($fucourseid);
13094:     my $cpart=unpack("%32S*",$part);
13095:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13096: 
13097: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13098: 			       
13099: 	$return.= ($cunique%$cuname+
13100: 		   $cunique%$cudom+
13101: 		   $cusymb%$cuname+
13102: 		   $cusymb%$cudom+
13103: 		   $cucourseid%$cuname+
13104: 		   $cucourseid%$cudom+
13105: 		   $cpart%$cuname+
13106: 		   $cpart%$cudom);
13107:     } else {
13108: 	$return.= ($cunique%$cuname+
13109: 		   $cunique%$cudom+
13110: 		   $cusymb%$cuname+
13111: 		   $cusymb%$cudom+
13112: 		   $cucourseid%$cuname+
13113: 		   $cucourseid%$cudom);
13114:     }
13115:     return $return;
13116: }
13117: 
13118: sub receipt {
13119:     my ($part)=@_;
13120:     my ($symb,$courseid,$domain,$name) = &whichuser();
13121:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13122: }
13123: 
13124: sub whichuser {
13125:     my ($passedsymb)=@_;
13126:     my ($symb,$courseid,$domain,$name,$publicuser);
13127:     if (defined($env{'form.grade_symb'})) {
13128: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13129: 	my $allowed=&allowed('vgr',$tmp_courseid);
13130: 	if (!$allowed &&
13131: 	    exists($env{'request.course.sec'}) &&
13132: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13133: 	    $allowed=&allowed('vgr',$tmp_courseid.
13134: 			      '/'.$env{'request.course.sec'});
13135: 	}
13136: 	if ($allowed) {
13137: 	    ($symb)=&get_env_multiple('form.grade_symb');
13138: 	    $courseid=$tmp_courseid;
13139: 	    ($domain)=&get_env_multiple('form.grade_domain');
13140: 	    ($name)=&get_env_multiple('form.grade_username');
13141: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13142: 	}
13143:     }
13144:     if (!$passedsymb) {
13145: 	$symb=&symbread();
13146:     } else {
13147: 	$symb=$passedsymb;
13148:     }
13149:     $courseid=$env{'request.course.id'};
13150:     $domain=$env{'user.domain'};
13151:     $name=$env{'user.name'};
13152:     if ($name eq 'public' && $domain eq 'public') {
13153: 	if (!defined($env{'form.username'})) {
13154: 	    $env{'form.username'}.=time.rand(10000000);
13155: 	}
13156: 	$name.=$env{'form.username'};
13157:     }
13158:     return ($symb,$courseid,$domain,$name,$publicuser);
13159: 
13160: }
13161: 
13162: # ------------------------------------------------------------ Serves up a file
13163: # returns either the contents of the file or 
13164: # -1 if the file doesn't exist
13165: #
13166: # if the target is a file that was uploaded via DOCS, 
13167: # a check will be made to see if a current copy exists on the local server,
13168: # if it does this will be served, otherwise a copy will be retrieved from
13169: # the home server for the course and stored in /home/httpd/html/userfiles on
13170: # the local server.   
13171: 
13172: sub getfile {
13173:     my ($file) = @_;
13174:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13175:     &repcopy($file);
13176:     return &readfile($file);
13177: }
13178: 
13179: sub repcopy_userfile {
13180:     my ($file)=@_;
13181:     my $londocroot = $perlvar{'lonDocRoot'};
13182:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13183:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13184:     my ($cdom,$cnum,$filename) = 
13185: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13186:     my $uri="/uploaded/$cdom/$cnum/$filename";
13187:     if (-e "$file") {
13188: # we already have a local copy, check it out
13189: 	my @fileinfo = stat($file);
13190: 	my $rtncode;
13191: 	my $info;
13192: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13193: 	if ($lwpresp ne 'ok') {
13194: # there is no such file anymore, even though we had a local copy
13195: 	    if ($rtncode eq '404') {
13196: 		unlink($file);
13197: 	    }
13198: 	    return -1;
13199: 	}
13200: 	if ($info < $fileinfo[9]) {
13201: # nice, the file we have is up-to-date, just say okay
13202: 	    return 'ok';
13203: 	} else {
13204: # the file is outdated, get rid of it
13205: 	    unlink($file);
13206: 	}
13207:     }
13208: # one way or the other, at this point, we don't have the file
13209: # construct the correct path for the file
13210:     my @parts = ($cdom,$cnum); 
13211:     if ($filename =~ m|^(.+)/[^/]+$|) {
13212: 	push @parts, split(/\//,$1);
13213:     }
13214:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13215:     foreach my $part (@parts) {
13216: 	$path .= '/'.$part;
13217: 	if (!-e $path) {
13218: 	    mkdir($path,0770);
13219: 	}
13220:     }
13221: # now the path exists for sure
13222: # get a user agent
13223:     my $transferfile=$file.'.in.transfer';
13224: # FIXME: this should flock
13225:     if (-e $transferfile) { return 'ok'; }
13226:     my $request;
13227:     $uri=~s/^\///;
13228:     my $homeserver = &homeserver($cnum,$cdom);
13229:     my $protocol = $protocol{$homeserver};
13230:     $protocol = 'http' if ($protocol ne 'https');
13231:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
13232:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13233: # did it work?
13234:     if ($response->is_error()) {
13235: 	unlink($transferfile);
13236: 	&logthis("Userfile repcopy failed for $uri");
13237: 	return -1;
13238:     }
13239: # worked, rename the transfer file
13240:     rename($transferfile,$file);
13241:     return 'ok';
13242: }
13243: 
13244: sub tokenwrapper {
13245:     my $uri=shift;
13246:     $uri=~s|^https?\://([^/]+)||;
13247:     $uri=~s|^/||;
13248:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13249:     my $token=$1;
13250:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13251:     if ($udom && $uname && $file) {
13252: 	$file=~s|(\?\.*)*$||;
13253:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13254:         my $homeserver = &homeserver($uname,$udom);
13255:         my $protocol = $protocol{$homeserver};
13256:         $protocol = 'http' if ($protocol ne 'https');
13257:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
13258:                (($uri=~/\?/)?'&':'?').'token='.$token.
13259:                                '&tokenissued='.$perlvar{'lonHostID'};
13260:     } else {
13261:         return '/adm/notfound.html';
13262:     }
13263: }
13264: 
13265: # call with reqtype HEAD: get last modification time
13266: # call with reqtype GET: get the file contents
13267: # Do not call this with reqtype GET for large files! It loads everything into memory
13268: #
13269: sub getuploaded {
13270:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13271:     $uri=~s/^\///;
13272:     my $homeserver = &homeserver($cnum,$cdom);
13273:     my $protocol = $protocol{$homeserver};
13274:     $protocol = 'http' if ($protocol ne 'https');
13275:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
13276:     my $request=new HTTP::Request($reqtype,$uri);
13277:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13278:     $$rtncode = $response->code;
13279:     if (! $response->is_success()) {
13280: 	return 'failed';
13281:     }      
13282:     if ($reqtype eq 'HEAD') {
13283: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13284:     } elsif ($reqtype eq 'GET') {
13285: 	$$info = $response->content;
13286:     }
13287:     return 'ok';
13288: }
13289: 
13290: sub readfile {
13291:     my $file = shift;
13292:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13293:     my $fh;
13294:     open($fh,"<",$file);
13295:     my $a='';
13296:     while (my $line = <$fh>) { $a .= $line; }
13297:     return $a;
13298: }
13299: 
13300: sub filelocation {
13301:     my ($dir,$file) = @_;
13302:     my $location;
13303:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13304: 
13305:     if ($file =~ m-^/adm/-) {
13306: 	$file=~s-^/adm/wrapper/-/-;
13307: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13308:     }
13309: 
13310:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13311:         $location = $file;
13312:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13313:         my ($udom,$uname,$filename)=
13314:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13315:         my $home=&homeserver($uname,$udom);
13316:         my $is_me=0;
13317:         my @ids=&current_machine_ids();
13318:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13319:         if ($is_me) {
13320:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13321:         } else {
13322:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13323:   	      $udom.'/'.$uname.'/'.$filename;
13324:         }
13325:     } elsif ($file =~ m-^/adm/-) {
13326: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13327:     } else {
13328:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13329:         $file=~s:^/(res|priv)/:/:;
13330:         my $space=$1;
13331:         if ( !( $file =~ m:^/:) ) {
13332:             $location = $dir. '/'.$file;
13333:         } else {
13334:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13335:         }
13336:     }
13337:     $location=~s://+:/:g; # remove duplicate /
13338:     while ($location=~m{/\.\./}) {
13339: 	if ($location =~ m{/[^/]+/\.\./}) {
13340: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13341: 	} else {
13342: 	    $location=~ s{/\.\./}{/}g;
13343: 	}
13344:     } #remove dir/..
13345:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13346:     return $location;
13347: }
13348: 
13349: sub hreflocation {
13350:     my ($dir,$file)=@_;
13351:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13352: 	$file=filelocation($dir,$file);
13353:     } elsif ($file=~m-^/adm/-) {
13354: 	$file=~s-^/adm/wrapper/-/-;
13355: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13356:     }
13357:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13358: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13359:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13360: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13361: 	        {/uploaded/$1/$2/}x;
13362:     }
13363:     if ($file=~ m{^/userfiles/}) {
13364: 	$file =~ s{^/userfiles/}{/uploaded/};
13365:     }
13366:     return $file;
13367: }
13368: 
13369: 
13370: 
13371: 
13372: 
13373: sub current_machine_domains {
13374:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13375: }
13376: 
13377: sub machine_domains {
13378:     my ($hostname) = @_;
13379:     my @domains;
13380:     my %hostname = &all_hostnames();
13381:     while( my($id, $name) = each(%hostname)) {
13382: #	&logthis("-$id-$name-$hostname-");
13383: 	if ($hostname eq $name) {
13384: 	    push(@domains,&host_domain($id));
13385: 	}
13386:     }
13387:     return @domains;
13388: }
13389: 
13390: sub current_machine_ids {
13391:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13392: }
13393: 
13394: sub machine_ids {
13395:     my ($hostname) = @_;
13396:     $hostname ||= &hostname($perlvar{'lonHostID'});
13397:     my @ids;
13398:     my %name_to_host = &all_names();
13399:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13400: 	return @{ $name_to_host{$hostname} };
13401:     }
13402:     return;
13403: }
13404: 
13405: sub additional_machine_domains {
13406:     my @domains;
13407:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13408:     while( my $line = <$fh>) {
13409:         $line =~ s/\s//g;
13410:         push(@domains,$line);
13411:     }
13412:     return @domains;
13413: }
13414: 
13415: sub default_login_domain {
13416:     my $domain = $perlvar{'lonDefDomain'};
13417:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13418:     foreach my $posdom (&current_machine_domains(),
13419:                         &additional_machine_domains()) {
13420:         if (lc($posdom) eq lc($testdomain)) {
13421:             $domain=$posdom;
13422:             last;
13423:         }
13424:     }
13425:     return $domain;
13426: }
13427: 
13428: # ------------------------------------------------------------- Declutters URLs
13429: 
13430: sub declutter {
13431:     my $thisfn=shift;
13432:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13433:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13434:         $thisfn=~s{^/home/httpd/html}{};
13435:     }
13436:     $thisfn=~s/^\///;
13437:     $thisfn=~s|^adm/wrapper/||;
13438:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13439:     $thisfn=~s/^res\///;
13440:     $thisfn=~s/^priv\///;
13441:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13442:         $thisfn=~s/\?.+$//;
13443:     }
13444:     return $thisfn;
13445: }
13446: 
13447: # ------------------------------------------------------------- Clutter up URLs
13448: 
13449: sub clutter {
13450:     my $thisfn='/'.&declutter(shift);
13451:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13452: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13453:        $thisfn='/res'.$thisfn; 
13454:     }
13455:     if ($thisfn !~m|^/adm|) {
13456: 	if ($thisfn =~ m|^/ext/|) {
13457: 	    $thisfn='/adm/wrapper'.$thisfn;
13458: 	} else {
13459: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13460: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13461: 	    if ($embstyle eq 'ssi'
13462: 		|| ($embstyle eq 'hdn')
13463: 		|| ($embstyle eq 'rat')
13464: 		|| ($embstyle eq 'prv')
13465: 		|| ($embstyle eq 'ign')) {
13466: 		#do nothing with these
13467: 	    } elsif (($embstyle eq 'img') 
13468: 		|| ($embstyle eq 'emb')
13469: 		|| ($embstyle eq 'wrp')) {
13470: 		$thisfn='/adm/wrapper'.$thisfn;
13471: 	    } elsif ($embstyle eq 'unk'
13472: 		     && $thisfn!~/\.(sequence|page)$/) {
13473: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13474: 	    } else {
13475: #		&logthis("Got a blank emb style");
13476: 	    }
13477: 	}
13478:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13479:         $thisfn='/adm/wrapper'.$thisfn;
13480:     }
13481:     return $thisfn;
13482: }
13483: 
13484: sub clutter_with_no_wrapper {
13485:     my $uri = &clutter(shift);
13486:     if ($uri =~ m-^/adm/-) {
13487: 	$uri =~ s-^/adm/wrapper/-/-;
13488: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13489:     }
13490:     return $uri;
13491: }
13492: 
13493: sub freeze_escape {
13494:     my ($value)=@_;
13495:     if (ref($value)) {
13496: 	$value=&nfreeze($value);
13497: 	return '__FROZEN__'.&escape($value);
13498:     }
13499:     return &escape($value);
13500: }
13501: 
13502: 
13503: sub thaw_unescape {
13504:     my ($value)=@_;
13505:     if ($value =~ /^__FROZEN__/) {
13506: 	substr($value,0,10,undef);
13507: 	$value=&unescape($value);
13508: 	return &thaw($value);
13509:     }
13510:     return &unescape($value);
13511: }
13512: 
13513: sub correct_line_ends {
13514:     my ($result)=@_;
13515:     $$result =~s/\r\n/\n/mg;
13516:     $$result =~s/\r/\n/mg;
13517: }
13518: # ================================================================ Main Program
13519: 
13520: sub goodbye {
13521:    &logthis("Starting Shut down");
13522: #not converted to using infrastruture and probably shouldn't be
13523:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13524: #converted
13525: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13526:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13527: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13528: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13529: #1.1 only
13530: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13531: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13532: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13533: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13534:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13535:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13536:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13537:    &flushcourselogs();
13538:    &logthis("Shutting down");
13539: }
13540: 
13541: sub get_dns {
13542:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13543:     if (!$ignore_cache) {
13544: 	my ($content,$cached)=
13545: 	    &Apache::lonnet::is_cached_new('dns',$url);
13546: 	if ($cached) {
13547: 	    &$func($content,$hashref);
13548: 	    return;
13549: 	}
13550:     }
13551: 
13552:     my %alldns;
13553:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13554:         foreach my $dns (<$config>) {
13555: 	    next if ($dns !~ /^\^(\S*)/x);
13556:             my $line = $1;
13557:             my ($host,$protocol) = split(/:/,$line);
13558:             if ($protocol ne 'https') {
13559:                 $protocol = 'http';
13560:             }
13561: 	    $alldns{$host} = $protocol;
13562:         }
13563:         close($config);
13564:     }
13565:     while (%alldns) {
13566: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13567: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13568:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13569:         delete($alldns{$dns});
13570: 	next if ($response->is_error());
13571:         if ($url eq '/adm/dns/loncapaCRL') {
13572:             return &$func($response);
13573:         } else {
13574: 	    my @content = split("\n",$response->content);
13575: 	    unless ($nocache) {
13576: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
13577: 	    }
13578: 	    &$func(\@content,$hashref);
13579:             return;
13580:         }
13581:     }
13582:     my $which = (split('/',$url,4))[3];
13583:     if ($which eq 'loncapaCRL') {
13584:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13585:         if (-e $diskfile) {
13586:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
13587:         } else {
13588:             &logthis("unable to contact DNS, no on disk file $diskfile available");
13589:         }
13590:     } else {
13591:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13592:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13593:             my @content = <$config>;
13594:             close($config);
13595:             &$func(\@content,$hashref);
13596:         }
13597:     }
13598:     return;
13599: }
13600: 
13601: # ------------------------------------------------------Get DNS checksums file
13602: sub parse_dns_checksums_tab {
13603:     my ($lines,$hashref) = @_;
13604:     my $lonhost = $perlvar{'lonHostID'};
13605:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13606:     my $loncaparev = &get_server_loncaparev($machine_dom);
13607:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13608:     my $webconfdir = '/etc/httpd/conf';
13609:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13610:         $webconfdir = '/etc/apache2';
13611:     } elsif ($distro =~ /^sles(\d+)$/) {
13612:         if ($1 >= 10) {
13613:             $webconfdir = '/etc/apache2';
13614:         }
13615:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13616:         if ($1 >= 10.0) {
13617:             $webconfdir = '/etc/apache2';
13618:         }
13619:     }
13620:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13621:     my (%chksum,%revnum);
13622:     if (ref($lines) eq 'ARRAY') {
13623:         chomp(@{$lines});
13624:         my $version = shift(@{$lines});
13625:         if ($version eq $release) {  
13626:             foreach my $line (@{$lines}) {
13627:                 my ($file,$version,$shasum) = split(/,/,$line);
13628:                 if ($file =~ m{^/etc/httpd/conf}) {
13629:                     if ($webconfdir eq '/etc/apache2') {
13630:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13631:                     }
13632:                 }
13633:                 $chksum{$file} = $shasum;
13634:                 $revnum{$file} = $version;
13635:             }
13636:             if (ref($hashref) eq 'HASH') {
13637:                 %{$hashref} = (
13638:                                 sums     => \%chksum,
13639:                                 versions => \%revnum,
13640:                               );
13641:             }
13642:         }
13643:     }
13644:     return;
13645: }
13646: 
13647: sub fetch_dns_checksums {
13648:     my %checksums;
13649:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13650:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13651:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13652:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13653:              \%checksums);
13654:     return \%checksums;
13655: }
13656: 
13657: sub fetch_crl_pemfile {
13658:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
13659: }
13660: 
13661: sub save_crl_pem {
13662:     my ($response) = @_;
13663:     my ($msg,$hadchanges);
13664:     if (ref($response)) {
13665:         my $now = time;
13666:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
13667:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
13668:         if (open(my $fh,'>',"$tmpcrl")) {
13669:             print $fh $response->content;
13670:             close($fh);
13671:             if (-e $lonca) {
13672:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
13673:                     my $check = <PIPE>;
13674:                     close(PIPE);
13675:                     chomp($check);
13676:                     if ($check eq 'verify OK') {
13677:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13678:                         my $backup;
13679:                         if (-e $dest) {
13680:                             if (&File::Copy::move($dest,"$dest.bak")) {
13681:                                 $backup = 'ok';
13682:                             }
13683:                         }
13684:                         if (&File::Copy::move($tmpcrl,$dest)) {
13685:                             $msg = 'ok';
13686:                             if ($backup) {
13687:                                 my (%oldnums,%newnums);
13688:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
13689:                                     while (<PIPE>) {
13690:                                         $oldnums{(split(/:/))[1]} = 1;
13691:                                     }
13692:                                     close(PIPE);
13693:                                 }
13694:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
13695:                                     while(<PIPE>) {
13696:                                         $newnums{(split(/:/))[1]} = 1;
13697:                                     }
13698:                                     close(PIPE);
13699:                                 }
13700:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
13701:                                     unless (exists($oldnums{$key})) {
13702:                                         $hadchanges = 1;
13703:                                         last;
13704:                                     }
13705:                                 }
13706:                                 unless ($hadchanges) {
13707:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
13708:                                         unless (exists($newnums{$key})) {
13709:                                             $hadchanges = 1;
13710:                                             last;
13711:                                         }
13712:                                     }
13713:                                 }
13714:                             }
13715:                         }
13716:                     } else {
13717:                         unlink($tmpcrl);
13718:                     }
13719:                 } else {
13720:                     unlink($tmpcrl);
13721:                 }
13722:             } else {
13723:                 unlink($tmpcrl);
13724:             }
13725:         }
13726:     }
13727:     return ($msg,$hadchanges);
13728: }
13729: 
13730: # ------------------------------------------------------------ Read domain file
13731: {
13732:     my $loaded;
13733:     my %domain;
13734: 
13735:     sub parse_domain_tab {
13736: 	my ($lines) = @_;
13737: 	foreach my $line (@$lines) {
13738: 	    next if ($line =~ /^(\#|\s*$ )/x);
13739: 
13740: 	    chomp($line);
13741: 	    my ($name,@elements) = split(/:/,$line,9);
13742: 	    my %this_domain;
13743: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13744: 			       'lang_def', 'city', 'longi', 'lati',
13745: 			       'primary') {
13746: 		$this_domain{$field} = shift(@elements);
13747: 	    }
13748: 	    $domain{$name} = \%this_domain;
13749: 	}
13750:     }
13751: 
13752:     sub reset_domain_info {
13753: 	undef($loaded);
13754: 	undef(%domain);
13755:     }
13756: 
13757:     sub load_domain_tab {
13758: 	my ($ignore_cache,$nocache) = @_;
13759: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13760: 	my $fh;
13761: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13762: 	    my @lines = <$fh>;
13763: 	    &parse_domain_tab(\@lines);
13764: 	}
13765: 	close($fh);
13766: 	$loaded = 1;
13767:     }
13768: 
13769:     sub domain {
13770: 	&load_domain_tab() if (!$loaded);
13771: 
13772: 	my ($name,$what) = @_;
13773: 	return if ( !exists($domain{$name}) );
13774: 
13775: 	if (!$what) {
13776: 	    return $domain{$name}{'description'};
13777: 	}
13778: 	return $domain{$name}{$what};
13779:     }
13780: 
13781:     sub domain_info {
13782:         &load_domain_tab() if (!$loaded);
13783:         return %domain;
13784:     }
13785: 
13786: }
13787: 
13788: 
13789: # ------------------------------------------------------------- Read hosts file
13790: {
13791:     my %hostname;
13792:     my %hostdom;
13793:     my %libserv;
13794:     my $loaded;
13795:     my %name_to_host;
13796:     my %internetdom;
13797:     my %LC_dns_serv;
13798: 
13799:     sub parse_hosts_tab {
13800: 	my ($file) = @_;
13801: 	foreach my $configline (@$file) {
13802: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13803:             chomp($configline);
13804: 	    if ($configline =~ /^\^/) {
13805:                 if ($configline =~ /^\^([\w.\-]+)/) {
13806:                     $LC_dns_serv{$1} = 1;
13807:                 }
13808:                 next;
13809:             }
13810: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13811: 	    $name=~s/\s//g;
13812: 	    if ($id && $domain && $role && $name) {
13813:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13814:                     my $curr = $hostname{$id};
13815:                     my $skip;
13816:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13817:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13818:                             $skip = 1;
13819:                         } else {
13820:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13821:                         }
13822:                     }
13823:                     unless ($skip) {
13824:                         push(@{$name_to_host{$name}},$id);
13825:                     }
13826:                 } else {
13827:                     push(@{$name_to_host{$name}},$id);
13828:                 }
13829: 		$hostname{$id}=$name;
13830: 		$hostdom{$id}=$domain;
13831: 		if ($role eq 'library') { $libserv{$id}=$name; }
13832:                 if (defined($protocol)) {
13833:                     if ($protocol eq 'https') {
13834:                         $protocol{$id} = $protocol;
13835:                     } else {
13836:                         $protocol{$id} = 'http'; 
13837:                     }
13838:                 } else {
13839:                     $protocol{$id} = 'http';
13840:                 }
13841:                 if (defined($intdom)) {
13842:                     $internetdom{$id} = $intdom;
13843:                 }
13844: 	    }
13845: 	}
13846:     }
13847:     
13848:     sub reset_hosts_info {
13849: 	&purge_remembered();
13850: 	&reset_domain_info();
13851: 	&reset_hosts_ip_info();
13852:         undef(%internetdom);
13853: 	undef(%name_to_host);
13854: 	undef(%hostname);
13855: 	undef(%hostdom);
13856: 	undef(%libserv);
13857: 	undef($loaded);
13858:     }
13859: 
13860:     sub load_hosts_tab {
13861: 	my ($ignore_cache,$nocache) = @_;
13862: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13863: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13864: 	my @config = <$config>;
13865: 	&parse_hosts_tab(\@config);
13866: 	close($config);
13867: 	$loaded=1;
13868:     }
13869: 
13870:     sub hostname {
13871: 	&load_hosts_tab() if (!$loaded);
13872: 
13873: 	my ($lonid) = @_;
13874: 	return $hostname{$lonid};
13875:     }
13876: 
13877:     sub all_hostnames {
13878: 	&load_hosts_tab() if (!$loaded);
13879: 
13880: 	return %hostname;
13881:     }
13882: 
13883:     sub all_names {
13884:         my ($ignore_cache,$nocache) = @_;
13885: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13886: 
13887: 	return %name_to_host;
13888:     }
13889: 
13890:     sub all_host_domain {
13891:         &load_hosts_tab() if (!$loaded);
13892:         return %hostdom;
13893:     }
13894: 
13895:     sub all_host_intdom {
13896:         &load_hosts_tab() if (!$loaded);
13897:         return %internetdom;
13898:     }
13899: 
13900:     sub is_library {
13901: 	&load_hosts_tab() if (!$loaded);
13902: 
13903: 	return exists($libserv{$_[0]});
13904:     }
13905: 
13906:     sub all_library {
13907: 	&load_hosts_tab() if (!$loaded);
13908: 
13909: 	return %libserv;
13910:     }
13911: 
13912:     sub unique_library {
13913: 	#2x reverse removes all hostnames that appear more than once
13914:         my %unique = reverse &all_library();
13915:         return reverse %unique;
13916:     }
13917: 
13918:     sub get_servers {
13919: 	&load_hosts_tab() if (!$loaded);
13920: 
13921: 	my ($domain,$type) = @_;
13922: 	my %possible_hosts = ($type eq 'library') ? %libserv
13923: 	                                          : %hostname;
13924: 	my %result;
13925: 	if (ref($domain) eq 'ARRAY') {
13926: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13927: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13928: 		    $result{$host} = $hostname;
13929: 		}
13930: 	    }
13931: 	} else {
13932: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13933: 		if ($hostdom{$host} eq $domain) {
13934: 		    $result{$host} = $hostname;
13935: 		}
13936: 	    }
13937: 	}
13938: 	return %result;
13939:     }
13940: 
13941:     sub get_unique_servers {
13942:         my %unique = reverse &get_servers(@_);
13943: 	return reverse %unique;
13944:     }
13945: 
13946:     sub host_domain {
13947: 	&load_hosts_tab() if (!$loaded);
13948: 
13949: 	my ($lonid) = @_;
13950: 	return $hostdom{$lonid};
13951:     }
13952: 
13953:     sub all_domains {
13954: 	&load_hosts_tab() if (!$loaded);
13955: 
13956: 	my %seen;
13957: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13958: 	return @uniq;
13959:     }
13960: 
13961:     sub internet_dom {
13962:         &load_hosts_tab() if (!$loaded);
13963: 
13964:         my ($lonid) = @_;
13965:         return $internetdom{$lonid};
13966:     }
13967: 
13968:     sub is_LC_dns {
13969:         &load_hosts_tab() if (!$loaded);
13970: 
13971:         my ($hostname) = @_;
13972:         return exists($LC_dns_serv{$hostname});
13973:     }
13974: 
13975: }
13976: 
13977: { 
13978:     my %iphost;
13979:     my %name_to_ip;
13980:     my %lonid_to_ip;
13981: 
13982:     sub get_hosts_from_ip {
13983: 	my ($ip) = @_;
13984: 	my %iphosts = &get_iphost();
13985: 	if (ref($iphosts{$ip})) {
13986: 	    return @{$iphosts{$ip}};
13987: 	}
13988: 	return;
13989:     }
13990:     
13991:     sub reset_hosts_ip_info {
13992: 	undef(%iphost);
13993: 	undef(%name_to_ip);
13994: 	undef(%lonid_to_ip);
13995:     }
13996: 
13997:     sub get_host_ip {
13998: 	my ($lonid) = @_;
13999: 	if (exists($lonid_to_ip{$lonid})) {
14000: 	    return $lonid_to_ip{$lonid};
14001: 	}
14002: 	my $name=&hostname($lonid);
14003:    	my $ip = gethostbyname($name);
14004: 	return if (!$ip || length($ip) ne 4);
14005: 	$ip=inet_ntoa($ip);
14006: 	$name_to_ip{$name}   = $ip;
14007: 	$lonid_to_ip{$lonid} = $ip;
14008: 	return $ip;
14009:     }
14010:     
14011:     sub get_iphost {
14012: 	my ($ignore_cache,$nocache) = @_;
14013: 
14014: 	if (!$ignore_cache) {
14015: 	    if (%iphost) {
14016: 		return %iphost;
14017: 	    }
14018: 	    my ($ip_info,$cached)=
14019: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14020: 	    if ($cached) {
14021: 		%iphost      = %{$ip_info->[0]};
14022: 		%name_to_ip  = %{$ip_info->[1]};
14023: 		%lonid_to_ip = %{$ip_info->[2]};
14024: 		return %iphost;
14025: 	    }
14026: 	}
14027: 
14028: 	# get yesterday's info for fallback
14029: 	my %old_name_to_ip;
14030: 	my ($ip_info,$cached)=
14031: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14032: 	if ($cached) {
14033: 	    %old_name_to_ip = %{$ip_info->[1]};
14034: 	}
14035: 
14036: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14037: 	foreach my $name (keys(%name_to_host)) {
14038: 	    my $ip;
14039: 	    if (!exists($name_to_ip{$name})) {
14040: 		$ip = gethostbyname($name);
14041: 		if (!$ip || length($ip) ne 4) {
14042: 		    if (defined($old_name_to_ip{$name})) {
14043: 			$ip = $old_name_to_ip{$name};
14044: 			&logthis("Can't find $name defaulting to old $ip");
14045: 		    } else {
14046: 			&logthis("Name $name no IP found");
14047: 			next;
14048: 		    }
14049: 		} else {
14050: 		    $ip=inet_ntoa($ip);
14051: 		}
14052: 		$name_to_ip{$name} = $ip;
14053: 	    } else {
14054: 		$ip = $name_to_ip{$name};
14055: 	    }
14056: 	    foreach my $id (@{ $name_to_host{$name} }) {
14057: 		$lonid_to_ip{$id} = $ip;
14058: 	    }
14059: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14060: 	}
14061:         unless ($nocache) {
14062: 	    &do_cache_new('iphost','iphost',
14063: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14064: 		          48*60*60);
14065:         }
14066: 
14067: 	return %iphost;
14068:     }
14069: 
14070:     #
14071:     #  Given a DNS returns the loncapa host name for that DNS 
14072:     # 
14073:     sub host_from_dns {
14074:         my ($dns) = @_;
14075:         my @hosts;
14076:         my $ip;
14077: 
14078:         if (exists($name_to_ip{$dns})) {
14079:             $ip = $name_to_ip{$dns};
14080:         }
14081:         if (!$ip) {
14082:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14083:             if (length($ip) == 4) { 
14084: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14085:             }
14086:         }
14087:         if ($ip) {
14088: 	    @hosts = get_hosts_from_ip($ip);
14089: 	    return $hosts[0];
14090:         }
14091:         return undef;
14092:     }
14093: 
14094:     sub get_internet_names {
14095:         my ($lonid) = @_;
14096:         return if ($lonid eq '');
14097:         my ($idnref,$cached)=
14098:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14099:         if ($cached) {
14100:             return $idnref;
14101:         }
14102:         my $ip = &get_host_ip($lonid);
14103:         my @hosts = &get_hosts_from_ip($ip);
14104:         my %iphost = &get_iphost();
14105:         my (@idns,%seen);
14106:         foreach my $id (@hosts) {
14107:             my $dom = &host_domain($id);
14108:             my $prim_id = &domain($dom,'primary');
14109:             my $prim_ip = &get_host_ip($prim_id);
14110:             next if ($seen{$prim_ip});
14111:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14112:                 foreach my $id (@{$iphost{$prim_ip}}) {
14113:                     my $intdom = &internet_dom($id);
14114:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14115:                         push(@idns,$intdom);
14116:                     }
14117:                 }
14118:             }
14119:             $seen{$prim_ip} = 1;
14120:         }
14121:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14122:     }
14123: 
14124: }
14125: 
14126: sub all_loncaparevs {
14127:     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);
14128: }
14129: 
14130: # ---------------------------------------------------------- Read loncaparev table
14131: {
14132:     sub load_loncaparevs { 
14133:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14134:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14135:                 while (my $configline=<$config>) {
14136:                     chomp($configline);
14137:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14138:                     $loncaparevs{$hostid}=$loncaparev;
14139:                 }
14140:                 close($config);
14141:             }
14142:         }
14143:     }
14144: }
14145: 
14146: # ---------------------------------------------------------- Read serverhostID table
14147: {
14148:     sub load_serverhomeIDs {
14149:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14150:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14151:                 while (my $configline=<$config>) {
14152:                     chomp($configline);
14153:                     my ($name,$id)=split(/:/,$configline);
14154:                     $serverhomeIDs{$name}=$id;
14155:                 }
14156:                 close($config);
14157:             }
14158:         }
14159:     }
14160: }
14161: 
14162: 
14163: BEGIN {
14164: 
14165: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14166:     unless ($readit) {
14167: {
14168:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14169:     %perlvar = (%perlvar,%{$configvars});
14170: }
14171: 
14172: 
14173: # ------------------------------------------------------ Read spare server file
14174: {
14175:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14176: 
14177:     while (my $configline=<$config>) {
14178:        chomp($configline);
14179:        if ($configline) {
14180: 	   my ($host,$type) = split(':',$configline,2);
14181: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14182: 	   push(@{ $spareid{$type} }, $host);
14183:        }
14184:     }
14185:     close($config);
14186: }
14187: # ------------------------------------------------------------ Read permissions
14188: {
14189:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14190: 
14191:     while (my $configline=<$config>) {
14192: 	chomp($configline);
14193: 	if ($configline) {
14194: 	    my ($role,$perm)=split(/ /,$configline);
14195: 	    if ($perm ne '') { $pr{$role}=$perm; }
14196: 	}
14197:     }
14198:     close($config);
14199: }
14200: 
14201: # -------------------------------------------- Read plain texts for permissions
14202: {
14203:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14204: 
14205:     while (my $configline=<$config>) {
14206: 	chomp($configline);
14207: 	if ($configline) {
14208: 	    my ($short,@plain)=split(/:/,$configline);
14209:             %{$prp{$short}} = ();
14210: 	    if (@plain > 0) {
14211:                 $prp{$short}{'std'} = $plain[0];
14212:                 for (my $i=1; $i<@plain; $i++) {
14213:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14214:                 }
14215:             }
14216: 	}
14217:     }
14218:     close($config);
14219: }
14220: 
14221: # ---------------------------------------------------------- Read package table
14222: {
14223:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14224: 
14225:     while (my $configline=<$config>) {
14226: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14227: 	chomp($configline);
14228: 	my ($short,$plain)=split(/:/,$configline);
14229: 	my ($pack,$name)=split(/\&/,$short);
14230: 	if ($plain ne '') {
14231: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14232: 	    $packagetab{$short}=$plain; 
14233: 	}
14234:     }
14235:     close($config);
14236: }
14237: 
14238: # ---------------------------------------------------------- Read loncaparev table
14239: 
14240: &load_loncaparevs();
14241: 
14242: # ---------------------------------------------------------- Read serverhostID table
14243: 
14244: &load_serverhomeIDs();
14245: 
14246: # ---------------------------------------------------------- Read releaseslist XML
14247: {
14248:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14249:     if (-e $file) {
14250:         my $parser = HTML::LCParser->new($file);
14251:         while (my $token = $parser->get_token()) {
14252:             if ($token->[0] eq 'S') {
14253:                 my $item = $token->[1];
14254:                 my $name = $token->[2]{'name'};
14255:                 my $value = $token->[2]{'value'};
14256:                 my $valuematch = $token->[2]{'valuematch'};
14257:                 my $namematch = $token->[2]{'namematch'};
14258:                 if ($item eq 'parameter') {
14259:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14260:                         my $release = $parser->get_text();
14261:                         $release =~ s/(^\s*|\s*$ )//gx;
14262:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14263:                     }
14264:                 } elsif ($item ne '' && $name ne '') {
14265:                     my $release = $parser->get_text();
14266:                     $release =~ s/(^\s*|\s*$ )//gx;
14267:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14268:                 }
14269:             }
14270:         }
14271:     }
14272: }
14273: 
14274: # ---------------------------------------------------------- Read managers table
14275: {
14276:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14277:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14278:             while (my $configline=<$config>) {
14279:                 chomp($configline);
14280:                 next if ($configline =~ /^\#/);
14281:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14282:                     $managerstab{$configline} = 1;
14283:                 }
14284:             }
14285:             close($config);
14286:         }
14287:     }
14288: }
14289: 
14290: # ------------- set up temporary directory
14291: {
14292:     $tmpdir = LONCAPA::tempdir();
14293: 
14294: }
14295: 
14296: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14297: 				'compress_threshold'=> 20_000,
14298:  			        });
14299: 
14300: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14301: $dumpcount=0;
14302: $locknum=0;
14303: 
14304: &logtouch();
14305: &logthis('<font color="yellow">INFO: Read configuration</font>');
14306: $readit=1;
14307:     {
14308: 	use integer;
14309: 	my $test=(2**32)+1;
14310: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14311: 	&logthis(" Detected 64bit platform ($_64bit)");
14312:     }
14313: }
14314: }
14315: 
14316: 1;
14317: __END__
14318: 
14319: =pod
14320: 
14321: =head1 NAME
14322: 
14323: Apache::lonnet - Subroutines to ask questions about things in the network.
14324: 
14325: =head1 SYNOPSIS
14326: 
14327: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14328: 
14329:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14330: 
14331: Common parameters:
14332: 
14333: =over 4
14334: 
14335: =item *
14336: 
14337: $uname : an internal username (if $cname expecting a course Id specifically)
14338: 
14339: =item *
14340: 
14341: $udom : a domain (if $cdom expecting a course's domain specifically)
14342: 
14343: =item *
14344: 
14345: $symb : a resource instance identifier
14346: 
14347: =item *
14348: 
14349: $namespace : the name of a .db file that contains the data needed or
14350: being set.
14351: 
14352: =back
14353: 
14354: =head1 OVERVIEW
14355: 
14356: lonnet provides subroutines which interact with the
14357: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14358: about classes, users, and resources.
14359: 
14360: For many of these objects you can also use this to store data about
14361: them or modify them in various ways.
14362: 
14363: =head2 Symbs
14364: 
14365: To identify a specific instance of a resource, LON-CAPA uses symbols
14366: or "symbs"X<symb>. These identifiers are built from the URL of the
14367: map, the resource number of the resource in the map, and the URL of
14368: the resource itself. The latter is somewhat redundant, but might help
14369: if maps change.
14370: 
14371: An example is
14372: 
14373:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14374: 
14375: The respective map entry is
14376: 
14377:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14378:   title="Problem 2">
14379:  </resource>
14380: 
14381: Symbs are used by the random number generator, as well as to store and
14382: restore data specific to a certain instance of for example a problem.
14383: 
14384: =head2 Storing And Retrieving Data
14385: 
14386: X<store()>X<cstore()>X<restore()>Three of the most important functions
14387: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14388: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14389: is is the non-critical message twin of cstore. These functions are for
14390: handlers to store a perl hash to a user's permanent data space in an
14391: easy manner, and to retrieve it again on another call. It is expected
14392: that a handler would use this once at the beginning to retrieve data,
14393: and then again once at the end to send only the new data back.
14394: 
14395: The data is stored in the user's data directory on the user's
14396: homeserver under the ID of the course.
14397: 
14398: The hash that is returned by restore will have all of the previous
14399: value for all of the elements of the hash.
14400: 
14401: Example:
14402: 
14403:  #creating a hash
14404:  my %hash;
14405:  $hash{'foo'}='bar';
14406: 
14407:  #storing it
14408:  &Apache::lonnet::cstore(\%hash);
14409: 
14410:  #changing a value
14411:  $hash{'foo'}='notbar';
14412: 
14413:  #adding a new value
14414:  $hash{'bar'}='foo';
14415:  &Apache::lonnet::cstore(\%hash);
14416: 
14417:  #retrieving the hash
14418:  my %history=&Apache::lonnet::restore();
14419: 
14420:  #print the hash
14421:  foreach my $key (sort(keys(%history))) {
14422:    print("\%history{$key} = $history{$key}");
14423:  }
14424: 
14425: Will print out:
14426: 
14427:  %history{1:foo} = bar
14428:  %history{1:keys} = foo:timestamp
14429:  %history{1:timestamp} = 990455579
14430:  %history{2:bar} = foo
14431:  %history{2:foo} = notbar
14432:  %history{2:keys} = foo:bar:timestamp
14433:  %history{2:timestamp} = 990455580
14434:  %history{bar} = foo
14435:  %history{foo} = notbar
14436:  %history{timestamp} = 990455580
14437:  %history{version} = 2
14438: 
14439: Note that the special hash entries C<keys>, C<version> and
14440: C<timestamp> were added to the hash. C<version> will be equal to the
14441: total number of versions of the data that have been stored. The
14442: C<timestamp> attribute will be the UNIX time the hash was
14443: stored. C<keys> is available in every historical section to list which
14444: keys were added or changed at a specific historical revision of a
14445: hash.
14446: 
14447: B<Warning>: do not store the hash that restore returns directly. This
14448: will cause a mess since it will restore the historical keys as if the
14449: were new keys. I.E. 1:foo will become 1:1:foo etc.
14450: 
14451: Calling convention:
14452: 
14453:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14454:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14455: 
14456: For more detailed information, see lonnet specific documentation.
14457: 
14458: =head1 RETURN MESSAGES
14459: 
14460: =over 4
14461: 
14462: =item * B<con_lost>: unable to contact remote host
14463: 
14464: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14465: when the connection is brought back up
14466: 
14467: =item * B<con_failed>: unable to contact remote host and unable to save message
14468: for later delivery
14469: 
14470: =item * B<error:>: an error a occurred, a description of the error follows the :
14471: 
14472: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14473: that was requested
14474: 
14475: =back
14476: 
14477: =head1 PUBLIC SUBROUTINES
14478: 
14479: =head2 Session Environment Functions
14480: 
14481: =over 4
14482: 
14483: =item * 
14484: X<appenv()>
14485: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14486: the user envirnoment file, and will be restored for each access this
14487: user makes during this session, also modifies the %env for the current
14488: process. Optional rolesarrayref - if defined contains a reference to an array
14489: of roles which are exempt from the restriction on modifying user.role entries 
14490: in the user's environment.db and in %env.    
14491: 
14492: =item *
14493: X<delenv()>
14494: B<delenv($delthis,$regexp)>: removes all items from the session
14495: environment file that begin with $delthis. If the 
14496: optional second arg - $regexp - is true, $delthis is treated as a 
14497: regular expression, otherwise \Q$delthis\E is used. 
14498: The values are also deleted from the current processes %env.
14499: 
14500: =item * get_env_multiple($name) 
14501: 
14502: gets $name from the %env hash, it seemlessly handles the cases where multiple
14503: values may be defined and end up as an array ref.
14504: 
14505: returns an array of values
14506: 
14507: =back
14508: 
14509: =head2 User Information
14510: 
14511: =over 4
14512: 
14513: =item *
14514: X<queryauthenticate()>
14515: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14516: authentication scheme
14517: 
14518: =item *
14519: X<authenticate()>
14520: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14521: authenticate user from domain's lib servers (first use the current
14522: one). C<$upass> should be the users password.
14523: $checkdefauth is optional (value is 1 if a check should be made to
14524:    authenticate user using default authentication method, and allow
14525:    account creation if username does not have account in the domain).
14526: $clientcancheckhost is optional (value is 1 if checking whether the
14527:    server can host will occur on the client side in lonauth.pm).   
14528: 
14529: =item *
14530: X<homeserver()>
14531: B<homeserver($uname,$udom)>: find the server which has
14532: the user's directory and files (there must be only one), this caches
14533: the answer, and also caches if there is a borken connection.
14534: 
14535: =item *
14536: X<idget()>
14537: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14538: a list of student/employee IDs or clicker IDs
14539: (student/employee IDs are a unique resource in a domain, there must be 
14540: only 1 ID per username, and only 1 username per ID in a specific domain).
14541: clickerIDs are not necessarily unique, as students might share clickers.
14542: (returns hash: id=>name,id=>name)
14543: 
14544: =item *
14545: X<idrget()>
14546: B<idrget($udom,@unames)>: find the IDs behind a list of
14547: usernames (returns hash: name=>id,name=>id)
14548: 
14549: =item *
14550: X<idput()>
14551: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14552: names and associated student/employee IDs or clicker IDs.
14553: 
14554: =item *
14555: X<iddel()>
14556: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14557: student/employee ID or clicker ID username look-ups from domain.
14558: The homeserver ($uhome) and namespace ($namespace) are optional.
14559: If no $uhome is provided, it will be determined usig &homeserver()
14560: for each user.  If no $namespace is provided, the default is ids.
14561: 
14562: =item *
14563: X<updateclickers()>
14564: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14565: clicker ID-to-username look-ups in clickers.db on library server.
14566: Permitted actions are add or del (i.e., add or delete). The 
14567: clickers.db contains clickerID as keys (escaped), and each corresponding
14568: value is an escaped comma-separated list of usernames (for whom the
14569: library server is the homeserver), who registered that particular ID.
14570: If $critical is true, the update will be sent via &critical, otherwise
14571: &reply() will be used.
14572: 
14573: =item *
14574: X<rolesinit()>
14575: B<rolesinit($udom,$username)>: get user privileges.
14576: returns user role, first access and timer interval hashes
14577: 
14578: =item *
14579: X<privileged()>
14580: B<privileged($username,$domain)>: returns a true if user has a
14581: privileged and active role (i.e. su or dc), false otherwise.
14582: 
14583: =item *
14584: X<getsection()>
14585: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14586: course $cname, return section name/number or '' for "not in course"
14587: and '-1' for "no section"
14588: 
14589: =item *
14590: X<userenvironment()>
14591: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14592: passed in @what from the requested user's environment, returns a hash
14593: 
14594: =item * 
14595: X<userlog_query()>
14596: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14597: activity.log file. %filters defines filters applied when parsing the
14598: log file. These can be start or end timestamps, or the type of action
14599: - log to look for Login or Logout events, check for Checkin or
14600: Checkout, role for role selection. The response is in the form
14601: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14602: escaped strings of the action recorded in the activity.log file.
14603: 
14604: =back
14605: 
14606: =head2 User Roles
14607: 
14608: =over 4
14609: 
14610: =item *
14611: 
14612: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14613: returns codes for allowed actions.
14614: 
14615: The first argument is required, all others are optional.
14616: 
14617: $priv is the privilege being checked.
14618: $uri contains additional information about what is being checked for access (e.g.,
14619: URL, course ID etc.). 
14620: $symb is the unique resource instance identifier in a course; if needed,
14621: but not provided, it will be retrieved via a call to &symbread(). 
14622: $role is the role for which a priv is being checked (only used if priv is evb). 
14623: $clientip is the user's IP address (only used when checking for access to portfolio 
14624: files).
14625: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14626: prevents recursive calls to &allowed.
14627: 
14628:  F: full access
14629:  U,I,K: authentication modes (cxx only)
14630:  '': forbidden
14631:  1: user needs to choose course
14632:  2: browse allowed
14633:  A: passphrase authentication needed
14634:  B: access temporarily blocked because of a blocking event in a course.
14635: 
14636: =item *
14637: 
14638: constructaccess($url,$setpriv) : check for access to construction space URL
14639: 
14640: See if the owner domain and name in the URL match those in the
14641: expected environment.  If so, return three element list
14642: ($ownername,$ownerdomain,$ownerhome).
14643: 
14644: Otherwise return the null string.
14645: 
14646: If second argument 'setpriv' is true, it assigns the privileges,
14647: and returns the same three element list, unless the owner has
14648: blocked "ad hoc" Domain Coordinator access to the Author Space,
14649: in which case the null string is returned.
14650: 
14651: =item *
14652: 
14653: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14654: define a custom role rolename set privileges in format of lonTabs/roles.tab
14655: for system, domain, and course level. $uname and $udom are optional (current
14656: user's username and domain will be used when either of $uname or $udom are absent.
14657: 
14658: =item *
14659: 
14660: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14661: (rolesplain.tab); plain text explanation of a user role term.
14662: $type is Course (default) or Community.
14663: If $forcedefault evaluates to true, text returned will be default 
14664: text for $type. Otherwise, if this is a course, the text returned 
14665: will be a custom name for the role (if defined in the course's 
14666: environment).  If no custom name is defined the default is returned.
14667:    
14668: =item *
14669: 
14670: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14671: All arguments are optional. Returns a hash of a roles, either for
14672: co-author/assistant author roles for a user's Construction Space
14673: (default), or if $context is 'userroles', roles for the user himself,
14674: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14675: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14676: For each key, value is set to colon-separated start and end times for
14677: the role.  If no username and domain are specified, will default to
14678: current user/domain. Types, roles, and roledoms are references to arrays
14679: of role statuses (active, future or previous), roles 
14680: (e.g., cc,in, st etc.) and domains of the roles which can be used
14681: to restrict the list of roles reported. If no array ref is 
14682: provided for types, will default to return only active roles.
14683: 
14684: =item *
14685: 
14686: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14687: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14688: 
14689: Additional optional arguments are: $type (if role checking is to be restricted 
14690: to certain user status types -- previous (expired roles), active (currently
14691: available roles) or future (roles available in the future), and
14692: $hideprivileged -- if true will not report course roles for users who
14693: have active Domain Coordinator role in course's domain or in additional
14694: domains (specified in 'Domains to check for privileged users' in course
14695: environment -- set via:  Course Settings -> Classlists and staff listing).
14696: 
14697: =item *
14698: 
14699: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14700: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14701: $possdomains and $possroles are optional array refs -- to domains to check and
14702: roles to check.  If $possdomains is not specified, a dump will be done of the
14703: users' roles.db to check for a dc or su role in any domain. This can be
14704: time consuming if &privileged is called repeatedly (e.g., when displaying a
14705: classlist), so in such cases, supplying a $possdomains array is preferred, as
14706: this then allows &privileged_by_domain() to be used, which caches the identity
14707: of privileged users, eliminating the need for repeated calls to &dump().
14708: 
14709: =item *
14710: 
14711: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14712: where the outer hash keys are domains specified in the $possdomains array ref,
14713: next inner hash keys are privileged roles specified in the $roles array ref,
14714: and the innermost hash contains key = value pairs for username:domain = end:start
14715: for active or future "privileged" users with that role in that domain. To avoid
14716: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14717: innerhash are cached using priv_$role and $dom as the identifiers.
14718: 
14719: =back
14720: 
14721: =head2 User Modification
14722: 
14723: =over 4
14724: 
14725: =item *
14726: 
14727: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14728: user for the level given by URL.  Optional start and end dates (leave empty
14729: string or zero for "no date")
14730: 
14731: =item *
14732: 
14733: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14734: change a users, password, possible return values are: ok,
14735: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14736: refused
14737: 
14738: =item *
14739: 
14740: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14741: 
14742: =item *
14743: 
14744: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14745:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14746: 
14747: will update user information (firstname,middlename,lastname,generation,
14748: permanentemail), and if forceid is true, student/employee ID also.
14749: A user's institutional affiliation(s) can also be updated.
14750: User information fields will not be overwritten with empty entries 
14751: unless the field is included in the $candelete array reference.
14752: This array is included when a single user is modified via "Manage Users",
14753: or when Autoupdate.pl is run by cron in a domain.
14754: 
14755: =item *
14756: 
14757: modifystudent
14758: 
14759: modify a student's enrollment and identification information.
14760: The course id is resolved based on the current user's environment.  
14761: This means the invoking user must be a course coordinator or otherwise
14762: associated with a course.
14763: 
14764: This call is essentially a wrapper for lonnet::modifyuser and
14765: lonnet::modify_student_enrollment
14766: 
14767: Inputs: 
14768: 
14769: =over 4
14770: 
14771: =item B<$udom> Student's loncapa domain
14772: 
14773: =item B<$uname> Student's loncapa login name
14774: 
14775: =item B<$uid> Student/Employee ID
14776: 
14777: =item B<$umode> Student's authentication mode
14778: 
14779: =item B<$upass> Student's password
14780: 
14781: =item B<$first> Student's first name
14782: 
14783: =item B<$middle> Student's middle name
14784: 
14785: =item B<$last> Student's last name
14786: 
14787: =item B<$gene> Student's generation
14788: 
14789: =item B<$usec> Student's section in course
14790: 
14791: =item B<$end> Unix time of the roles expiration
14792: 
14793: =item B<$start> Unix time of the roles start date
14794: 
14795: =item B<$forceid> If defined, allow $uid to be changed
14796: 
14797: =item B<$desiredhome> server to use as home server for student
14798: 
14799: =item B<$email> Student's permanent e-mail address
14800: 
14801: =item B<$type> Type of enrollment (auto or manual)
14802: 
14803: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14804: 
14805: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14806: 
14807: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14808: 
14809: =item B<$context> role change context (shown in User Management Logs display in a course)
14810: 
14811: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14812: 
14813: =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.
14814: 
14815: =back
14816: 
14817: =item *
14818: 
14819: modify_student_enrollment
14820: 
14821: Change a student's enrollment status in a class.  The environment variable
14822: 'role.request.course' must be defined for this function to proceed.
14823: 
14824: Inputs:
14825: 
14826: =over 4
14827: 
14828: =item $udom, student's domain
14829: 
14830: =item $uname, student's name
14831: 
14832: =item $uid, student's user id
14833: 
14834: =item $first, student's first name
14835: 
14836: =item $middle
14837: 
14838: =item $last
14839: 
14840: =item $gene
14841: 
14842: =item $usec
14843: 
14844: =item $end
14845: 
14846: =item $start
14847: 
14848: =item $type
14849: 
14850: =item $locktype
14851: 
14852: =item $cid
14853: 
14854: =item $selfenroll
14855: 
14856: =item $context
14857: 
14858: =item $credits, number of credits student will earn from this class
14859: 
14860: =item $instsec, institutional course section code for student
14861: 
14862: =back
14863: 
14864: 
14865: =item *
14866: 
14867: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14868: custom role; give a custom role to a user for the level given by URL.  Specify
14869: name and domain of role author, and role name
14870: 
14871: =item *
14872: 
14873: revokerole($udom,$uname,$url,$role) : revoke a role for url
14874: 
14875: =item *
14876: 
14877: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14878: 
14879: =back
14880: 
14881: =head2 Course Infomation
14882: 
14883: =over 4
14884: 
14885: =item *
14886: 
14887: coursedescription($courseid,$options) : returns a hash of information about the
14888: specified course id, including all environment settings for the
14889: course, the description of the course will be in the hash under the
14890: key 'description'
14891: 
14892: $options is an optional parameter that if supplied is a hash reference that controls
14893: what how this function works.  It has the following key/values:
14894: 
14895: =over 4
14896: 
14897: =item freshen_cache
14898: 
14899: If defined, and the environment cache for the course is valid, it is 
14900: returned in the returned hash.
14901: 
14902: =item one_time
14903: 
14904: If defined, the last cache time is set to _now_
14905: 
14906: =item user
14907: 
14908: If defined, the supplied username is used instead of the current user.
14909: 
14910: 
14911: =back
14912: 
14913: =item *
14914: 
14915: resdata($name,$domain,$type,@which) : request for current parameter
14916: setting for a specific $type, where $type is either 'course' or 'user',
14917: @what should be a list of parameters to ask about. This routine caches
14918: answers for 10 minutes.
14919: 
14920: =item *
14921: 
14922: get_courseresdata($courseid, $domain) : dump the entire course resource
14923: data base, returning a hash that is keyed by the resource name and has
14924: values that are the resource value.  I believe that the timestamps and
14925: versions are also returned.
14926: 
14927: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14928: supplemental content area. This routine caches the number of files for 
14929: 10 minutes.
14930: 
14931: =back
14932: 
14933: =head2 Course Modification
14934: 
14935: =over 4
14936: 
14937: =item *
14938: 
14939: writecoursepref($courseid,%prefs) : write preferences (environment
14940: database) for a course
14941: 
14942: =item *
14943: 
14944: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14945: 
14946: =item *
14947: 
14948: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14949: 
14950: =item *
14951: 
14952: is_course($courseid), is_course($cdom, $cnum)
14953: 
14954: Accepts either a combined $courseid (in the form of domain_courseid) or the
14955: two component version $cdom, $cnum. It checks if the specified course exists.
14956: 
14957: Returns:
14958:     undef if the course doesn't exist, otherwise
14959:     in scalar context the combined courseid.
14960:     in list context the two components of the course identifier, domain and 
14961:     courseid.    
14962: 
14963: =back
14964: 
14965: =head2 Resource Subroutines
14966: 
14967: =over 4
14968: 
14969: =item *
14970: 
14971: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14972: 
14973: =item *
14974: 
14975: repcopy($filename) : subscribes to the requested file, and attempts to
14976: replicate from the owning library server, Might return
14977: 'unavailable', 'not_found', 'forbidden', 'ok', or
14978: 'bad_request', also attempts to grab the metadata for the
14979: resource. Expects the local filesystem pathname
14980: (/home/httpd/html/res/....)
14981: 
14982: =back
14983: 
14984: =head2 Resource Information
14985: 
14986: =over 4
14987: 
14988: =item *
14989: 
14990: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14991: and returns the value of a variety of different possible values,
14992: $varname should be a request string, and the other parameters can be
14993: used to specify who and what one is asking about. Ordinarily, $cid 
14994: does not need to be specified, as it is retrived from 
14995: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14996: within lonuserstate::loadmap() when initializing a course, before
14997: $env{'request.course.id'} has been set, so it needs to be provided
14998: in that one case.
14999: 
15000: Possible values for $varname are environment.lastname (or other item
15001: from the envirnment hash), user.name (or someother aspect about the
15002: user), resource.0.maxtries (or some other part and parameter of a
15003: resource)
15004: 
15005: =item *
15006: 
15007: directcondval($number) : get current value of a condition; reads from a state
15008: string
15009: 
15010: =item *
15011: 
15012: condval($condidx) : value of condition index based on state
15013: 
15014: =item *
15015: 
15016: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15017: resource's metadata, $what should be either a specific key, or either
15018: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15019: packages that this resource currently uses, the last 3 arguments are 
15020: only used internally for recursive metadata.
15021: 
15022: the toolsymb is only used where the uri is for an external tool (for which
15023: the uri as well as the symb are guaranteed to be unique).
15024: 
15025: this function automatically caches all requests except any made recursively
15026: to retrieve a list of metadata keys for an imported library file ($liburi is 
15027: defined).
15028: 
15029: =item *
15030: 
15031: metadata_query($query,$custom,$customshow) : make a metadata query against the
15032: network of library servers; returns file handle of where SQL and regex results
15033: will be stored for query
15034: 
15035: =item *
15036: 
15037: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15038: return symbolic list entry (all arguments optional). 
15039: 
15040: Args: filename is the filename (including path) for the file for which a symb 
15041: is required; donotrecurse, if true will prevent calls to allowed() being made 
15042: to check access status if more than one resource was found in the bighash 
15043: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15044: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15045: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15046: cause possible symbs to be checked to determine if they are subject to content
15047: blocking, if so they will not be included as possible symbs; possibles is a
15048: ref to a hash, which, as a side effect, will be populated with all possible 
15049: symbs (content blocking not tested).
15050:  
15051: returns the data handle
15052: 
15053: =item *
15054: 
15055: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15056: and is a possible symb for the URL in $thisfn, and if is an encrypted
15057: resource that the user accessed using /enc/ returns a 1 on success, 0
15058: on failure, user must be in a course, as it assumes the existence of
15059: the course initial hash, and uses $env('request.course.id'}.  The third
15060: arg is an optional reference to a scalar.  If this arg is passed in the 
15061: call to symbverify, it will be set to 1 if the symb has been set to be 
15062: encrypted; otherwise it will be null.  
15063: 
15064: =item *
15065: 
15066: symbclean($symb) : removes versions numbers from a symb, returns the
15067: cleaned symb
15068: 
15069: =item *
15070: 
15071: is_on_map($uri) : checks if the $uri is somewhere on the current
15072: course map, user must be in a course for it to work.
15073: 
15074: =item *
15075: 
15076: numval($salt) : return random seed value (addend for rndseed)
15077: 
15078: =item *
15079: 
15080: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15081: a random seed, all arguments are optional, if they aren't sent it uses the
15082: environment to derive them. Note: if symb isn't sent and it can't get one
15083: from &symbread it will use the current time as its return value
15084: 
15085: =item *
15086: 
15087: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15088: unfakeable, receipt
15089: 
15090: =item *
15091: 
15092: receipt() : API to ireceipt working off of env values; given out to users
15093: 
15094: =item *
15095: 
15096: countacc($url) : count the number of accesses to a given URL
15097: 
15098: =item *
15099: 
15100: 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
15101: 
15102: =item *
15103: 
15104: 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)
15105: 
15106: =item *
15107: 
15108: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15109: 
15110: =item *
15111: 
15112: devalidate($symb) : devalidate temporary spreadsheet calculations,
15113: forcing spreadsheet to reevaluate the resource scores next time.
15114: 
15115: =item * 
15116: 
15117: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15118: when viewing in course context.
15119: 
15120:  input: six args -- filename (decluttered), course number, course domain,
15121:                     url, symb (if registered) and group (if this is a 
15122:                     group item -- e.g., bulletin board, group page etc.).
15123: 
15124:  output: array of five scalars --
15125:          $cfile -- url for file editing if editable on current server
15126:          $home -- homeserver of resource (i.e., for author if published,
15127:                                           or course if uploaded.).
15128:          $switchserver --  1 if server switch will be needed.
15129:          $forceedit -- 1 if icon/link should be to go to edit mode 
15130:          $forceview -- 1 if icon/link should be to go to view mode
15131: 
15132: =item *
15133: 
15134: is_course_upload($file,$cnum,$cdom)
15135: 
15136: Used in course context to determine if current file was uploaded to 
15137: the course (i.e., would be found in /userfiles/docs on the course's 
15138: homeserver.
15139: 
15140:   input: 3 args -- filename (decluttered), course number and course domain.
15141:   output: boolean -- 1 if file was uploaded.
15142: 
15143: =back
15144: 
15145: =head2 Storing/Retreiving Data
15146: 
15147: =over 4
15148: 
15149: =item *
15150: 
15151: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15152: permanently for this url; hashref needs to be given and should be a \%hashname;
15153: the remaining args aren't required and if they aren't passed or are '' they will
15154: be derived from the env (with the exception of $laststore, which is an 
15155: optional arg used when a user's submission is stored in grading).
15156: $laststore is $version=$timestamp, where $version is the most recent version
15157: number retrieved for the corresponding $symb in the $namespace db file, and
15158: $timestamp is the timestamp for that transaction (UNIX time).
15159: $laststore is currently only passed when cstore() is called by 
15160: structuretags::finalize_storage().
15161: 
15162: =item *
15163: 
15164: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15165: but uses critical subroutine
15166: 
15167: =item *
15168: 
15169: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15170: all args are optional
15171: 
15172: =item *
15173: 
15174: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15175: dumps the complete (or key matching regexp) namespace into a hash
15176: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15177: normally &store()ed into
15178: 
15179: $range should be either an integer '100' (give me the first 100
15180:                                            matching records)
15181:               or be  two integers sperated by a - with no spaces
15182:                  '30-50' (give me the 30th through the 50th matching
15183:                           records)
15184: 
15185: 
15186: =item *
15187: 
15188: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15189: replaces a &store() version of data with a replacement set of data
15190: for a particular resource in a namespace passed in the $storehash hash 
15191: reference. If $tolog is true, the transaction is logged in the courselog
15192: with an action=PUTSTORE.
15193: 
15194: =item *
15195: 
15196: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15197: works very similar to store/cstore, but all data is stored in a
15198: temporary location and can be reset using tmpreset, $storehash should
15199: be a hash reference, returns nothing on success
15200: 
15201: =item *
15202: 
15203: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15204: similar to restore, but all data is stored in a temporary location and
15205: can be reset using tmpreset. Returns a hash of values on success,
15206: error string otherwise.
15207: 
15208: =item *
15209: 
15210: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15211: deltes all keys for $symb form the temporary storage hash.
15212: 
15213: =item *
15214: 
15215: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15216: reference filled in from namesp ($udom and $uname are optional)
15217: 
15218: =item *
15219: 
15220: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15221: namesp ($udom and $uname are optional)
15222: 
15223: =item *
15224: 
15225: dump($namespace,$udom,$uname,$regexp,$range) : 
15226: dumps the complete (or key matching regexp) namespace into a hash
15227: ($udom, $uname, $regexp, $range are optional)
15228: 
15229: $range should be either an integer '100' (give me the first 100
15230:                                            matching records)
15231:               or be  two integers sperated by a - with no spaces
15232:                  '30-50' (give me the 30th through the 50th matching
15233:                           records)
15234: =item *
15235: 
15236: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15237: $store can be a scalar, an array reference, or if the amount to be 
15238: incremented is > 1, a hash reference.
15239: 
15240: ($udom and $uname are optional)
15241: 
15242: =item *
15243: 
15244: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15245: ($udom and $uname are optional)
15246: 
15247: =item *
15248: 
15249: cput($namespace,$storehash,$udom,$uname) : critical put
15250: ($udom and $uname are optional)
15251: 
15252: =item *
15253: 
15254: newput($namespace,$storehash,$udom,$uname) :
15255: 
15256: Attempts to store the items in the $storehash, but only if they don't
15257: currently exist, if this succeeds you can be certain that you have 
15258: successfully created a new key value pair in the $namespace db.
15259: 
15260: 
15261: Args:
15262:  $namespace: name of database to store values to
15263:  $storehash: hashref to store to the db
15264:  $udom: (optional) domain of user containing the db
15265:  $uname: (optional) name of user caontaining the db
15266: 
15267: Returns:
15268:  'ok' -> succeeded in storing all keys of $storehash
15269:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15270:                         least <key> already existed in the db (other
15271:                         requested keys may also already exist)
15272:  'error: <msg>' -> unable to tie the DB or other error occurred
15273:  'con_lost' -> unable to contact request server
15274:  'refused' -> action was not allowed by remote machine
15275: 
15276: 
15277: =item *
15278: 
15279: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15280: reference filled in from namesp (encrypts the return communication)
15281: ($udom and $uname are optional)
15282: 
15283: =item *
15284: 
15285: log($udom,$name,$home,$message) : write to permanent log for user; use
15286: critical subroutine
15287: 
15288: =item *
15289: 
15290: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15291: array reference filled in from namespace found in domain level on either
15292: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15293: 
15294: =item *
15295: 
15296: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15297: domain level either on specified domain server ($uhome) or primary domain 
15298: server ($udom and $uhome are optional)
15299: 
15300: =item * 
15301: 
15302: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15303: for: authentication, language, quotas, timezone, date locale, and portal URL in
15304: the target domain.
15305: 
15306: May also include additional key => value pairs for the following groups:
15307: 
15308: =over
15309: 
15310: =item
15311: disk quotas (MB allocated by default to portfolios and authoring spaces).
15312: 
15313: =over
15314: 
15315: =item defaultquota, authorquota
15316: 
15317: =back
15318: 
15319: =item
15320: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15321: portfolio for users).
15322: 
15323: =over
15324: 
15325: =item
15326: aboutme, blog, webdav, portfolio
15327: 
15328: =back
15329: 
15330: =item
15331: requestcourses: ability to request courses, and how requests are processed.
15332: 
15333: =over
15334: 
15335: =item
15336: official, unofficial, community, textbook, placement
15337: 
15338: =back
15339: 
15340: =item
15341: inststatus: types of institutional affiliation, and order in which they are displayed.
15342: 
15343: =over
15344: 
15345: =item
15346: inststatustypes, inststatusorder, inststatusguest
15347: 
15348: =back
15349: 
15350: =item
15351: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15352: for course's uploaded content.
15353: 
15354: =over
15355: 
15356: =item
15357: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15358: communityquota, textbookquota, placementquota
15359: 
15360: =back
15361: 
15362: =item
15363: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15364: on your servers.
15365: 
15366: =over
15367: 
15368: =item 
15369: remotesessions, hostedsessions
15370: 
15371: =back
15372: 
15373: =back
15374: 
15375: In cases where a domain coordinator has never used the "Set Domain Configuration"
15376: utility to create a configuration.db file on a domain's primary library server 
15377: only the following domain defaults: auth_def, auth_arg_def, lang_def
15378: -- corresponding values are authentication type (internal, krb4, krb5,
15379: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15380: will be available. Values are retrieved from cache (if current), unless the
15381: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15382: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15383: 
15384: Typical usage:
15385: 
15386: %domdefaults = &get_domain_defaults($target_domain);
15387: 
15388: =back
15389: 
15390: =head2 Network Status Functions
15391: 
15392: =over 4
15393: 
15394: =item *
15395: 
15396: dirlist() : return directory list based on URI (first arg).
15397: 
15398: Inputs: 1 required, 5 optional.
15399: 
15400: =over
15401: 
15402: =item 
15403: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15404: 
15405: =item
15406: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15407: 
15408: =item
15409: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15410: 
15411: =item
15412: $getpropath - boolean: 1 if prepend path using &propath(). 
15413: 
15414: =item
15415: $getuserdir - boolean: 1 if prepend path for "userfiles".
15416: 
15417: =item 
15418: $alternateRoot - path to prepend in place of path from $uri.
15419: 
15420: =back
15421: 
15422: Returns: Array of up to two items.
15423: 
15424: =over
15425: 
15426: a reference to an array of files/subdirectories
15427: 
15428: =over
15429: 
15430: Each element in the array of files/subdirectories is a & separated list of
15431: item name and the result of running stat on the item.  If dirlist was requested
15432: for a file instead of a directory, the item name will be ''. For a directory 
15433: listing, if the item is a metadata file, the element will end &N&M 
15434: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15435: default copyright set (1).  
15436: 
15437: =back
15438: 
15439: a scalar containing error condition (if encountered).
15440: 
15441: =over
15442: 
15443: =item 
15444: no_host (no homeserver identified for $username:$domain).
15445: 
15446: =item 
15447: no_such_host (server contacted for listing not identified as valid host).
15448: 
15449: =item 
15450: con_lost (connection to remote server failed).
15451: 
15452: =item 
15453: refused (invalid $username:$domain received on lond side).
15454: 
15455: =item 
15456: no_such_dir (directory at specified path on lond side does not exist). 
15457: 
15458: =item 
15459: empty (directory at specified path on lond side is empty).
15460: 
15461: =over
15462: 
15463: This is currently not encountered because the &ls3, &ls2, 
15464: &ls (_handler) routines on the lond side do not filter out
15465: . and .. from a directory listing. 
15466: 
15467: =back
15468: 
15469: =back
15470: 
15471: =back
15472: 
15473: =item *
15474: 
15475: spareserver() : find server with least workload from spare.tab
15476: 
15477: 
15478: =item *
15479: 
15480: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15481: if there is no corresponding loncapa host.
15482: 
15483: =back
15484: 
15485: 
15486: =head2 Apache Request
15487: 
15488: =over 4
15489: 
15490: =item *
15491: 
15492: ssi($url,%hash) : server side include, does a complete request cycle on url to
15493: localhost, posts hash
15494: 
15495: =back
15496: 
15497: =head2 Data to String to Data
15498: 
15499: =over 4
15500: 
15501: =item *
15502: 
15503: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15504: and '&' separators, supports elements that are arrayrefs and hashrefs
15505: 
15506: =item *
15507: 
15508: hashref2str($hashref) : convert a hashref into a string complete with
15509: escaping and '=' and '&' separators, supports elements that are
15510: arrayrefs and hashrefs
15511: 
15512: =item *
15513: 
15514: arrayref2str($arrayref) : convert an arrayref into a string complete
15515: with escaping and '&' separators, supports elements that are arrayrefs
15516: and hashrefs
15517: 
15518: =item *
15519: 
15520: str2hash($string) : convert string to hash using unescaping and
15521: splitting on '=' and '&', supports elements that are arrayrefs and
15522: hashrefs
15523: 
15524: =item *
15525: 
15526: str2array($string) : convert string to hash using unescaping and
15527: splitting on '&', supports elements that are arrayrefs and hashrefs
15528: 
15529: =back
15530: 
15531: =head2 Logging Routines
15532: 
15533: 
15534: These routines allow one to make log messages in the lonnet.log and
15535: lonnet.perm logfiles.
15536: 
15537: =over 4
15538: 
15539: =item *
15540: 
15541: logtouch() : make sure the logfile, lonnet.log, exists
15542: 
15543: =item *
15544: 
15545: logthis() : append message to the normal lonnet.log file, it gets
15546: preiodically rolled over and deleted.
15547: 
15548: =item *
15549: 
15550: logperm() : append a permanent message to lonnet.perm.log, this log
15551: file never gets deleted by any automated portion of the system, only
15552: messages of critical importance should go in here.
15553: 
15554: 
15555: =back
15556: 
15557: =head2 General File Helper Routines
15558: 
15559: =over 4
15560: 
15561: =item *
15562: 
15563: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15564: (a) files in /uploaded
15565:   (i) If a local copy of the file exists - 
15566:       compares modification date of local copy with last-modified date for 
15567:       definitive version stored on home server for course. If local copy is 
15568:       stale, requests a new version from the home server and stores it. 
15569:       If the original has been removed from the home server, then local copy 
15570:       is unlinked.
15571:   (ii) If local copy does not exist -
15572:       requests the file from the home server and stores it. 
15573:   
15574:   If $caller is 'uploadrep':  
15575:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15576:     for request for files originally uploaded via DOCS. 
15577:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15578:   
15579:   Otherwise:
15580:      This indicates a call from the content generation phase of the request.
15581:      -  returns the entire contents of the file or -1.
15582:      
15583: (b) files in /res
15584:    - returns the entire contents of a file or -1; 
15585:    it properly subscribes to and replicates the file if neccessary.
15586: 
15587: 
15588: =item *
15589: 
15590: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15591:                   reference
15592: 
15593: returns either a stat() list of data about the file or an empty list
15594: if the file doesn't exist or couldn't find out about it (connection
15595: problems or user unknown)
15596: 
15597: =item *
15598: 
15599: filelocation($dir,$file) : returns file system location of a file
15600: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15601: directory that relative $file lookups are to looked in ($dir of /a/dir
15602: and a file of ../bob will become /a/bob)
15603: 
15604: =item *
15605: 
15606: hreflocation($dir,$file) : returns file system location or a URL; same as
15607: filelocation except for hrefs
15608: 
15609: =item *
15610: 
15611: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15612: also removes beginning /home/httpd/html unless /priv/ follows it.
15613: 
15614: =back
15615: 
15616: =head2 Usererfile file routines (/uploaded*)
15617: 
15618: =over 4
15619: 
15620: =item *
15621: 
15622: userfileupload(): main rotine for putting a file in a user or course's
15623:                   filespace, arguments are,
15624: 
15625:  formname - required - this is the name of the element in $env where the
15626:            filename, and the contents of the file to create/modifed exist
15627:            the filename is in $env{'form.'.$formname.'.filename'} and the
15628:            contents of the file is located in $env{'form.'.$formname}
15629:  context - if coursedoc, store the file in the course of the active role
15630:              of the current user; 
15631:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15632:            if 'canceloverwrite': delete file in tmp/overwrites directory
15633:  subdir - required - subdirectory to put the file in under ../userfiles/
15634:          if undefined, it will be placed in "unknown"
15635: 
15636:  (This routine calls clean_filename() to remove any dangerous
15637:  characters from the filename, and then calls finuserfileupload() to
15638:  complete the transaction)
15639: 
15640:  returns either the url of the uploaded file (/uploaded/....) if successful
15641:  and /adm/notfound.html if unsuccessful
15642: 
15643: =item *
15644: 
15645: clean_filename(): routine for cleaing a filename up for storage in
15646:                  userfile space, argument is:
15647: 
15648:  filename - proposed filename
15649: 
15650: returns: the new clean filename
15651: 
15652: =item *
15653: 
15654: finishuserfileupload(): routine that creates and sends the file to
15655: userspace, probably shouldn't be called directly
15656: 
15657:   docuname: username or courseid of destination for the file
15658:   docudom: domain of user/course of destination for the file
15659:   formname: same as for userfileupload()
15660:   fname: filename (including subdirectories) for the file
15661:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15662:   allfiles: reference to hash used to store objects found by parser
15663:   codebase: reference to hash used for codebases of java objects found by parser
15664:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15665:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15666:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15667:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15668:   context: if 'overwrite', will move the uploaded file from its temporary location to
15669:             userfiles to facilitate overwriting a previously uploaded file with same name.
15670:   mimetype: reference to scalar to accommodate mime type determined
15671:             from File::MMagic if $parser = parse.
15672: 
15673:  returns either the url of the uploaded file (/uploaded/....) if successful
15674:  and /adm/notfound.html if unsuccessful (or an error message if context 
15675:  was 'overwrite').
15676:  
15677: 
15678: =item *
15679: 
15680: renameuserfile(): renames an existing userfile to a new name
15681: 
15682:   Args:
15683:    docuname: username or courseid of destination for the file
15684:    docudom: domain of user/course of destination for the file
15685:    old: current file name (including any subdirs under userfiles)
15686:    new: desired file name (including any subdirs under userfiles)
15687: 
15688: =item *
15689: 
15690: mkdiruserfile(): creates a directory is a userfiles dir
15691: 
15692:   Args:
15693:    docuname: username or courseid of destination for the file
15694:    docudom: domain of user/course of destination for the file
15695:    dir: dir to create (including any subdirs under userfiles)
15696: 
15697: =item *
15698: 
15699: removeuserfile(): removes a file that exists in userfiles
15700: 
15701:   Args:
15702:    docuname: username or courseid of destination for the file
15703:    docudom: domain of user/course of destination for the file
15704:    fname: filname to delete (including any subdirs under userfiles)
15705: 
15706: =item *
15707: 
15708: removeuploadedurl(): convience function for removeuserfile()
15709: 
15710:   Args:
15711:    url:  a full /uploaded/... url to delete
15712: 
15713: =item * 
15714: 
15715: get_portfile_permissions():
15716:   Args:
15717:     domain: domain of user or course contain the portfolio files
15718:     user: name of user or num of course contain the portfolio files
15719:   Returns:
15720:     hashref of a dump of the proper file_permissions.db
15721:    
15722: 
15723: =item * 
15724: 
15725: get_access_controls():
15726: 
15727: Args:
15728:   current_permissions: the hash ref returned from get_portfile_permissions()
15729:   group: (optional) the group you want the files associated with
15730:   file: (optional) the file you want access info on
15731: 
15732: Returns:
15733:     a hash (keys are file names) of hashes containing
15734:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15735:         values are XML containing access control settings (see below) 
15736: 
15737: Internal notes:
15738: 
15739:  access controls are stored in file_permissions.db as key=value pairs.
15740:     key -> path to file/file_name\0uniqueID:scope_end_start
15741:         where scope -> public,guest,course,group,domains or users.
15742:               end -> UNIX time for end of access (0 -> no end date)
15743:               start -> UNIX time for start of access
15744: 
15745:     value -> XML description of access control
15746:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15747:             <start></start>
15748:             <end></end>
15749: 
15750:             <password></password>  for scope type = guest
15751: 
15752:             <domain></domain>     for scope type = course or group
15753:             <number></number>
15754:             <roles id="">
15755:              <role></role>
15756:              <access></access>
15757:              <section></section>
15758:              <group></group>
15759:             </roles>
15760: 
15761:             <dom></dom>         for scope type = domains
15762: 
15763:             <users>             for scope type = users
15764:              <user>
15765:               <uname></uname>
15766:               <udom></udom>
15767:              </user>
15768:             </users>
15769:            </scope> 
15770:               
15771:  Access data is also aggregated for each file in an additional key=value pair:
15772:  key -> path to file/file_name\0accesscontrol 
15773:  value -> reference to hash
15774:           hash contains key = value pairs
15775:           where key = uniqueID:scope_end_start
15776:                 value = UNIX time record was last updated
15777: 
15778:           Used to improve speed of look-ups of access controls for each file.  
15779:  
15780:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15781: 
15782: =item *
15783: 
15784: modify_access_controls():
15785: 
15786: Modifies access controls for a portfolio file
15787: Args
15788: 1. file name
15789: 2. reference to hash of required changes,
15790: 3. domain
15791: 4. username
15792:   where domain,username are the domain of the portfolio owner 
15793:   (either a user or a course) 
15794: 
15795: Returns:
15796: 1. result of additions or updates ('ok' or 'error', with error message). 
15797: 2. result of deletions ('ok' or 'error', with error message).
15798: 3. reference to hash of any new or updated access controls.
15799: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15800:    key = integer (inbound ID)
15801:    value = uniqueID
15802: 
15803: =item *
15804: 
15805: get_timebased_id():
15806: 
15807: Attempts to get a unique timestamp-based suffix for use with items added to a 
15808: course via the Course Editor (e.g., folders, composite pages, 
15809: group bulletin boards).
15810: 
15811: Args: (first three required; six others optional)
15812: 
15813: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15814:    docssequence, or name of group
15815: 
15816: 2. keyid (alphanumeric): name of temporary locking key in hash,
15817:    e.g., num, boardids
15818: 
15819: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15820:    file will be named nohist_namespace.db
15821: 
15822: 4. cdom: domain of course; default is current course domain from %env
15823: 
15824: 5. cnum: course number; default is current course number from %env
15825: 
15826: 6. idtype: set to concat if an additional digit is to be appended to the 
15827:    unix timestamp to form the suffix, if the plain timestamp is already
15828:    in use.  Default is to not do this, but simply increment the unix 
15829:    timestamp by 1 until a unique key is obtained.
15830: 
15831: 7. who: holder of locking key; defaults to user:domain for user.
15832: 
15833: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15834:    retrying); default is 3.
15835: 
15836: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15837: 
15838: Returns:
15839: 
15840: 1. suffix obtained (numeric)
15841: 
15842: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15843: 
15844: 3. error: contains (localized) error message if an error occurred.
15845: 
15846: 
15847: =back
15848: 
15849: =head2 HTTP Helper Routines
15850: 
15851: =over 4
15852: 
15853: =item *
15854: 
15855: escape() : unpack non-word characters into CGI-compatible hex codes
15856: 
15857: =item *
15858: 
15859: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15860: 
15861: =back
15862: 
15863: =head1 PRIVATE SUBROUTINES
15864: 
15865: =head2 Underlying communication routines (Shouldn't call)
15866: 
15867: =over 4
15868: 
15869: =item *
15870: 
15871: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15872: 
15873: =item *
15874: 
15875: reply() : uses subreply to send a message to remote machine, logs all failures
15876: 
15877: =item *
15878: 
15879: critical() : passes a critical message to another server; if cannot
15880: get through then place message in connection buffer directory and
15881: returns con_delayed, if incapable of saving message, returns
15882: con_failed
15883: 
15884: =item *
15885: 
15886: reconlonc() : tries to reconnect lonc client processes.
15887: 
15888: =back
15889: 
15890: =head2 Resource Access Logging
15891: 
15892: =over 4
15893: 
15894: =item *
15895: 
15896: flushcourselogs() : flush (save) buffer logs and access logs
15897: 
15898: =item *
15899: 
15900: courselog($what) : save message for course in hash
15901: 
15902: =item *
15903: 
15904: courseacclog($what) : save message for course using &courselog().  Perform
15905: special processing for specific resource types (problems, exams, quizzes, etc).
15906: 
15907: =item *
15908: 
15909: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15910: as a PerlChildExitHandler
15911: 
15912: =back
15913: 
15914: =head2 Other
15915: 
15916: =over 4
15917: 
15918: =item *
15919: 
15920: symblist($mapname,%newhash) : update symbolic storage links
15921: 
15922: =back
15923: 
15924: =cut
15925: 

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