File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1381: download - view: text, annotated - select for diffs
Thu Aug 9 14:04:35 2018 UTC (5 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Fewer calls to courseiddump() to check if something is a course.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1381 2018/08/09 14:04:35 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: 
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 20;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_servercerts_info {
  233:     my ($lonhost,$context) = @_;
  234:     my ($rep,$uselocal);
  235:     if (grep { $_ eq $lonhost } &current_machine_ids()) {
  236:         $uselocal = 1;
  237:     }
  238:     if (($context ne 'cgi') && ($uselocal)) {
  239:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  240:         if ($distro eq '') {
  241:             $uselocal = 0;
  242:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  243:             if ($1 < 6) {
  244:                 $uselocal = 0;
  245:             }
  246:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  247:             if ($1 < 12) {
  248:                 $uselocal = 0;
  249:             }
  250:         }
  251:     }
  252:     if ($uselocal) {
  253:         $rep = LONCAPA::Lond::server_certs(\%perlvar);
  254:     } else {
  255:         $rep=&reply('servercerts',$lonhost);
  256:     }
  257:     my ($result,%returnhash);
  258:     if (defined($lonhost)) {
  259:         if (!defined(&hostname($lonhost))) {
  260:             return;
  261:         }
  262:     }
  263:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  264:         ($rep eq 'unknown_cmd')) {
  265:         $result = $rep;
  266:     } else {
  267:         $result = 'ok';
  268:         my @pairs=split(/\&/,$rep);
  269:         foreach my $item (@pairs) {
  270:             my ($key,$value)=split(/=/,$item,2);
  271:             my $what = &unescape($key);
  272:             $returnhash{$what}=&thaw_unescape($value);
  273:         }
  274:     }
  275:     return ($result,\%returnhash);
  276: }
  277: 
  278: sub get_server_loncaparev {
  279:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  280:     if (defined($lonhost)) {
  281:         if (!defined(&hostname($lonhost))) {
  282:             undef($lonhost);
  283:         }
  284:     }
  285:     if (!defined($lonhost)) {
  286:         if (defined(&domain($dom,'primary'))) {
  287:             $lonhost=&domain($dom,'primary');
  288:             if ($lonhost eq 'no_host') {
  289:                 undef($lonhost);
  290:             }
  291:         }
  292:     }
  293:     if (defined($lonhost)) {
  294:         my $cachetime = 12*3600;
  295:         if (!$ignore_cache) {
  296:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  297:             if (defined($cached)) {
  298:                 return $loncaparev;
  299:             }
  300:         }
  301:         my ($answer,$loncaparev);
  302:         my @ids=&current_machine_ids();
  303:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  304:             $answer = $perlvar{'lonVersion'};
  305:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  306:                 $loncaparev = $1;
  307:             }
  308:         } else {
  309:             $answer = &reply('serverloncaparev',$lonhost);
  310:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  311:                 if ($caller eq 'loncron') {
  312:                     my $protocol = $protocol{$lonhost};
  313:                     $protocol = 'http' if ($protocol ne 'https');
  314:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  315:                     my $request=new HTTP::Request('GET',$url);
  316:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  317:                     unless ($response->is_error()) {
  318:                         my $content = $response->content;
  319:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  320:                             $loncaparev = $1;
  321:                         }
  322:                     }
  323:                 } else {
  324:                     $loncaparev = $loncaparevs{$lonhost};
  325:                 }
  326:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  327:                 $loncaparev = $1;
  328:             }
  329:         }
  330:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  331:     }
  332: }
  333: 
  334: sub get_server_homeID {
  335:     my ($hostname,$ignore_cache,$caller) = @_;
  336:     unless ($ignore_cache) {
  337:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  338:         if (defined($cached)) {
  339:             return $serverhomeID;
  340:         }
  341:     }
  342:     my $cachetime = 12*3600;
  343:     my $serverhomeID;
  344:     if ($caller eq 'loncron') { 
  345:         my @machine_ids = &machine_ids($hostname);
  346:         foreach my $id (@machine_ids) {
  347:             my $response = &reply('serverhomeID',$id);
  348:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  349:                 $serverhomeID = $response;
  350:                 last;
  351:             }
  352:         }
  353:         if ($serverhomeID eq '') {
  354:             $serverhomeID = $machine_ids[-1];
  355:         }
  356:     } else {
  357:         $serverhomeID = $serverhomeIDs{$hostname};
  358:     }
  359:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  360: }
  361: 
  362: sub get_remote_globals {
  363:     my ($lonhost,$whathash,$ignore_cache) = @_;
  364:     my ($result,%returnhash,%whatneeded);
  365:     if (ref($whathash) eq 'HASH') {
  366:         foreach my $what (sort(keys(%{$whathash}))) {
  367:             my $hashid = $lonhost.'-'.$what;
  368:             my ($response,$cached);
  369:             unless ($ignore_cache) {
  370:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  371:             }
  372:             if (defined($cached)) {
  373:                 $returnhash{$what} = $response;
  374:             } else {
  375:                 $whatneeded{$what} = 1;
  376:             }
  377:         }
  378:         if (keys(%whatneeded) == 0) {
  379:             $result = 'ok';
  380:         } else {
  381:             my $requested = &freeze_escape(\%whatneeded);
  382:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  383:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  384:                 ($rep eq 'unknown_cmd')) {
  385:                 $result = $rep;
  386:             } else {
  387:                 $result = 'ok';
  388:                 my @pairs=split(/\&/,$rep);
  389:                 foreach my $item (@pairs) {
  390:                     my ($key,$value)=split(/=/,$item,2);
  391:                     my $what = &unescape($key);
  392:                     my $hashid = $lonhost.'-'.$what;
  393:                     $returnhash{$what}=&thaw_unescape($value);
  394:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  395:                 }
  396:             }
  397:         }
  398:     }
  399:     return ($result,\%returnhash);
  400: }
  401: 
  402: sub remote_devalidate_cache {
  403:     my ($lonhost,$cachekeys) = @_;
  404:     my $items;
  405:     return unless (ref($cachekeys) eq 'ARRAY');
  406:     my $cachestr = join('&',@{$cachekeys});
  407:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  408:     return $response;
  409: }
  410: 
  411: # -------------------------------------------------- Non-critical communication
  412: sub subreply {
  413:     my ($cmd,$server)=@_;
  414:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  415:     #
  416:     #  With loncnew process trimming, there's a timing hole between lonc server
  417:     #  process exit and the master server picking up the listen on the AF_UNIX
  418:     #  socket.  In that time interval, a lock file will exist:
  419: 
  420:     my $lockfile=$peerfile.".lock";
  421:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  422: 	sleep(0.1);
  423:     }
  424:     # At this point, either a loncnew parent is listening or an old lonc
  425:     # or loncnew child is listening so we can connect or everything's dead.
  426:     #
  427:     #   We'll give the connection a few tries before abandoning it.  If
  428:     #   connection is not possible, we'll con_lost back to the client.
  429:     #   
  430:     my $client;
  431:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  432: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  433: 				      Type    => SOCK_STREAM,
  434: 				      Timeout => 10);
  435: 	if ($client) {
  436: 	    last;		# Connected!
  437: 	} else {
  438: 	    &create_connection(&hostname($server),$server);
  439: 	}
  440:         sleep(0.1);	# Try again later if failed connection.
  441:     }
  442:     my $answer;
  443:     if ($client) {
  444: 	print $client "sethost:$server:$cmd\n";
  445: 	$answer=<$client>;
  446: 	if (!$answer) { $answer="con_lost"; }
  447: 	chomp($answer);
  448:     } else {
  449: 	$answer = 'con_lost';	# Failed connection.
  450:     }
  451:     return $answer;
  452: }
  453: 
  454: sub reply {
  455:     my ($cmd,$server)=@_;
  456:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  457:     my $answer=subreply($cmd,$server);
  458:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  459:        &logthis("<font color=\"blue\">WARNING:".
  460:                 " $cmd to $server returned $answer</font>");
  461:     }
  462:     return $answer;
  463: }
  464: 
  465: # ----------------------------------------------------------- Send USR1 to lonc
  466: 
  467: sub reconlonc {
  468:     my ($lonid) = @_;
  469:     if ($lonid) {
  470:         my $hostname = &hostname($lonid);
  471: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  472: 	if ($hostname && -e $peerfile) {
  473: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  474: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  475: 					     Type    => SOCK_STREAM,
  476: 					     Timeout => 10);
  477: 	    if ($client) {
  478: 		print $client ("reset_retries\n");
  479: 		my $answer=<$client>;
  480: 		#reset just this one.
  481: 	    }
  482: 	}
  483: 	return;
  484:     }
  485: 
  486:     &logthis("Trying to reconnect lonc");
  487:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  488:     if (open(my $fh,"<",$loncfile)) {
  489: 	my $loncpid=<$fh>;
  490:         chomp($loncpid);
  491:         if (kill 0 => $loncpid) {
  492: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  493:             kill USR1 => $loncpid;
  494:             sleep 1;
  495:         } else {
  496: 	    &logthis(
  497:                "<font color=\"blue\">WARNING:".
  498:                " lonc at pid $loncpid not responding, giving up</font>");
  499:         }
  500:     } else {
  501: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  502:     }
  503: }
  504: 
  505: # ------------------------------------------------------ Critical communication
  506: 
  507: sub critical {
  508:     my ($cmd,$server)=@_;
  509:     unless (&hostname($server)) {
  510:         &logthis("<font color=\"blue\">WARNING:".
  511:                " Critical message to unknown server ($server)</font>");
  512:         return 'no_such_host';
  513:     }
  514:     my $answer=reply($cmd,$server);
  515:     if ($answer eq 'con_lost') {
  516: 	&reconlonc($server);
  517: 	my $answer=reply($cmd,$server);
  518:         if ($answer eq 'con_lost') {
  519:             my $now=time;
  520:             my $middlename=$cmd;
  521:             $middlename=substr($middlename,0,16);
  522:             $middlename=~s/\W//g;
  523:             my $dfilename=
  524:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  525:             $dumpcount++;
  526:             {
  527: 		my $dfh;
  528: 		if (open($dfh,">",$dfilename)) {
  529: 		    print $dfh "$cmd\n"; 
  530: 		    close($dfh);
  531: 		}
  532:             }
  533:             sleep 1;
  534:             my $wcmd='';
  535:             {
  536: 		my $dfh;
  537: 		if (open($dfh,"<",$dfilename)) {
  538: 		    $wcmd=<$dfh>; 
  539: 		    close($dfh);
  540: 		}
  541:             }
  542:             chomp($wcmd);
  543:             if ($wcmd eq $cmd) {
  544: 		&logthis("<font color=\"blue\">WARNING: ".
  545:                          "Connection buffer $dfilename: $cmd</font>");
  546:                 &logperm("D:$server:$cmd");
  547: 	        return 'con_delayed';
  548:             } else {
  549:                 &logthis("<font color=\"red\">CRITICAL:"
  550:                         ." Critical connection failed: $server $cmd</font>");
  551:                 &logperm("F:$server:$cmd");
  552:                 return 'con_failed';
  553:             }
  554:         }
  555:     }
  556:     return $answer;
  557: }
  558: 
  559: # ------------------------------------------- check if return value is an error
  560: 
  561: sub error {
  562:     my ($result) = @_;
  563:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  564: 	if ($2 == 2) { return undef; }
  565: 	return $1;
  566:     }
  567:     return undef;
  568: }
  569: 
  570: sub convert_and_load_session_env {
  571:     my ($lonidsdir,$handle)=@_;
  572:     my @profile;
  573:     {
  574: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  575: 	if (!$opened) {
  576: 	    return 0;
  577: 	}
  578: 	flock($idf,LOCK_SH);
  579: 	@profile=<$idf>;
  580: 	close($idf);
  581:     }
  582:     my %temp_env;
  583:     foreach my $line (@profile) {
  584: 	if ($line !~ m/=/) {
  585: 	    return 0;
  586: 	}
  587: 	chomp($line);
  588: 	my ($envname,$envvalue)=split(/=/,$line,2);
  589: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  590:     }
  591:     unlink("$lonidsdir/$handle.id");
  592:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  593: 	    0640)) {
  594: 	%disk_env = %temp_env;
  595: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  596: 	untie(%disk_env);
  597:     }
  598:     return 1;
  599: }
  600: 
  601: # ------------------------------------------- Transfer profile into environment
  602: my $env_loaded;
  603: sub transfer_profile_to_env {
  604:     my ($lonidsdir,$handle,$force_transfer) = @_;
  605:     if (!$force_transfer && $env_loaded) { return; } 
  606: 
  607:     if (!defined($lonidsdir)) {
  608: 	$lonidsdir = $perlvar{'lonIDsDir'};
  609:     }
  610:     if (!defined($handle)) {
  611:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  612:     }
  613: 
  614:     my $convert;
  615:     {
  616:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  617: 	if (!$opened) {
  618: 	    return;
  619: 	}
  620: 	flock($idf,LOCK_SH);
  621: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  622: 		&GDBM_READER(),0640)) {
  623: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  624: 	    untie(%disk_env);
  625: 	} else {
  626: 	    $convert = 1;
  627: 	}
  628:     }
  629:     if ($convert) {
  630: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  631: 	    &logthis("Failed to load session, or convert session.");
  632: 	}
  633:     }
  634: 
  635:     my %remove;
  636:     while ( my $envname = each(%env) ) {
  637:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  638:             if ($time < time-300) {
  639:                 $remove{$key}++;
  640:             }
  641:         }
  642:     }
  643: 
  644:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  645:     $env_loaded=1;
  646:     foreach my $expired_key (keys(%remove)) {
  647:         &delenv($expired_key);
  648:     }
  649: }
  650: 
  651: # ---------------------------------------------------- Check for valid session 
  652: sub check_for_valid_session {
  653:     my ($r,$name,$userhashref,$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 $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
 3201: 
 3202:     if (wantarray) {
 3203: 	return ($response->content, $response);
 3204:     } else {
 3205: 	return $response->content;
 3206:     }
 3207: }
 3208: 
 3209: sub externalssi {
 3210:     my ($url)=@_;
 3211:     my $request=new HTTP::Request('GET',$url);
 3212:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3213:     if (wantarray) {
 3214:         return ($response->content, $response);
 3215:     } else {
 3216:         return $response->content;
 3217:     }
 3218: }
 3219: 
 3220: 
 3221: # If the local copy of a replicated resource is outdated, trigger a  
 3222: # connection from the homeserver to flush the delayed queue. If no update 
 3223: # happens, remove local copies of outdated resource (and corresponding
 3224: # metadata file).
 3225: 
 3226: sub remove_stale_resfile {
 3227:     my ($url) = @_;
 3228:     my $removed;
 3229:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3230:         my $audom = $1;
 3231:         my $auname = $2;
 3232:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3233:             my $homeserver = &homeserver($auname,$audom);
 3234:             unless (($homeserver eq 'no_host') ||
 3235:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3236:                 my $fname = &filelocation('',$url);
 3237:                 if (-e $fname) {
 3238:                     my $protocol = $protocol{$homeserver};
 3239:                     $protocol = 'http' if ($protocol ne 'https');
 3240:                     my $hostname = &hostname($homeserver);
 3241:                     if ($hostname) {
 3242:                         my $uri = &declutter($url);
 3243:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3244:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3245:                         if ($response->is_success()) {
 3246:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3247:                             my $locmodtime = (stat($fname))[9];
 3248:                             if ($locmodtime < $remmodtime) {
 3249:                                 my $stale;
 3250:                                 my $answer = &reply('pong',$homeserver);
 3251:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3252:                                     sleep(0.2);
 3253:                                     $locmodtime = (stat($fname))[9];
 3254:                                     if ($locmodtime < $remmodtime) {
 3255:                                         my $posstransfer = $fname.'.in.transfer';
 3256:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3257:                                             $removed = 1;
 3258:                                         } else {
 3259:                                             $stale = 1;
 3260:                                         }
 3261:                                     } else {
 3262:                                         $removed = 1;
 3263:                                     }
 3264:                                 } else {
 3265:                                     $stale = 1;
 3266:                                 }
 3267:                                 if ($stale) {
 3268:                                     unlink($fname);
 3269:                                     if ($uri!~/\.meta$/) {
 3270:                                         unlink($fname.'.meta');
 3271:                                     }
 3272:                                     &reply("unsub:$fname",$homeserver);
 3273:                                     $removed = 1;
 3274:                                 }
 3275:                             }
 3276:                         }
 3277:                     }
 3278:                 }
 3279:             }
 3280:         }
 3281:     }
 3282:     return $removed;
 3283: }
 3284: 
 3285: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3286: 
 3287: sub allowuploaded {
 3288:     my ($srcurl,$url)=@_;
 3289:     $url=&clutter(&declutter($url));
 3290:     my $dir=$url;
 3291:     $dir=~s/\/[^\/]+$//;
 3292:     my %httpref=();
 3293:     my $httpurl=&hreflocation('',$url);
 3294:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3295:     &Apache::lonnet::appenv(\%httpref);
 3296: }
 3297: 
 3298: #
 3299: # Determine if the current user should be able to edit a particular resource,
 3300: # when viewing in course context.
 3301: # (a) When viewing resource used to determine if "Edit" item is included in 
 3302: #     Functions.
 3303: # (b) When displaying folder contents in course editor, used to determine if
 3304: #     "Edit" link will be displayed alongside resource.
 3305: #
 3306: #  input: six args -- filename (decluttered), course number, course domain,
 3307: #                   url, symb (if registered) and group (if this is a group
 3308: #                   item -- e.g., bulletin board, group page etc.).
 3309: #  output: array of five scalars -- 
 3310: #          $cfile -- url for file editing if editable on current server
 3311: #          $home -- homeserver of resource (i.e., for author if published,
 3312: #                                           or course if uploaded.).
 3313: #          $switchserver --  1 if server switch will be needed.
 3314: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3315: #          $forceview -- 1 if icon/link should be to go to view mode
 3316: #
 3317: 
 3318: sub can_edit_resource {
 3319:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3320:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3321: #
 3322: # For aboutme pages user can only edit his/her own.
 3323: #
 3324:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3325:         my ($sdom,$sname) = ($1,$2);
 3326:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3327:             $home = $env{'user.home'};
 3328:             $cfile = $resurl;
 3329:             if ($env{'form.forceedit'}) {
 3330:                 $forceview = 1;
 3331:             } else {
 3332:                 $forceedit = 1;
 3333:             }
 3334:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3335:         } else {
 3336:             return;
 3337:         }
 3338:     }
 3339: 
 3340:     if ($env{'request.course.id'}) {
 3341:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3342:         if ($group ne '') {
 3343: # if this is a group homepage or group bulletin board, check group privs
 3344:             my $allowed = 0;
 3345:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3346:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3347:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3348:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3349:                     $allowed = 1;
 3350:                 }
 3351:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3352:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3353:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3354:                     $allowed = 1;
 3355:                 }
 3356:             }
 3357:             if ($allowed) {
 3358:                 $home=&homeserver($cnum,$cdom);
 3359:                 if ($env{'form.forceedit'}) {
 3360:                     $forceview = 1;
 3361:                 } else {
 3362:                     $forceedit = 1;
 3363:                 }
 3364:                 $cfile = $resurl;
 3365:             } else {
 3366:                 return;
 3367:             }
 3368:         } else {
 3369:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3370:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3371:                     return;
 3372:                 }
 3373:             } elsif (!$crsedit) {
 3374: #
 3375: # No edit allowed where CC has switched to student role.
 3376: #
 3377:                 return;
 3378:             }
 3379:         }
 3380:     }
 3381: 
 3382:     if ($file ne '') {
 3383:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3384:             if (&is_course_upload($file,$cnum,$cdom)) {
 3385:                 $uploaded = 1;
 3386:                 $incourse = 1;
 3387:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3388:                     $cfile = &hreflocation('',$file);
 3389:                     if ($env{'form.forceedit'}) {
 3390:                         $forceview = 1;
 3391:                     } else {
 3392:                         $forceedit = 1;
 3393:                     }
 3394:                 }
 3395:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3396:                 $incourse = 1;
 3397:                 if ($env{'form.forceedit'}) {
 3398:                     $forceview = 1;
 3399:                 } else {
 3400:                     $forceedit = 1;
 3401:                 }
 3402:                 $cfile = $resurl;
 3403:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3404:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3405:                     $incourse = 1;
 3406:                     if ($env{'form.forceedit'}) {
 3407:                         $forceview = 1;
 3408:                     } else {
 3409:                         $forceedit = 1;
 3410:                     }
 3411:                     $cfile = $resurl;
 3412:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3413:                     $incourse = 1;
 3414:                     $cfile = $resurl.'/smpedit';
 3415:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3416:                     $incourse = 1;
 3417:                     if ($env{'form.forceedit'}) {
 3418:                         $forceview = 1;
 3419:                     } else {
 3420:                         $forceedit = 1;
 3421:                     }
 3422:                     $cfile = $resurl;
 3423:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3424:                     $incourse = 1;
 3425:                     if ($env{'form.forceedit'}) {
 3426:                         $forceview = 1;
 3427:                     } else {
 3428:                         $forceedit = 1;
 3429:                     }
 3430:                     $cfile = $resurl;
 3431:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3432:                     $incourse = 1;
 3433:                     if ($env{'form.forceedit'}) {
 3434:                         $forceview = 1;
 3435:                     } else {
 3436:                         $forceedit = 1;
 3437:                     }
 3438:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3439:                 }
 3440:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3441:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3442:                 if (&is_on_map($template)) { 
 3443:                     $incourse = 1;
 3444:                     $forceview = 1;
 3445:                     $cfile = $template;
 3446:                 }
 3447:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3448:                     $incourse = 1;
 3449:                     if ($env{'form.forceedit'}) {
 3450:                         $forceview = 1;
 3451:                     } else {
 3452:                         $forceedit = 1;
 3453:                     }
 3454:                     $cfile = $resurl;
 3455:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3456:                 $incourse = 1;
 3457:                 if ($env{'form.forceedit'}) {
 3458:                     $forceview = 1;
 3459:                 } else {
 3460:                     $forceedit = 1;
 3461:                 }
 3462:                 $cfile = $resurl;
 3463:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3464:                 $incourse = 1;
 3465:                 $forceview = 1;
 3466:                 if ($symb) {
 3467:                     my ($map,$id,$res)=&decode_symb($symb);
 3468:                     $env{'request.symb'} = $symb;
 3469:                     $cfile = &clutter($res);
 3470:                 } else {
 3471:                     $cfile = $env{'form.suppurl'};
 3472:                     my $escfile = &unescape($cfile);
 3473:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3474:                         $cfile = '/adm/wrapper'.$escfile;
 3475:                     } else {
 3476:                         $escfile =~ s{^http://}{};
 3477:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3478:                     }
 3479:                 }
 3480:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3481:                 if ($env{'form.forceedit'}) {
 3482:                     $forceview = 1;
 3483:                 } else {
 3484:                     $forceedit = 1;
 3485:                 }
 3486:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3487:             }
 3488:         }
 3489:         if ($uploaded || $incourse) {
 3490:             $home=&homeserver($cnum,$cdom);
 3491:         } elsif ($file !~ m{/$}) {
 3492:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3493:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3494:             # Check that the user has permission to edit this resource
 3495:             my $setpriv = 1;
 3496:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3497:             if (defined($cfudom)) {
 3498:                 $home=&homeserver($cfuname,$cfudom);
 3499:                 $cfile=$file;
 3500:             }
 3501:         }
 3502:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3503:             (($home ne '') && ($home ne 'no_host'))) {
 3504:             my @ids=&current_machine_ids();
 3505:             unless (grep(/^\Q$home\E$/,@ids)) {
 3506:                 $switchserver=1;
 3507:             }
 3508:         }
 3509:     }
 3510:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3511: }
 3512: 
 3513: sub is_course_upload {
 3514:     my ($file,$cnum,$cdom) = @_;
 3515:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3516:     $uploadpath =~ s{^\/}{};
 3517:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3518:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3519:         return 1;
 3520:     }
 3521:     return;
 3522: }
 3523: 
 3524: sub in_course {
 3525:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3526:     if ($hideprivileged) {
 3527:         my $skipuser;
 3528:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3529:         my @possdoms = ($cdom);  
 3530:         if ($coursehash{'checkforpriv'}) { 
 3531:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3532:         }
 3533:         if (&privileged($uname,$udom,\@possdoms)) {
 3534:             $skipuser = 1;
 3535:             if ($coursehash{'nothideprivileged'}) {
 3536:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3537:                     my $user;
 3538:                     if ($item =~ /:/) {
 3539:                         $user = $item;
 3540:                     } else {
 3541:                         $user = join(':',split(/[\@]/,$item));
 3542:                     }
 3543:                     if ($user eq $uname.':'.$udom) {
 3544:                         undef($skipuser);
 3545:                         last;
 3546:                     }
 3547:                 }
 3548:             }
 3549:             if ($skipuser) {
 3550:                 return 0;
 3551:             }
 3552:         }
 3553:     }
 3554:     $type ||= 'any';
 3555:     if (!defined($cdom) || !defined($cnum)) {
 3556:         my $cid  = $env{'request.course.id'};
 3557:         $cdom = $env{'course.'.$cid.'.domain'};
 3558:         $cnum = $env{'course.'.$cid.'.num'};
 3559:     }
 3560:     my $typesref;
 3561:     if (($type eq 'any') || ($type eq 'all')) {
 3562:         $typesref = ['active','previous','future'];
 3563:     } elsif ($type eq 'previous' || $type eq 'future') {
 3564:         $typesref = [$type];
 3565:     }
 3566:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3567:                               $typesref,undef,[$cdom]);
 3568:     my ($tmp) = keys(%roles);
 3569:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3570:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3571:     if (@course_roles > 0) {
 3572:         return 1;
 3573:     }
 3574:     return 0;
 3575: }
 3576: 
 3577: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3578: # input: action, courseID, current domain, intended
 3579: #        path to file, source of file, instruction to parse file for objects,
 3580: #        ref to hash for embedded objects,
 3581: #        ref to hash for codebase of java objects.
 3582: #        reference to scalar to accommodate mime type determined
 3583: #          from File::MMagic if $parser = parse.
 3584: #
 3585: # output: url to file (if action was uploaddoc), 
 3586: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3587: #
 3588: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3589: # course.
 3590: #
 3591: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3592: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3593: #          course's home server.
 3594: #
 3595: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3596: #          be copied from $source (current location) to 
 3597: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3598: #         and will then be copied to
 3599: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3600: #         course's home server.
 3601: #
 3602: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3603: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3604: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3605: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3606: #         in course's home server.
 3607: #
 3608: 
 3609: sub process_coursefile {
 3610:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3611:         $mimetype)=@_;
 3612:     my $fetchresult;
 3613:     my $home=&homeserver($docuname,$docudom);
 3614:     if ($action eq 'propagate') {
 3615:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3616: 			     $home);
 3617:     } else {
 3618:         my $fpath = '';
 3619:         my $fname = $file;
 3620:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3621:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3622:         my $filepath = &build_filepath($fpath);
 3623:         if ($action eq 'copy') {
 3624:             if ($source eq '') {
 3625:                 $fetchresult = 'no source file';
 3626:                 return $fetchresult;
 3627:             } else {
 3628:                 my $destination = $filepath.'/'.$fname;
 3629:                 rename($source,$destination);
 3630:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3631:                                  $home);
 3632:             }
 3633:         } elsif ($action eq 'uploaddoc') {
 3634:             open(my $fh,'>',$filepath.'/'.$fname);
 3635:             print $fh $env{'form.'.$source};
 3636:             close($fh);
 3637:             if ($parser eq 'parse') {
 3638:                 my $mm = new File::MMagic;
 3639:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3640:                 if ($type eq 'text/html') {
 3641:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3642:                     unless ($parse_result eq 'ok') {
 3643:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3644:                     }
 3645:                 }
 3646:                 if (ref($mimetype)) {
 3647:                     $$mimetype = $type;
 3648:                 } 
 3649:             }
 3650:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3651:                                  $home);
 3652:             if ($fetchresult eq 'ok') {
 3653:                 return '/uploaded/'.$fpath.'/'.$fname;
 3654:             } else {
 3655:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3656:                         ' to host '.$home.': '.$fetchresult);
 3657:                 return '/adm/notfound.html';
 3658:             }
 3659:         }
 3660:     }
 3661:     unless ( $fetchresult eq 'ok') {
 3662:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3663:              ' to host '.$home.': '.$fetchresult);
 3664:     }
 3665:     return $fetchresult;
 3666: }
 3667: 
 3668: sub build_filepath {
 3669:     my ($fpath) = @_;
 3670:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3671:     unless ($fpath eq '') {
 3672:         my @parts=split('/',$fpath);
 3673:         foreach my $part (@parts) {
 3674:             $filepath.= '/'.$part;
 3675:             if ((-e $filepath)!=1) {
 3676:                 mkdir($filepath,0777);
 3677:             }
 3678:         }
 3679:     }
 3680:     return $filepath;
 3681: }
 3682: 
 3683: sub store_edited_file {
 3684:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3685:     my $file = $primary_url;
 3686:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3687:     my $fpath = '';
 3688:     my $fname = $file;
 3689:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3690:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3691:     my $filepath = &build_filepath($fpath);
 3692:     open(my $fh,'>',$filepath.'/'.$fname);
 3693:     print $fh $content;
 3694:     close($fh);
 3695:     my $home=&homeserver($docuname,$docudom);
 3696:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3697: 			  $home);
 3698:     if ($$fetchresult eq 'ok') {
 3699:         return '/uploaded/'.$fpath.'/'.$fname;
 3700:     } else {
 3701:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3702: 		 ' to host '.$home.': '.$$fetchresult);
 3703:         return '/adm/notfound.html';
 3704:     }
 3705: }
 3706: 
 3707: sub clean_filename {
 3708:     my ($fname,$args)=@_;
 3709: # Replace Windows backslashes by forward slashes
 3710:     $fname=~s/\\/\//g;
 3711:     if (!$args->{'keep_path'}) {
 3712:         # Get rid of everything but the actual filename
 3713: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3714:     }
 3715: # Replace spaces by underscores
 3716:     $fname=~s/\s+/\_/g;
 3717: # Replace all other weird characters by nothing
 3718:     $fname=~s{[^/\w\.\-]}{}g;
 3719: # Replace all .\d. sequences with _\d. so they no longer look like version
 3720: # numbers
 3721:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3722:     return $fname;
 3723: }
 3724: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3725: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3726: # image with the same aspect ratio as the original, but with dimensions which do 
 3727: # not exceed $resizewidth and $resizeheight.
 3728:  
 3729: sub resizeImage {
 3730:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3731:     my $ima = Image::Magick->new;
 3732:     my $resized;
 3733:     if (-e $img_path) {
 3734:         $ima->Read($img_path);
 3735:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3736:             my $width = $ima->Get('width');
 3737:             my $height = $ima->Get('height');
 3738:             if ($width > $resizewidth) {
 3739: 	        my $factor = $width/$resizewidth;
 3740:                 my $newheight = $height/$factor;
 3741:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3742:                 $resized = 1;
 3743:             }
 3744:         }
 3745:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3746:             my $width = $ima->Get('width');
 3747:             my $height = $ima->Get('height');
 3748:             if ($height > $resizeheight) {
 3749:                 my $factor = $height/$resizeheight;
 3750:                 my $newwidth = $width/$factor;
 3751:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3752:                 $resized = 1;
 3753:             }
 3754:         }
 3755:         if ($resized) {
 3756:             $ima->Write($img_path);
 3757:         }
 3758:     }
 3759:     return;
 3760: }
 3761: 
 3762: # --------------- Take an uploaded file and put it into the userfiles directory
 3763: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3764: #                    the desired filename is in $env{"form.$formname.filename"}
 3765: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3766: #                                    canceloverwrite, or ''. 
 3767: #                   if 'coursedoc': upload to the current course
 3768: #                   if 'existingfile': write file to tmp/overwrites directory 
 3769: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3770: #                   $context is passed as argument to &finishuserfileupload
 3771: #        $subdir - directory in userfile to store the file into
 3772: #        $parser - instruction to parse file for objects ($parser = parse)    
 3773: #        $allfiles - reference to hash for embedded objects
 3774: #        $codebase - reference to hash for codebase of java objects
 3775: #        $desuname - username for permanent storage of uploaded file
 3776: #        $dsetudom - domain for permanaent storage of uploaded file
 3777: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3778: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3779: #        $resizewidth - width (pixels) to which to resize uploaded image
 3780: #        $resizeheight - height (pixels) to which to resize uploaded image
 3781: #        $mimetype - reference to scalar to accommodate mime type determined
 3782: #                    from File::MMagic.
 3783: # 
 3784: # output: url of file in userspace, or error: <message> 
 3785: #             or /adm/notfound.html if failure to upload occurse
 3786: 
 3787: sub userfileupload {
 3788:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3789:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3790:     if (!defined($subdir)) { $subdir='unknown'; }
 3791:     my $fname=$env{'form.'.$formname.'.filename'};
 3792:     $fname=&clean_filename($fname);
 3793:     # See if there is anything left
 3794:     unless ($fname) { return 'error: no uploaded file'; }
 3795:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3796:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3797:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3798:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3799:         my $now = time;
 3800:         my $filepath;
 3801:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3802:              $filepath = 'tmp/helprequests/'.$now;
 3803:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3804:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3805:                          '_'.$env{'user.domain'}.'/pending';
 3806:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3807:             my ($docuname,$docudom);
 3808:             if ($destudom =~ /^$match_domain$/) {
 3809:                 $docudom = $destudom;
 3810:             } else {
 3811:                 $docudom = $env{'user.domain'};
 3812:             }
 3813:             if ($destuname =~ /^$match_username$/) {
 3814:                 $docuname = $destuname;
 3815:             } else {
 3816:                 $docuname = $env{'user.name'};
 3817:             }
 3818:             if (exists($env{'form.group'})) {
 3819:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3820:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3821:             }
 3822:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3823:             if ($context eq 'canceloverwrite') {
 3824:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3825:                 if (-e  $tempfile) {
 3826:                     my @info = stat($tempfile);
 3827:                     if ($info[9] eq $env{'form.timestamp'}) {
 3828:                         unlink($tempfile);
 3829:                     }
 3830:                 }
 3831:                 return;
 3832:             }
 3833:         }
 3834:         # Create the directory if not present
 3835:         my @parts=split(/\//,$filepath);
 3836:         my $fullpath = $perlvar{'lonDaemons'};
 3837:         for (my $i=0;$i<@parts;$i++) {
 3838:             $fullpath .= '/'.$parts[$i];
 3839:             if ((-e $fullpath)!=1) {
 3840:                 mkdir($fullpath,0777);
 3841:             }
 3842:         }
 3843:         open(my $fh,'>',$fullpath.'/'.$fname);
 3844:         print $fh $env{'form.'.$formname};
 3845:         close($fh);
 3846:         if ($context eq 'existingfile') {
 3847:             my @info = stat($fullpath.'/'.$fname);
 3848:             return ($fullpath.'/'.$fname,$info[9]);
 3849:         } else {
 3850:             return $fullpath.'/'.$fname;
 3851:         }
 3852:     }
 3853:     if ($subdir eq 'scantron') {
 3854:         $fname = 'scantron_orig_'.$fname;
 3855:     } else {
 3856:         $fname="$subdir/$fname";
 3857:     }
 3858:     if ($context eq 'coursedoc') {
 3859: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3860: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3861:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3862:             return &finishuserfileupload($docuname,$docudom,
 3863: 					 $formname,$fname,$parser,$allfiles,
 3864: 					 $codebase,$thumbwidth,$thumbheight,
 3865:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3866:         } else {
 3867:             if ($env{'form.folder'}) {
 3868:                 $fname=$env{'form.folder'}.'/'.$fname;
 3869:             }
 3870:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3871: 				       $fname,$formname,$parser,
 3872: 				       $allfiles,$codebase,$mimetype);
 3873:         }
 3874:     } elsif (defined($destuname)) {
 3875:         my $docuname=$destuname;
 3876:         my $docudom=$destudom;
 3877: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3878: 				     $parser,$allfiles,$codebase,
 3879:                                      $thumbwidth,$thumbheight,
 3880:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3881:     } else {
 3882:         my $docuname=$env{'user.name'};
 3883:         my $docudom=$env{'user.domain'};
 3884:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3885:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3886:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3887:         }
 3888: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3889: 				     $parser,$allfiles,$codebase,
 3890:                                      $thumbwidth,$thumbheight,
 3891:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3892:     }
 3893: }
 3894: 
 3895: sub finishuserfileupload {
 3896:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3897:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3898:     my $path=$docudom.'/'.$docuname.'/';
 3899:     my $filepath=$perlvar{'lonDocRoot'};
 3900:   
 3901:     my ($fnamepath,$file,$fetchthumb);
 3902:     $file=$fname;
 3903:     if ($fname=~m|/|) {
 3904:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3905: 	$path.=$fnamepath.'/';
 3906:     }
 3907:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3908:     my $count;
 3909:     for ($count=4;$count<=$#parts;$count++) {
 3910:         $filepath.="/$parts[$count]";
 3911:         if ((-e $filepath)!=1) {
 3912: 	    mkdir($filepath,0777);
 3913:         }
 3914:     }
 3915: 
 3916: # Save the file
 3917:     {
 3918: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 3919: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3920: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3921: 	    return '/adm/notfound.html';
 3922: 	}
 3923:         if ($context eq 'overwrite') {
 3924:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3925:             my $target = $filepath.'/'.$file;
 3926:             if (-e $source) {
 3927:                 my @info = stat($source);
 3928:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3929:                     unless (&File::Copy::move($source,$target)) {
 3930:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3931:                         return "Moving from $source failed";
 3932:                     }
 3933:                 } else {
 3934:                     return "Temporary file: $source had unexpected date/time for last modification";
 3935:                 }
 3936:             } else {
 3937:                 return "Temporary file: $source missing";
 3938:             }
 3939:         } elsif (!print FH ($env{'form.'.$formname})) {
 3940: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3941: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3942: 	    return '/adm/notfound.html';
 3943: 	}
 3944: 	close(FH);
 3945:         if ($resizewidth && $resizeheight) {
 3946:             my $mm = new File::MMagic;
 3947:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3948:             if ($mime_type =~ m{^image/}) {
 3949: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3950:             }  
 3951: 	}
 3952:     }
 3953:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3954:         if (ref($mimetype)) {
 3955:             if ($$mimetype eq '') {
 3956:                 my $mm = new File::MMagic;
 3957:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3958:                 $$mimetype = $type;
 3959:             }
 3960:         }
 3961:     }
 3962:     if ($parser eq 'parse') {
 3963:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3964:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3965:                                                        $allfiles,$codebase);
 3966:             unless ($parse_result eq 'ok') {
 3967:                 &logthis('Failed to parse '.$filepath.$file.
 3968: 	   	         ' for embedded media: '.$parse_result); 
 3969:             }
 3970:         }
 3971:     }
 3972:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3973:         my $input = $filepath.'/'.$file;
 3974:         my $output = $filepath.'/'.'tn-'.$file;
 3975:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3976:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 3977:         system({$args[0]} @args);
 3978:         if (-e $filepath.'/'.'tn-'.$file) {
 3979:             $fetchthumb  = 1; 
 3980:         }
 3981:     }
 3982:  
 3983: # Notify homeserver to grep it
 3984: #
 3985:     my $docuhome=&homeserver($docuname,$docudom);	
 3986:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3987:     if ($fetchresult eq 'ok') {
 3988:         if ($fetchthumb) {
 3989:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3990:             if ($thumbresult ne 'ok') {
 3991:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3992:                          $docuhome.': '.$thumbresult);
 3993:             }
 3994:         }
 3995: #
 3996: # Return the URL to it
 3997:         return '/uploaded/'.$path.$file;
 3998:     } else {
 3999:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4000: 		 ': '.$fetchresult);
 4001:         return '/adm/notfound.html';
 4002:     }
 4003: }
 4004: 
 4005: sub extract_embedded_items {
 4006:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4007:     my @state = ();
 4008:     my (%lastids,%related,%shockwave,%flashvars);
 4009:     my %javafiles = (
 4010:                       codebase => '',
 4011:                       code => '',
 4012:                       archive => ''
 4013:                     );
 4014:     my %mediafiles = (
 4015:                       src => '',
 4016:                       movie => '',
 4017:                      );
 4018:     my $p;
 4019:     if ($content) {
 4020:         $p = HTML::LCParser->new($content);
 4021:     } else {
 4022:         $p = HTML::LCParser->new($fullpath);
 4023:     }
 4024:     while (my $t=$p->get_token()) {
 4025: 	if ($t->[0] eq 'S') {
 4026: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4027: 	    push(@state, $tagname);
 4028:             if (lc($tagname) eq 'allow') {
 4029:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4030:             }
 4031: 	    if (lc($tagname) eq 'img') {
 4032: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4033: 	    }
 4034: 	    if (lc($tagname) eq 'a') {
 4035:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4036:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4037:                 }
 4038: 	    }
 4039:             if (lc($tagname) eq 'script') {
 4040:                 my $src;
 4041:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4042:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4043:                 } else {
 4044:                     if ($attr->{'src'} ne '') {
 4045:                         $src = $attr->{'src'};
 4046:                         &add_filetype($allfiles,$src,'src');
 4047:                     }
 4048:                 }
 4049:                 my $text = $p->get_trimmed_text();
 4050:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4051:                     my @swfargs = split(/,/,$1);
 4052:                     foreach my $item (@swfargs) {
 4053:                         $item =~ s/["']//g;
 4054:                         $item =~ s/^\s+//;
 4055:                         $item =~ s/\s+$//;
 4056:                     }
 4057:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4058:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4059:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4060:                         } else {
 4061:                             $related{$swfargs[0]} = [$swfargs[2]];
 4062:                         }
 4063:                     }
 4064:                 }
 4065:             }
 4066:             if (lc($tagname) eq 'link') {
 4067:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4068:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4069:                 }
 4070:             }
 4071: 	    if (lc($tagname) eq 'object' ||
 4072: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4073: 		foreach my $item (keys(%javafiles)) {
 4074: 		    $javafiles{$item} = '';
 4075: 		}
 4076:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4077:                     $lastids{lc($tagname)} = $attr->{'id'};
 4078:                 }
 4079: 	    }
 4080: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4081: 		my $name = lc($attr->{'name'});
 4082: 		foreach my $item (keys(%javafiles)) {
 4083: 		    if ($name eq $item) {
 4084: 			$javafiles{$item} = $attr->{'value'};
 4085: 			last;
 4086: 		    }
 4087: 		}
 4088:                 my $pathfrom;
 4089: 		foreach my $item (keys(%mediafiles)) {
 4090: 		    if ($name eq $item) {
 4091:                         $pathfrom = $attr->{'value'};
 4092:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4093: 			&add_filetype($allfiles,$pathfrom,$name);
 4094: 			last;
 4095: 		    }
 4096: 		}
 4097:                 if ($name eq 'flashvars') {
 4098:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4099:                 }
 4100:                 if ($pathfrom ne '') {
 4101:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4102:                                          $pathfrom);
 4103:                 }
 4104: 	    }
 4105: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4106: 		foreach my $item (keys(%javafiles)) {
 4107: 		    if ($attr->{$item}) {
 4108: 			$javafiles{$item} = $attr->{$item};
 4109: 			last;
 4110: 		    }
 4111: 		}
 4112: 		foreach my $item (keys(%mediafiles)) {
 4113: 		    if ($attr->{$item}) {
 4114: 			&add_filetype($allfiles,$attr->{$item},$item);
 4115: 			last;
 4116: 		    }
 4117: 		}
 4118:                 if (lc($tagname) eq 'embed') {
 4119:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4120:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4121:                                              $attr->{'src'});
 4122:                     }
 4123:                 }
 4124: 	    }
 4125:             if (lc($tagname) eq 'iframe') {
 4126:                 my $src = $attr->{'src'} ;
 4127:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4128:                     &add_filetype($allfiles,$src,'src');
 4129:                 } elsif ($src =~ m{^/}) {
 4130:                     if ($env{'request.course.id'}) {
 4131:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4132:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4133:                         my $url = &hreflocation('',$fullpath);
 4134:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4135:                             my $relpath = $1;
 4136:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4137:                                 &add_filetype($allfiles,$1,'src');
 4138:                             }
 4139:                         }
 4140:                     }
 4141:                 }
 4142:             }
 4143:             if ($t->[4] =~ m{/>$}) {
 4144:                 pop(@state);
 4145:             }
 4146: 	} elsif ($t->[0] eq 'E') {
 4147: 	    my ($tagname) = ($t->[1]);
 4148: 	    if ($javafiles{'codebase'} ne '') {
 4149: 		$javafiles{'codebase'} .= '/';
 4150: 	    }  
 4151: 	    if (lc($tagname) eq 'applet' ||
 4152: 		lc($tagname) eq 'object' ||
 4153: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4154: 		) {
 4155: 		foreach my $item (keys(%javafiles)) {
 4156: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4157: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4158: 			&add_filetype($allfiles,$file,$item);
 4159: 		    }
 4160: 		}
 4161: 	    } 
 4162: 	    pop @state;
 4163: 	}
 4164:     }
 4165:     foreach my $id (sort(keys(%flashvars))) {
 4166:         if ($shockwave{$id} ne '') {
 4167:             my @pairs = split(/\&/,$flashvars{$id});
 4168:             foreach my $pair (@pairs) {
 4169:                 my ($key,$value) = split(/\=/,$pair);
 4170:                 if ($key eq 'thumb') {
 4171:                     &add_filetype($allfiles,$value,$key);
 4172:                 } elsif ($key eq 'content') {
 4173:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4174:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4175:                     if ($ext ne '') {
 4176:                         &add_filetype($allfiles,$path.$value,$ext);
 4177:                     }
 4178:                 }
 4179:             }
 4180:         }
 4181:     }
 4182:     return 'ok';
 4183: }
 4184: 
 4185: sub add_filetype {
 4186:     my ($allfiles,$file,$type)=@_;
 4187:     if (exists($allfiles->{$file})) {
 4188: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4189: 	    push(@{$allfiles->{$file}}, &escape($type));
 4190: 	}
 4191:     } else {
 4192: 	@{$allfiles->{$file}} = (&escape($type));
 4193:     }
 4194: }
 4195: 
 4196: sub embedded_dependency {
 4197:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4198:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4199:         if (($identifier ne '') &&
 4200:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4201:             ($pathfrom ne '')) {
 4202:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4203:             foreach my $dep (@{$related->{$identifier}}) {
 4204:                 &add_filetype($allfiles,$path.$dep,'object');
 4205:             }
 4206:         }
 4207:     }
 4208:     return;
 4209: }
 4210: 
 4211: sub removeuploadedurl {
 4212:     my ($url)=@_;	
 4213:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4214:     return &removeuserfile($uname,$udom,$fname);
 4215: }
 4216: 
 4217: sub removeuserfile {
 4218:     my ($docuname,$docudom,$fname)=@_;
 4219:     my $home=&homeserver($docuname,$docudom);    
 4220:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4221:     if ($result eq 'ok') {	
 4222:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4223:             my $metafile = $fname.'.meta';
 4224:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4225: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4226:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4227:             my $sqlresult = 
 4228:                 &update_portfolio_table($docuname,$docudom,$file,
 4229:                                         'portfolio_metadata',$group,
 4230:                                         'delete');
 4231:         }
 4232:     }
 4233:     return $result;
 4234: }
 4235: 
 4236: sub mkdiruserfile {
 4237:     my ($docuname,$docudom,$dir)=@_;
 4238:     my $home=&homeserver($docuname,$docudom);
 4239:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4240: }
 4241: 
 4242: sub renameuserfile {
 4243:     my ($docuname,$docudom,$old,$new)=@_;
 4244:     my $home=&homeserver($docuname,$docudom);
 4245:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4246:                         &escape("$old").':'.&escape("$new"),$home);
 4247:     if ($result eq 'ok') {
 4248:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4249:             my $oldmeta = $old.'.meta';
 4250:             my $newmeta = $new.'.meta';
 4251:             my $metaresult = 
 4252:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4253: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4254:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4255:             my $sqlresult = 
 4256:                 &update_portfolio_table($docuname,$docudom,$file,
 4257:                                         'portfolio_metadata',$group,
 4258:                                         'delete');
 4259:         }
 4260:     }
 4261:     return $result;
 4262: }
 4263: 
 4264: # ------------------------------------------------------------------------- Log
 4265: 
 4266: sub log {
 4267:     my ($dom,$nam,$hom,$what)=@_;
 4268:     return critical("log:$dom:$nam:$what",$hom);
 4269: }
 4270: 
 4271: # ------------------------------------------------------------------ Course Log
 4272: #
 4273: # This routine flushes several buffers of non-mission-critical nature
 4274: #
 4275: 
 4276: sub flushcourselogs {
 4277:     &logthis('Flushing log buffers');
 4278: #
 4279: # course logs
 4280: # This is a log of all transactions in a course, which can be used
 4281: # for data mining purposes
 4282: #
 4283: # It also collects the courseid database, which lists last transaction
 4284: # times and course titles for all courseids
 4285: #
 4286:     my %courseidbuffer=();
 4287:     foreach my $crsid (keys(%courselogs)) {
 4288:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4289: 		          &escape($courselogs{$crsid}),
 4290: 		          $coursehombuf{$crsid}) eq 'ok') {
 4291: 	    delete $courselogs{$crsid};
 4292:         } else {
 4293:             &logthis('Failed to flush log buffer for '.$crsid);
 4294:             if (length($courselogs{$crsid})>40000) {
 4295:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4296:                         " exceeded maximum size, deleting.</font>");
 4297:                delete $courselogs{$crsid};
 4298:             }
 4299:         }
 4300:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4301:             'description' => $coursedescrbuf{$crsid},
 4302:             'inst_code'    => $courseinstcodebuf{$crsid},
 4303:             'type'        => $coursetypebuf{$crsid},
 4304:             'owner'       => $courseownerbuf{$crsid},
 4305:         };
 4306:     }
 4307: #
 4308: # Write course id database (reverse lookup) to homeserver of courses 
 4309: # Is used in pickcourse
 4310: #
 4311:     foreach my $crs_home (keys(%courseidbuffer)) {
 4312:         my $response = &courseidput(&host_domain($crs_home),
 4313:                                     $courseidbuffer{$crs_home},
 4314:                                     $crs_home,'timeonly');
 4315:     }
 4316: #
 4317: # File accesses
 4318: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4319: #
 4320:     foreach my $entry (keys(%accesshash)) {
 4321:         if ($entry =~ /___count$/) {
 4322:             my ($dom,$name);
 4323:             ($dom,$name,undef)=
 4324: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4325:             if (! defined($dom) || $dom eq '' || 
 4326:                 ! defined($name) || $name eq '') {
 4327:                 my $cid = $env{'request.course.id'};
 4328:                 $dom  = $env{'request.'.$cid.'.domain'};
 4329:                 $name = $env{'request.'.$cid.'.num'};
 4330:             }
 4331:             my $value = $accesshash{$entry};
 4332:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4333:             my %temphash=($url => $value);
 4334:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4335:             if ($result eq 'ok') {
 4336:                 delete $accesshash{$entry};
 4337:             }
 4338:         } else {
 4339:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4340:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4341:             my %temphash=($entry => $accesshash{$entry});
 4342:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4343:                 delete $accesshash{$entry};
 4344:             }
 4345:         }
 4346:     }
 4347: #
 4348: # Roles
 4349: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4350: #
 4351:     foreach my $entry (keys(%userrolehash)) {
 4352:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4353: 	    split(/\:/,$entry);
 4354:         if (&Apache::lonnet::put('nohist_userroles',
 4355:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4356:                 $rudom,$runame) eq 'ok') {
 4357: 	    delete $userrolehash{$entry};
 4358:         }
 4359:     }
 4360: #
 4361: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4362: #
 4363:     my %domrolebuffer = ();
 4364:     foreach my $entry (keys(%domainrolehash)) {
 4365:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4366:         if ($domrolebuffer{$rudom}) {
 4367:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4368:                       '='.&escape($domainrolehash{$entry});
 4369:         } else {
 4370:             $domrolebuffer{$rudom}.=&escape($entry).
 4371:                       '='.&escape($domainrolehash{$entry});
 4372:         }
 4373:         delete $domainrolehash{$entry};
 4374:     }
 4375:     foreach my $dom (keys(%domrolebuffer)) {
 4376: 	my %servers;
 4377: 	if (defined(&domain($dom,'primary'))) {
 4378: 	    my $primary=&domain($dom,'primary');
 4379: 	    my $hostname=&hostname($primary);
 4380: 	    $servers{$primary} = $hostname;
 4381: 	} else { 
 4382: 	    %servers = &get_servers($dom,'library');
 4383: 	}
 4384: 	foreach my $tryserver (keys(%servers)) {
 4385: 	    if (&reply('domroleput:'.$dom.':'.
 4386: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4387: 		last;
 4388: 	    } else {  
 4389: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4390: 	    }
 4391:         }
 4392:     }
 4393:     $dumpcount++;
 4394: }
 4395: 
 4396: sub courselog {
 4397:     my $what=shift;
 4398:     $what=time.':'.$what;
 4399:     unless ($env{'request.course.id'}) { return ''; }
 4400:     $coursedombuf{$env{'request.course.id'}}=
 4401:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4402:     $coursenumbuf{$env{'request.course.id'}}=
 4403:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4404:     $coursehombuf{$env{'request.course.id'}}=
 4405:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4406:     $coursedescrbuf{$env{'request.course.id'}}=
 4407:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4408:     $courseinstcodebuf{$env{'request.course.id'}}=
 4409:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4410:     $courseownerbuf{$env{'request.course.id'}}=
 4411:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4412:     $coursetypebuf{$env{'request.course.id'}}=
 4413:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4414:     if (defined $courselogs{$env{'request.course.id'}}) {
 4415: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4416:     } else {
 4417: 	$courselogs{$env{'request.course.id'}}.=$what;
 4418:     }
 4419:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4420: 	&flushcourselogs();
 4421:     }
 4422: }
 4423: 
 4424: sub courseacclog {
 4425:     my $fnsymb=shift;
 4426:     unless ($env{'request.course.id'}) { return ''; }
 4427:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4428:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4429:         $what.=':POST';
 4430:         # FIXME: Probably ought to escape things....
 4431: 	foreach my $key (keys(%env)) {
 4432:             if ($key=~/^form\.(.*)/) {
 4433:                 my $formitem = $1;
 4434:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4435:                     $what.=':'.$formitem.'='.$env{$key};
 4436:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4437:                     $what.=':'.$formitem.'='.$env{$key};
 4438:                 }
 4439:             }
 4440:         }
 4441:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4442:         # FIXME: We should not be depending on a form parameter that someone
 4443:         # editing lonsearchcat.pm might change in the future.
 4444:         if ($env{'form.phase'} eq 'course_search') {
 4445:             $what.= ':POST';
 4446:             # FIXME: Probably ought to escape things....
 4447:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4448:                                  'crsdiscuss') {
 4449:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4450:             }
 4451:         }
 4452:     }
 4453:     &courselog($what);
 4454: }
 4455: 
 4456: sub countacc {
 4457:     my $url=&declutter(shift);
 4458:     return if (! defined($url) || $url eq '');
 4459:     unless ($env{'request.course.id'}) { return ''; }
 4460: #
 4461: # Mark that this url was used in this course
 4462: #
 4463:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4464: #
 4465: # Increase the access count for this resource in this child process
 4466: #
 4467:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4468:     $accesshash{$key}++;
 4469: }
 4470: 
 4471: sub linklog {
 4472:     my ($from,$to)=@_;
 4473:     $from=&declutter($from);
 4474:     $to=&declutter($to);
 4475:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4476:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4477: }
 4478: 
 4479: sub statslog {
 4480:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4481:     if ($users<2) { return; }
 4482:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4483:             'course'       => $env{'request.course.id'},
 4484:             'sections'     => '"all"',
 4485:             'num_students' => $users,
 4486:             'part'         => $part,
 4487:             'symb'         => $symb,
 4488:             'mean_tries'   => $av_attempts,
 4489:             'deg_of_diff'  => $degdiff});
 4490:     foreach my $key (keys(%dynstore)) {
 4491:         $accesshash{$key}=$dynstore{$key};
 4492:     }
 4493: }
 4494:   
 4495: sub userrolelog {
 4496:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4497:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4498:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4499:        $userrolehash
 4500:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4501:                     =$tend.':'.$tstart;
 4502:     }
 4503:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4504:        $userrolehash
 4505:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4506:                     =$tend.':'.$tstart;
 4507:     }
 4508:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4509:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4510:        $domainrolehash
 4511:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4512:                     = $tend.':'.$tstart;
 4513:     }
 4514: }
 4515: 
 4516: sub courserolelog {
 4517:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4518:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4519:         my $cdom = $1;
 4520:         my $cnum = $2;
 4521:         my $sec = $3;
 4522:         my $namespace = 'rolelog';
 4523:         my %storehash = (
 4524:                            role    => $trole,
 4525:                            start   => $tstart,
 4526:                            end     => $tend,
 4527:                            selfenroll => $selfenroll,
 4528:                            context    => $context,
 4529:                         );
 4530:         if ($trole eq 'gr') {
 4531:             $namespace = 'groupslog';
 4532:             $storehash{'group'} = $sec;
 4533:         } else {
 4534:             $storehash{'section'} = $sec;
 4535:         }
 4536:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4537:                    $domain,$cnum,$cdom);
 4538:         if (($trole ne 'st') || ($sec ne '')) {
 4539:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4540:         }
 4541:     }
 4542:     return;
 4543: }
 4544: 
 4545: sub domainrolelog {
 4546:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4547:     if ($area =~ m{^/($match_domain)/$}) {
 4548:         my $cdom = $1;
 4549:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4550:         my $namespace = 'rolelog';
 4551:         my %storehash = (
 4552:                            role    => $trole,
 4553:                            start   => $tstart,
 4554:                            end     => $tend,
 4555:                            context => $context,
 4556:                         );
 4557:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4558:                    $domain,$domconfiguser,$cdom);
 4559:     }
 4560:     return;
 4561: 
 4562: }
 4563: 
 4564: sub coauthorrolelog {
 4565:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4566:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4567:         my $audom = $1;
 4568:         my $auname = $2;
 4569:         my $namespace = 'rolelog';
 4570:         my %storehash = (
 4571:                            role    => $trole,
 4572:                            start   => $tstart,
 4573:                            end     => $tend,
 4574:                            context => $context,
 4575:                         );
 4576:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4577:                    $domain,$auname,$audom);
 4578:     }
 4579:     return;
 4580: }
 4581: 
 4582: sub get_course_adv_roles {
 4583:     my ($cid,$codes) = @_;
 4584:     $cid=$env{'request.course.id'} unless (defined($cid));
 4585:     my %coursehash=&coursedescription($cid);
 4586:     my $crstype = &Apache::loncommon::course_type($cid);
 4587:     my %nothide=();
 4588:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4589:         if ($user !~ /:/) {
 4590: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4591:         } else {
 4592:             $nothide{$user}=1;
 4593:         }
 4594:     }
 4595:     my @possdoms = ($coursehash{'domain'});
 4596:     if ($coursehash{'checkforpriv'}) {
 4597:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4598:     }
 4599:     my %returnhash=();
 4600:     my %dumphash=
 4601:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4602:     my $now=time;
 4603:     my %privileged;
 4604:     foreach my $entry (keys(%dumphash)) {
 4605: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4606:         if (($tstart) && ($tstart<0)) { next; }
 4607:         if (($tend) && ($tend<$now)) { next; }
 4608:         if (($tstart) && ($now<$tstart)) { next; }
 4609:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4610: 	if ($username eq '' || $domain eq '') { next; }
 4611:         if ((&privileged($username,$domain,\@possdoms)) &&
 4612:             (!$nothide{$username.':'.$domain})) { next; }
 4613: 	if ($role eq 'cr') { next; }
 4614:         if ($codes) {
 4615:             if ($section) { $role .= ':'.$section; }
 4616:             if ($returnhash{$role}) {
 4617:                 $returnhash{$role}.=','.$username.':'.$domain;
 4618:             } else {
 4619:                 $returnhash{$role}=$username.':'.$domain;
 4620:             }
 4621:         } else {
 4622:             my $key=&plaintext($role,$crstype);
 4623:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4624:             if ($returnhash{$key}) {
 4625: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4626:             } else {
 4627:                 $returnhash{$key}=$username.':'.$domain;
 4628:             }
 4629:         }
 4630:     }
 4631:     return %returnhash;
 4632: }
 4633: 
 4634: sub get_my_roles {
 4635:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4636:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4637:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4638:     my (%dumphash,%nothide);
 4639:     if ($context eq 'userroles') {
 4640:         %dumphash = &dump('roles',$udom,$uname);
 4641:     } else {
 4642:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4643:         if ($hidepriv) {
 4644:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4645:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4646:                 if ($user !~ /:/) {
 4647:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4648:                 } else {
 4649:                     $nothide{$user} = 1;
 4650:                 }
 4651:             }
 4652:         }
 4653:     }
 4654:     my %returnhash=();
 4655:     my $now=time;
 4656:     my %privileged;
 4657:     foreach my $entry (keys(%dumphash)) {
 4658:         my ($role,$tend,$tstart);
 4659:         if ($context eq 'userroles') {
 4660:             next if ($entry =~ /^rolesdef/);
 4661: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4662:         } else {
 4663:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4664:         }
 4665:         if (($tstart) && ($tstart<0)) { next; }
 4666:         my $status = 'active';
 4667:         if (($tend) && ($tend<=$now)) {
 4668:             $status = 'previous';
 4669:         } 
 4670:         if (($tstart) && ($now<$tstart)) {
 4671:             $status = 'future';
 4672:         }
 4673:         if (ref($types) eq 'ARRAY') {
 4674:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4675:                 next;
 4676:             } 
 4677:         } else {
 4678:             if ($status ne 'active') {
 4679:                 next;
 4680:             }
 4681:         }
 4682:         my ($rolecode,$username,$domain,$section,$area);
 4683:         if ($context eq 'userroles') {
 4684:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4685:             (undef,$domain,$username,$section) = split(/\//,$area);
 4686:         } else {
 4687:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4688:         }
 4689:         if (ref($roledoms) eq 'ARRAY') {
 4690:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4691:                 next;
 4692:             }
 4693:         }
 4694:         if (ref($roles) eq 'ARRAY') {
 4695:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4696:                 if ($role =~ /^cr\//) {
 4697:                     if (!grep(/^cr$/,@{$roles})) {
 4698:                         next;
 4699:                     }
 4700:                 } elsif ($role =~ /^gr\//) {
 4701:                     if (!grep(/^gr$/,@{$roles})) {
 4702:                         next;
 4703:                     }
 4704:                 } else {
 4705:                     next;
 4706:                 }
 4707:             }
 4708:         }
 4709:         if ($hidepriv) {
 4710:             my @privroles = ('dc','su');
 4711:             if ($context eq 'userroles') {
 4712:                 next if (grep(/^\Q$role\E$/,@privroles));
 4713:             } else {
 4714:                 my $possdoms = [$domain];
 4715:                 if (ref($roledoms) eq 'ARRAY') {
 4716:                    push(@{$possdoms},@{$roledoms}); 
 4717:                 }
 4718:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4719:                     if (!$nothide{$username.':'.$domain}) {
 4720:                         next;
 4721:                     }
 4722:                 }
 4723:             }
 4724:         }
 4725:         if ($withsec) {
 4726:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4727:                 $tstart.':'.$tend;
 4728:         } else {
 4729:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4730:         }
 4731:     }
 4732:     return %returnhash;
 4733: }
 4734: 
 4735: sub get_all_adhocroles {
 4736:     my ($dom) = @_;
 4737:     my @roles_by_num = ();
 4738:     my %domdefaults = &get_domain_defaults($dom);
 4739:     my (%description,%access_in_dom,%access_info);
 4740:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4741:         my $count = 0;
 4742:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4743:         my %ordered;
 4744:         foreach my $role (sort(keys(%domcurrent))) {
 4745:             my ($order,$desc,$access_in_dom);
 4746:             if (ref($domcurrent{$role}) eq 'HASH') {
 4747:                 $order = $domcurrent{$role}{'order'};
 4748:                 $desc = $domcurrent{$role}{'desc'};
 4749:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4750:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4751:             }
 4752:             if ($order eq '') {
 4753:                 $order = $count;
 4754:             }
 4755:             $ordered{$order} = $role;
 4756:             if ($desc ne '') {
 4757:                 $description{$role} = $desc;
 4758:             } else {
 4759:                 $description{$role}= $role;
 4760:             }
 4761:             $count++;
 4762:         }
 4763:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4764:             push(@roles_by_num,$ordered{$item});
 4765:         }
 4766:     }
 4767:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4768: }
 4769: 
 4770: sub get_my_adhocroles {
 4771:     my ($cid,$checkreg) = @_;
 4772:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4773:     if ($env{'request.course.id'} eq $cid) {
 4774:         $cdom = $env{'course.'.$cid.'.domain'};
 4775:         $cnum = $env{'course.'.$cid.'.num'};
 4776:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4777:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4778:         $cdom = $1;
 4779:         $cnum = $2;
 4780:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4781:                                      $cdom,$cnum);
 4782:     }
 4783:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4784:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4785:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4786:         if ($rosterhash{$user} ne '') {
 4787:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4788:             return ([],{}) if ($type eq 'auto');
 4789:         }
 4790:     }
 4791:     if (($cdom ne '') && ($cnum ne ''))  {
 4792:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4793:             my $then=$env{'user.login.time'};
 4794:             my $update=$env{'user.update.time'};
 4795:             if (!$update) {
 4796:                 $update = $then;
 4797:             }
 4798:             my @liveroles;
 4799:             foreach my $role ('dh','da') {
 4800:                 if ($env{"user.role.$role./$cdom/"}) {
 4801:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4802:                     my $limit = $update;
 4803:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4804:                         $limit = $then;
 4805:                     }
 4806:                     my $activerole = 1;
 4807:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4808:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4809:                     if ($activerole) {
 4810:                         push(@liveroles,$role);
 4811:                     }
 4812:                 }
 4813:             }
 4814:             if (@liveroles) {
 4815:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4816:                     my ($accessref,$accessinfo,%access_in_dom);
 4817:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4818:                     if (ref($roles_by_num) eq 'ARRAY') {
 4819:                         if (@{$roles_by_num}) {
 4820:                             my %settings;
 4821:                             if ($env{'request.course.id'} eq $cid) {
 4822:                                 foreach my $envkey (keys(%env)) {
 4823:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4824:                                         $settings{$1} = $env{$envkey};
 4825:                                     }
 4826:                                 }
 4827:                             } else {
 4828:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4829:                             }
 4830:                             my %setincrs;
 4831:                             if ($settings{'internal.adhocaccess'}) {
 4832:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4833:                             }
 4834:                             my @statuses;
 4835:                             if ($env{'environment.inststatus'}) {
 4836:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4837:                             }
 4838:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4839:                             if (ref($accessref) eq 'HASH') {
 4840:                                 %access_in_dom = %{$accessref};
 4841:                             }
 4842:                             foreach my $role (@{$roles_by_num}) {
 4843:                                 my ($curraccess,@okstatus,@personnel);
 4844:                                 if ($setincrs{$role}) {
 4845:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4846:                                     if ($curraccess eq 'status') {
 4847:                                         @okstatus = split(/\&/,$rest);
 4848:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4849:                                         @personnel = split(/\&/,$rest);
 4850:                                     }
 4851:                                 } else {
 4852:                                     $curraccess = $access_in_dom{$role};
 4853:                                     if (ref($accessinfo) eq 'HASH') {
 4854:                                         if ($curraccess eq 'status') {
 4855:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4856:                                                 @okstatus = @{$accessinfo->{$role}};
 4857:                                             }
 4858:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4859:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4860:                                                 @personnel = @{$accessinfo->{$role}};
 4861:                                             }
 4862:                                         }
 4863:                                     }
 4864:                                 }
 4865:                                 if ($curraccess eq 'none') {
 4866:                                     next;
 4867:                                 } elsif ($curraccess eq 'all') {
 4868:                                     push(@possroles,$role);
 4869:                                 } elsif ($curraccess eq 'dh') {
 4870:                                     if (grep(/^dh$/,@liveroles)) {
 4871:                                         push(@possroles,$role);
 4872:                                     } else {
 4873:                                         next;
 4874:                                     }
 4875:                                 } elsif ($curraccess eq 'da') {
 4876:                                     if (grep(/^da$/,@liveroles)) {
 4877:                                         push(@possroles,$role);
 4878:                                     } else {
 4879:                                         next;
 4880:                                     }
 4881:                                 } elsif ($curraccess eq 'status') {
 4882:                                     if (@okstatus) {
 4883:                                         if (!@statuses) {
 4884:                                             if (grep(/^default$/,@okstatus)) {
 4885:                                                 push(@possroles,$role);
 4886:                                             }
 4887:                                         } else {
 4888:                                             foreach my $status (@okstatus) {
 4889:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 4890:                                                     push(@possroles,$role);
 4891:                                                     last;
 4892:                                                 }
 4893:                                             }
 4894:                                         }
 4895:                                     }
 4896:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4897:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 4898:                                         if ($curraccess eq 'exc') {
 4899:                                             push(@possroles,$role);
 4900:                                         }
 4901:                                     } elsif ($curraccess eq 'inc') {
 4902:                                         push(@possroles,$role);
 4903:                                     }
 4904:                                 }
 4905:                             }
 4906:                         }
 4907:                     }
 4908:                 }
 4909:             }
 4910:         }
 4911:     }
 4912:     unless (ref($description) eq 'HASH') {
 4913:         if (ref($roles_by_num) eq 'ARRAY') {
 4914:             my %desc;
 4915:             map { $desc{$_} = $_; } (@{$roles_by_num});
 4916:             $description = \%desc;
 4917:         } else {
 4918:             $description = {};
 4919:         }
 4920:     }
 4921:     return (\@possroles,$description);
 4922: }
 4923: 
 4924: # ----------------------------------------------------- Frontpage Announcements
 4925: #
 4926: #
 4927: 
 4928: sub postannounce {
 4929:     my ($server,$text)=@_;
 4930:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4931:     unless ($text=~/\w/) { $text=''; }
 4932:     return &reply('setannounce:'.&escape($text),$server);
 4933: }
 4934: 
 4935: sub getannounce {
 4936: 
 4937:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4938: 	my $announcement='';
 4939: 	while (my $line = <$fh>) { $announcement .= $line; }
 4940: 	close($fh);
 4941: 	if ($announcement=~/\w/) { 
 4942: 	    return 
 4943:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4944:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4945: 	} else {
 4946: 	    return '';
 4947: 	}
 4948:     } else {
 4949: 	return '';
 4950:     }
 4951: }
 4952: 
 4953: # ---------------------------------------------------------- Course ID routines
 4954: # Deal with domain's nohist_courseid.db files
 4955: #
 4956: 
 4957: sub courseidput {
 4958:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4959:     return unless (ref($storehash) eq 'HASH');
 4960:     my $outcome;
 4961:     if ($caller eq 'timeonly') {
 4962:         my $cids = '';
 4963:         foreach my $item (keys(%$storehash)) {
 4964:             $cids.=&escape($item).'&';
 4965:         }
 4966:         $cids=~s/\&$//;
 4967:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4968:                           $coursehome);       
 4969:     } else {
 4970:         my $items = '';
 4971:         foreach my $item (keys(%$storehash)) {
 4972:             $items.= &escape($item).'='.
 4973:                      &freeze_escape($$storehash{$item}).'&';
 4974:         }
 4975:         $items=~s/\&$//;
 4976:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4977:                           $coursehome);
 4978:     }
 4979:     if ($outcome eq 'unknown_cmd') {
 4980:         my $what;
 4981:         foreach my $cid (keys(%$storehash)) {
 4982:             $what .= &escape($cid).'=';
 4983:             foreach my $item ('description','inst_code','owner','type') {
 4984:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4985:             }
 4986:             $what =~ s/\:$/&/;
 4987:         }
 4988:         $what =~ s/\&$//;  
 4989:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4990:     } else {
 4991:         return $outcome;
 4992:     }
 4993: }
 4994: 
 4995: sub courseiddump {
 4996:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4997:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4998:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4999:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5000:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5001:     my $as_hash = 1;
 5002:     my %returnhash;
 5003:     if (!$domfilter) { $domfilter=''; }
 5004:     my %libserv = &all_library();
 5005:     foreach my $tryserver (keys(%libserv)) {
 5006:         if ( (  $hostidflag == 1 
 5007: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5008: 	     || (!defined($hostidflag)) ) {
 5009: 
 5010: 	    if (($domfilter eq '') ||
 5011: 		(&host_domain($tryserver) eq $domfilter)) {
 5012:                 my $rep;
 5013:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5014:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5015:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5016:                                 &escape($descfilter), &escape($instcodefilter), 
 5017:                                 &escape($ownerfilter), &escape($coursefilter),
 5018:                                 &escape($typefilter), &escape($regexp_ok), 
 5019:                                 $as_hash, &escape($selfenrollonly), 
 5020:                                 &escape($catfilter), $showhidden, $caller, 
 5021:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5022:                                 &escape($createdbefore), &escape($createdafter), 
 5023:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5024:                                 $reqcrsdom,&escape($reqinstcode))));
 5025:                 } else {
 5026:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5027:                              $sincefilter.':'.&escape($descfilter).':'.
 5028:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5029:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5030:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5031:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5032:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5033:                              &escape($cc_clone).':'.$cloneonly.':'.
 5034:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5035:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5036:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5037:                 }
 5038:                      
 5039:                 my @pairs=split(/\&/,$rep);
 5040:                 foreach my $item (@pairs) {
 5041:                     my ($key,$value)=split(/\=/,$item,2);
 5042:                     $key = &unescape($key);
 5043:                     next if ($key =~ /^error: 2 /);
 5044:                     my $result = &thaw_unescape($value);
 5045:                     if (ref($result) eq 'HASH') {
 5046:                         $returnhash{$key}=$result;
 5047:                     } else {
 5048:                         my @responses = split(/:/,$value);
 5049:                         my @items = ('description','inst_code','owner','type');
 5050:                         for (my $i=0; $i<@responses; $i++) {
 5051:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5052:                         }
 5053:                     }
 5054:                 }
 5055:             }
 5056:         }
 5057:     }
 5058:     return %returnhash;
 5059: }
 5060: 
 5061: sub courselastaccess {
 5062:     my ($cdom,$cnum,$hostidref) = @_;
 5063:     my %returnhash;
 5064:     if ($cdom && $cnum) {
 5065:         my $chome = &homeserver($cnum,$cdom);
 5066:         if ($chome ne 'no_host') {
 5067:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5068:             &extract_lastaccess(\%returnhash,$rep);
 5069:         }
 5070:     } else {
 5071:         if (!$cdom) { $cdom=''; }
 5072:         my %libserv = &all_library();
 5073:         foreach my $tryserver (keys(%libserv)) {
 5074:             if (ref($hostidref) eq 'ARRAY') {
 5075:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5076:             } 
 5077:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5078:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5079:                 &extract_lastaccess(\%returnhash,$rep);
 5080:             }
 5081:         }
 5082:     }
 5083:     return %returnhash;
 5084: }
 5085: 
 5086: sub extract_lastaccess {
 5087:     my ($returnhash,$rep) = @_;
 5088:     if (ref($returnhash) eq 'HASH') {
 5089:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5090:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5091:                  $rep eq '') {
 5092:             my @pairs=split(/\&/,$rep);
 5093:             foreach my $item (@pairs) {
 5094:                 my ($key,$value)=split(/\=/,$item,2);
 5095:                 $key = &unescape($key);
 5096:                 next if ($key =~ /^error: 2 /);
 5097:                 $returnhash->{$key} = &thaw_unescape($value);
 5098:             }
 5099:         }
 5100:     }
 5101:     return;
 5102: }
 5103: 
 5104: # ---------------------------------------------------------- DC e-mail
 5105: 
 5106: sub dcmailput {
 5107:     my ($domain,$msgid,$message,$server)=@_;
 5108:     my $status = &Apache::lonnet::critical(
 5109:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5110:        &escape($message),$server);
 5111:     return $status;
 5112: }
 5113: 
 5114: sub dcmaildump {
 5115:     my ($dom,$startdate,$enddate,$senders) = @_;
 5116:     my %returnhash=();
 5117: 
 5118:     if (defined(&domain($dom,'primary'))) {
 5119:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5120:                                                          &escape($enddate).':';
 5121: 	my @esc_senders=map { &escape($_)} @$senders;
 5122: 	$cmd.=&escape(join('&',@esc_senders));
 5123: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5124:             my ($key,$value) = split(/\=/,$line,2);
 5125:             if (($key) && ($value)) {
 5126:                 $returnhash{&unescape($key)} = &unescape($value);
 5127:             }
 5128:         }
 5129:     }
 5130:     return %returnhash;
 5131: }
 5132: # ---------------------------------------------------------- Domain roles
 5133: 
 5134: sub get_domain_roles {
 5135:     my ($dom,$roles,$startdate,$enddate)=@_;
 5136:     if ((!defined($startdate)) || ($startdate eq '')) {
 5137:         $startdate = '.';
 5138:     }
 5139:     if ((!defined($enddate)) || ($enddate eq '')) {
 5140:         $enddate = '.';
 5141:     }
 5142:     my $rolelist;
 5143:     if (ref($roles) eq 'ARRAY') {
 5144:         $rolelist = join('&',@{$roles});
 5145:     }
 5146:     my %personnel = ();
 5147: 
 5148:     my %servers = &get_servers($dom,'library');
 5149:     foreach my $tryserver (keys(%servers)) {
 5150: 	%{$personnel{$tryserver}}=();
 5151: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5152: 					    &escape($startdate).':'.
 5153: 					    &escape($enddate).':'.
 5154: 					    &escape($rolelist), $tryserver))) {
 5155: 	    my ($key,$value) = split(/\=/,$line,2);
 5156: 	    if (($key) && ($value)) {
 5157: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5158: 	    }
 5159: 	}
 5160:     }
 5161:     return %personnel;
 5162: }
 5163: 
 5164: sub get_active_domroles {
 5165:     my ($dom,$roles) = @_;
 5166:     return () unless (ref($roles) eq 'ARRAY');
 5167:     my $now = time;
 5168:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5169:     my %domroles;
 5170:     foreach my $server (keys(%dompersonnel)) {
 5171:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5172:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5173:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5174:         }
 5175:     }
 5176:     return %domroles;
 5177: }
 5178: 
 5179: # ----------------------------------------------------------- Interval timing 
 5180: 
 5181: {
 5182: # Caches needed for speedup of navmaps
 5183: # We don't want to cache this for very long at all (5 seconds at most)
 5184: # 
 5185: # The user for whom we cache
 5186: my $cachedkey='';
 5187: # The cached times for this user
 5188: my %cachedtimes=();
 5189: # When this was last done
 5190: my $cachedtime='';
 5191: 
 5192: sub load_all_first_access {
 5193:     my ($uname,$udom,$ignorecache)=@_;
 5194:     if (($cachedkey eq $uname.':'.$udom) &&
 5195:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5196:         (!$ignorecache)) {
 5197:         return;
 5198:     }
 5199:     $cachedtime=time;
 5200:     $cachedkey=$uname.':'.$udom;
 5201:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5202: }
 5203: 
 5204: sub get_first_access {
 5205:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5206:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5207:     if ($argsymb) { $symb=$argsymb; }
 5208:     my ($map,$id,$res)=&decode_symb($symb);
 5209:     if ($argmap) { $map = $argmap; }
 5210:     if ($type eq 'course') {
 5211: 	$res='course';
 5212:     } elsif ($type eq 'map') {
 5213: 	$res=&symbread($map);
 5214:     } else {
 5215: 	$res=$symb;
 5216:     }
 5217:     &load_all_first_access($uname,$udom,$ignorecache);
 5218:     return $cachedtimes{"$courseid\0$res"};
 5219: }
 5220: 
 5221: sub set_first_access {
 5222:     my ($type,$interval)=@_;
 5223:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5224:     my ($map,$id,$res)=&decode_symb($symb);
 5225:     if ($type eq 'course') {
 5226: 	$res='course';
 5227:     } elsif ($type eq 'map') {
 5228: 	$res=&symbread($map);
 5229:     } else {
 5230: 	$res=$symb;
 5231:     }
 5232:     $cachedkey='';
 5233:     my $firstaccess=&get_first_access($type,$symb,$map);
 5234:     if (!$firstaccess) {
 5235:         my $start = time;
 5236: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5237:                           $udom,$uname);
 5238:         if ($putres eq 'ok') {
 5239:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5240:                  $udom,$uname); 
 5241:             &appenv(
 5242:                      {
 5243:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5244:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5245:                      }
 5246:                   );
 5247:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5248:                 $cachedtimes{"$courseid\0$res"} = $start;
 5249:             }
 5250:         }
 5251:         return $putres;
 5252:     }
 5253:     return 'already_set';
 5254: }
 5255: }
 5256: 
 5257: # --------------------------------------------- Set Expire Date for Spreadsheet
 5258: 
 5259: sub expirespread {
 5260:     my ($uname,$udom,$stype,$usymb)=@_;
 5261:     my $cid=$env{'request.course.id'}; 
 5262:     if ($cid) {
 5263:        my $now=time;
 5264:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5265:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5266:                             $env{'course.'.$cid.'.num'}.
 5267: 	        	    ':nohist_expirationdates:'.
 5268:                             &escape($key).'='.$now,
 5269:                             $env{'course.'.$cid.'.home'})
 5270:     }
 5271:     return 'ok';
 5272: }
 5273: 
 5274: # ----------------------------------------------------- Devalidate Spreadsheets
 5275: 
 5276: sub devalidate {
 5277:     my ($symb,$uname,$udom)=@_;
 5278:     my $cid=$env{'request.course.id'}; 
 5279:     if ($cid) {
 5280:         # delete the stored spreadsheets for
 5281:         # - the student level sheet of this user in course's homespace
 5282:         # - the assessment level sheet for this resource 
 5283:         #   for this user in user's homespace
 5284: 	# - current conditional state info
 5285: 	my $key=$uname.':'.$udom.':';
 5286:         my $status=
 5287: 	    &del('nohist_calculatedsheets',
 5288: 		 [$key.'studentcalc:'],
 5289: 		 $env{'course.'.$cid.'.domain'},
 5290: 		 $env{'course.'.$cid.'.num'})
 5291: 		.' '.
 5292: 	    &del('nohist_calculatedsheets_'.$cid,
 5293: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5294:         unless ($status eq 'ok ok') {
 5295:            &logthis('Could not devalidate spreadsheet '.
 5296:                     $uname.' at '.$udom.' for '.
 5297: 		    $symb.': '.$status);
 5298:         }
 5299: 	&delenv('user.state.'.$cid);
 5300:     }
 5301: }
 5302: 
 5303: sub get_scalar {
 5304:     my ($string,$end) = @_;
 5305:     my $value;
 5306:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5307: 	$value = $1;
 5308:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5309: 	$value = $1;
 5310:     }
 5311:     return &unescape($value);
 5312: }
 5313: 
 5314: sub array2str {
 5315:   my (@array) = @_;
 5316:   my $result=&arrayref2str(\@array);
 5317:   $result=~s/^__ARRAY_REF__//;
 5318:   $result=~s/__END_ARRAY_REF__$//;
 5319:   return $result;
 5320: }
 5321: 
 5322: sub arrayref2str {
 5323:   my ($arrayref) = @_;
 5324:   my $result='__ARRAY_REF__';
 5325:   foreach my $elem (@$arrayref) {
 5326:     if(ref($elem) eq 'ARRAY') {
 5327:       $result.=&arrayref2str($elem).'&';
 5328:     } elsif(ref($elem) eq 'HASH') {
 5329:       $result.=&hashref2str($elem).'&';
 5330:     } elsif(ref($elem)) {
 5331:       #print("Got a ref of ".(ref($elem))." skipping.");
 5332:     } else {
 5333:       $result.=&escape($elem).'&';
 5334:     }
 5335:   }
 5336:   $result=~s/\&$//;
 5337:   $result .= '__END_ARRAY_REF__';
 5338:   return $result;
 5339: }
 5340: 
 5341: sub hash2str {
 5342:   my (%hash) = @_;
 5343:   my $result=&hashref2str(\%hash);
 5344:   $result=~s/^__HASH_REF__//;
 5345:   $result=~s/__END_HASH_REF__$//;
 5346:   return $result;
 5347: }
 5348: 
 5349: sub hashref2str {
 5350:   my ($hashref)=@_;
 5351:   my $result='__HASH_REF__';
 5352:   foreach my $key (sort(keys(%$hashref))) {
 5353:     if (ref($key) eq 'ARRAY') {
 5354:       $result.=&arrayref2str($key).'=';
 5355:     } elsif (ref($key) eq 'HASH') {
 5356:       $result.=&hashref2str($key).'=';
 5357:     } elsif (ref($key)) {
 5358:       $result.='=';
 5359:       #print("Got a ref of ".(ref($key))." skipping.");
 5360:     } else {
 5361: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5362:     }
 5363: 
 5364:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5365:       $result.=&arrayref2str($hashref->{$key}).'&';
 5366:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5367:       $result.=&hashref2str($hashref->{$key}).'&';
 5368:     } elsif(ref($hashref->{$key})) {
 5369:        $result.='&';
 5370:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5371:     } else {
 5372:       $result.=&escape($hashref->{$key}).'&';
 5373:     }
 5374:   }
 5375:   $result=~s/\&$//;
 5376:   $result .= '__END_HASH_REF__';
 5377:   return $result;
 5378: }
 5379: 
 5380: sub str2hash {
 5381:     my ($string)=@_;
 5382:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5383:     return %$hash;
 5384: }
 5385: 
 5386: sub str2hashref {
 5387:   my ($string) = @_;
 5388: 
 5389:   my %hash;
 5390: 
 5391:   if($string !~ /^__HASH_REF__/) {
 5392:       if (! ($string eq '' || !defined($string))) {
 5393: 	  $hash{'error'}='Not hash reference';
 5394:       }
 5395:       return (\%hash, $string);
 5396:   }
 5397: 
 5398:   $string =~ s/^__HASH_REF__//;
 5399: 
 5400:   while($string !~ /^__END_HASH_REF__/) {
 5401:       #key
 5402:       my $key='';
 5403:       if($string =~ /^__HASH_REF__/) {
 5404:           ($key, $string)=&str2hashref($string);
 5405:           if(defined($key->{'error'})) {
 5406:               $hash{'error'}='Bad data';
 5407:               return (\%hash, $string);
 5408:           }
 5409:       } elsif($string =~ /^__ARRAY_REF__/) {
 5410:           ($key, $string)=&str2arrayref($string);
 5411:           if($key->[0] eq 'Array reference error') {
 5412:               $hash{'error'}='Bad data';
 5413:               return (\%hash, $string);
 5414:           }
 5415:       } else {
 5416:           $string =~ s/^(.*?)=//;
 5417: 	  $key=&unescape($1);
 5418:       }
 5419:       $string =~ s/^=//;
 5420: 
 5421:       #value
 5422:       my $value='';
 5423:       if($string =~ /^__HASH_REF__/) {
 5424:           ($value, $string)=&str2hashref($string);
 5425:           if(defined($value->{'error'})) {
 5426:               $hash{'error'}='Bad data';
 5427:               return (\%hash, $string);
 5428:           }
 5429:       } elsif($string =~ /^__ARRAY_REF__/) {
 5430:           ($value, $string)=&str2arrayref($string);
 5431:           if($value->[0] eq 'Array reference error') {
 5432:               $hash{'error'}='Bad data';
 5433:               return (\%hash, $string);
 5434:           }
 5435:       } else {
 5436: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5437:       }
 5438:       $string =~ s/^&//;
 5439: 
 5440:       $hash{$key}=$value;
 5441:   }
 5442: 
 5443:   $string =~ s/^__END_HASH_REF__//;
 5444: 
 5445:   return (\%hash, $string);
 5446: }
 5447: 
 5448: sub str2array {
 5449:     my ($string)=@_;
 5450:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5451:     return @$array;
 5452: }
 5453: 
 5454: sub str2arrayref {
 5455:   my ($string) = @_;
 5456:   my @array;
 5457: 
 5458:   if($string !~ /^__ARRAY_REF__/) {
 5459:       if (! ($string eq '' || !defined($string))) {
 5460: 	  $array[0]='Array reference error';
 5461:       }
 5462:       return (\@array, $string);
 5463:   }
 5464: 
 5465:   $string =~ s/^__ARRAY_REF__//;
 5466: 
 5467:   while($string !~ /^__END_ARRAY_REF__/) {
 5468:       my $value='';
 5469:       if($string =~ /^__HASH_REF__/) {
 5470:           ($value, $string)=&str2hashref($string);
 5471:           if(defined($value->{'error'})) {
 5472:               $array[0] ='Array reference error';
 5473:               return (\@array, $string);
 5474:           }
 5475:       } elsif($string =~ /^__ARRAY_REF__/) {
 5476:           ($value, $string)=&str2arrayref($string);
 5477:           if($value->[0] eq 'Array reference error') {
 5478:               $array[0] ='Array reference error';
 5479:               return (\@array, $string);
 5480:           }
 5481:       } else {
 5482: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5483:       }
 5484:       $string =~ s/^&//;
 5485: 
 5486:       push(@array, $value);
 5487:   }
 5488: 
 5489:   $string =~ s/^__END_ARRAY_REF__//;
 5490: 
 5491:   return (\@array, $string);
 5492: }
 5493: 
 5494: # -------------------------------------------------------------------Temp Store
 5495: 
 5496: sub tmpreset {
 5497:   my ($symb,$namespace,$domain,$stuname) = @_;
 5498:   if (!$symb) {
 5499:     $symb=&symbread();
 5500:     if (!$symb) { $symb= $env{'request.url'}; }
 5501:   }
 5502:   $symb=escape($symb);
 5503: 
 5504:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5505:   $namespace=~s/\//\_/g;
 5506:   $namespace=~s/\W//g;
 5507: 
 5508:   if (!$domain) { $domain=$env{'user.domain'}; }
 5509:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5510:   if ($domain eq 'public' && $stuname eq 'public') {
 5511:       $stuname=$ENV{'REMOTE_ADDR'};
 5512:   }
 5513:   my $path=LONCAPA::tempdir();
 5514:   my %hash;
 5515:   if (tie(%hash,'GDBM_File',
 5516: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5517: 	  &GDBM_WRCREAT(),0640)) {
 5518:     foreach my $key (keys(%hash)) {
 5519:       if ($key=~ /:$symb/) {
 5520: 	delete($hash{$key});
 5521:       }
 5522:     }
 5523:   }
 5524: }
 5525: 
 5526: sub tmpstore {
 5527:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5528: 
 5529:   if (!$symb) {
 5530:     $symb=&symbread();
 5531:     if (!$symb) { $symb= $env{'request.url'}; }
 5532:   }
 5533:   $symb=escape($symb);
 5534: 
 5535:   if (!$namespace) {
 5536:     # I don't think we would ever want to store this for a course.
 5537:     # it seems this will only be used if we don't have a course.
 5538:     #$namespace=$env{'request.course.id'};
 5539:     #if (!$namespace) {
 5540:       $namespace=$env{'request.state'};
 5541:     #}
 5542:   }
 5543:   $namespace=~s/\//\_/g;
 5544:   $namespace=~s/\W//g;
 5545:   if (!$domain) { $domain=$env{'user.domain'}; }
 5546:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5547:   if ($domain eq 'public' && $stuname eq 'public') {
 5548:       $stuname=$ENV{'REMOTE_ADDR'};
 5549:   }
 5550:   my $now=time;
 5551:   my %hash;
 5552:   my $path=LONCAPA::tempdir();
 5553:   if (tie(%hash,'GDBM_File',
 5554: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5555: 	  &GDBM_WRCREAT(),0640)) {
 5556:     $hash{"version:$symb"}++;
 5557:     my $version=$hash{"version:$symb"};
 5558:     my $allkeys=''; 
 5559:     foreach my $key (keys(%$storehash)) {
 5560:       $allkeys.=$key.':';
 5561:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5562:     }
 5563:     $hash{"$version:$symb:timestamp"}=$now;
 5564:     $allkeys.='timestamp';
 5565:     $hash{"$version:keys:$symb"}=$allkeys;
 5566:     if (untie(%hash)) {
 5567:       return 'ok';
 5568:     } else {
 5569:       return "error:$!";
 5570:     }
 5571:   } else {
 5572:     return "error:$!";
 5573:   }
 5574: }
 5575: 
 5576: # -----------------------------------------------------------------Temp Restore
 5577: 
 5578: sub tmprestore {
 5579:   my ($symb,$namespace,$domain,$stuname) = @_;
 5580: 
 5581:   if (!$symb) {
 5582:     $symb=&symbread();
 5583:     if (!$symb) { $symb= $env{'request.url'}; }
 5584:   }
 5585:   $symb=escape($symb);
 5586: 
 5587:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5588: 
 5589:   if (!$domain) { $domain=$env{'user.domain'}; }
 5590:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5591:   if ($domain eq 'public' && $stuname eq 'public') {
 5592:       $stuname=$ENV{'REMOTE_ADDR'};
 5593:   }
 5594:   my %returnhash;
 5595:   $namespace=~s/\//\_/g;
 5596:   $namespace=~s/\W//g;
 5597:   my %hash;
 5598:   my $path=LONCAPA::tempdir();
 5599:   if (tie(%hash,'GDBM_File',
 5600: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5601: 	  &GDBM_READER(),0640)) {
 5602:     my $version=$hash{"version:$symb"};
 5603:     $returnhash{'version'}=$version;
 5604:     my $scope;
 5605:     for ($scope=1;$scope<=$version;$scope++) {
 5606:       my $vkeys=$hash{"$scope:keys:$symb"};
 5607:       my @keys=split(/:/,$vkeys);
 5608:       my $key;
 5609:       $returnhash{"$scope:keys"}=$vkeys;
 5610:       foreach $key (@keys) {
 5611: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5612: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5613:       }
 5614:     }
 5615:     if (!(untie(%hash))) {
 5616:       return "error:$!";
 5617:     }
 5618:   } else {
 5619:     return "error:$!";
 5620:   }
 5621:   return %returnhash;
 5622: }
 5623: 
 5624: # ----------------------------------------------------------------------- Store
 5625: 
 5626: sub store {
 5627:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5628:     my $home='';
 5629: 
 5630:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5631: 
 5632:     $symb=&symbclean($symb);
 5633:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5634: 
 5635:     if (!$domain) { $domain=$env{'user.domain'}; }
 5636:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5637: 
 5638:     &devalidate($symb,$stuname,$domain);
 5639: 
 5640:     $symb=escape($symb);
 5641:     if (!$namespace) { 
 5642:        unless ($namespace=$env{'request.course.id'}) { 
 5643:           return ''; 
 5644:        } 
 5645:     }
 5646:     if (!$home) { $home=$env{'user.home'}; }
 5647: 
 5648:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5649:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5650: 
 5651:     my $namevalue='';
 5652:     foreach my $key (keys(%$storehash)) {
 5653:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5654:     }
 5655:     $namevalue=~s/\&$//;
 5656:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5657:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5658: }
 5659: 
 5660: # -------------------------------------------------------------- Critical Store
 5661: 
 5662: sub cstore {
 5663:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5664:     my $home='';
 5665: 
 5666:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5667: 
 5668:     $symb=&symbclean($symb);
 5669:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5670: 
 5671:     if (!$domain) { $domain=$env{'user.domain'}; }
 5672:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5673: 
 5674:     &devalidate($symb,$stuname,$domain);
 5675: 
 5676:     $symb=escape($symb);
 5677:     if (!$namespace) { 
 5678:        unless ($namespace=$env{'request.course.id'}) { 
 5679:           return ''; 
 5680:        } 
 5681:     }
 5682:     if (!$home) { $home=$env{'user.home'}; }
 5683: 
 5684:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5685:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5686: 
 5687:     my $namevalue='';
 5688:     foreach my $key (keys(%$storehash)) {
 5689:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5690:     }
 5691:     $namevalue=~s/\&$//;
 5692:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5693:     return critical
 5694:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5695: }
 5696: 
 5697: # --------------------------------------------------------------------- Restore
 5698: 
 5699: sub restore {
 5700:     my ($symb,$namespace,$domain,$stuname) = @_;
 5701:     my $home='';
 5702: 
 5703:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5704: 
 5705:     if (!$symb) {
 5706:         return if ($namespace eq 'courserequests');
 5707:         unless ($symb=escape(&symbread())) { return ''; }
 5708:     } else {
 5709:         unless ($namespace eq 'courserequests') {
 5710:             $symb=&escape(&symbclean($symb));
 5711:         }
 5712:     }
 5713:     if (!$namespace) { 
 5714:        unless ($namespace=$env{'request.course.id'}) { 
 5715:           return ''; 
 5716:        } 
 5717:     }
 5718:     if (!$domain) { $domain=$env{'user.domain'}; }
 5719:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5720:     if (!$home) { $home=$env{'user.home'}; }
 5721:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5722: 
 5723:     my %returnhash=();
 5724:     foreach my $line (split(/\&/,$answer)) {
 5725: 	my ($name,$value)=split(/\=/,$line);
 5726:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5727:     }
 5728:     my $version;
 5729:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5730:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5731:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5732:        }
 5733:     }
 5734:     return %returnhash;
 5735: }
 5736: 
 5737: # ---------------------------------------------------------- Course Description
 5738: #
 5739: #  
 5740: 
 5741: sub coursedescription {
 5742:     my ($courseid,$args)=@_;
 5743:     $courseid=~s/^\///;
 5744:     $courseid=~s/\_/\//g;
 5745:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5746:     my $chome=&homeserver($cnum,$cdomain);
 5747:     my $normalid=$cdomain.'_'.$cnum;
 5748:     # need to always cache even if we get errors otherwise we keep 
 5749:     # trying and trying and trying to get the course description.
 5750:     my %envhash=();
 5751:     my %returnhash=();
 5752:     
 5753:     my $expiretime=600;
 5754:     if ($env{'request.course.id'} eq $normalid) {
 5755: 	$expiretime=120;
 5756:     }
 5757: 
 5758:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5759:     if (!$args->{'freshen_cache'}
 5760: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5761: 	foreach my $key (keys(%env)) {
 5762: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5763: 	    my ($setting) = $1;
 5764: 	    $returnhash{$setting} = $env{$key};
 5765: 	}
 5766: 	return %returnhash;
 5767:     }
 5768: 
 5769:     # get the data again
 5770: 
 5771:     if (!$args->{'one_time'}) {
 5772: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5773:     }
 5774: 
 5775:     if ($chome ne 'no_host') {
 5776:        %returnhash=&dump('environment',$cdomain,$cnum);
 5777:        if (!exists($returnhash{'con_lost'})) {
 5778: 	   my $username = $env{'user.name'}; # Defult username
 5779: 	   if(defined $args->{'user'}) {
 5780: 	       $username = $args->{'user'};
 5781: 	   }
 5782:            $returnhash{'home'}= $chome;
 5783: 	   $returnhash{'domain'} = $cdomain;
 5784: 	   $returnhash{'num'} = $cnum;
 5785:            if (!defined($returnhash{'type'})) {
 5786:                $returnhash{'type'} = 'Course';
 5787:            }
 5788:            while (my ($name,$value) = each %returnhash) {
 5789:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5790:            }
 5791:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5792:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5793: 	       $username.'_'.$cdomain.'_'.$cnum;
 5794:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5795:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5796:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5797:        }
 5798:     }
 5799:     if (!$args->{'one_time'}) {
 5800: 	&appenv(\%envhash);
 5801:     }
 5802:     return %returnhash;
 5803: }
 5804: 
 5805: sub update_released_required {
 5806:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5807:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5808:         $cid = $env{'request.course.id'};
 5809:         $cdom = $env{'course.'.$cid.'.domain'};
 5810:         $cnum = $env{'course.'.$cid.'.num'};
 5811:         $chome = $env{'course.'.$cid.'.home'};
 5812:     }
 5813:     if ($needsrelease) {
 5814:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5815:         my $needsupdate;
 5816:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5817:             $needsupdate = 1;
 5818:         } else {
 5819:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5820:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5821:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5822:                 $needsupdate = 1;
 5823:             }
 5824:         }
 5825:         if ($needsupdate) {
 5826:             my %needshash = (
 5827:                              'internal.releaserequired' => $needsrelease,
 5828:                             );
 5829:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5830:             if ($putresult eq 'ok') {
 5831:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5832:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5833:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5834:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5835:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5836:                 }
 5837:             }
 5838:         }
 5839:     }
 5840:     return;
 5841: }
 5842: 
 5843: # -------------------------------------------------See if a user is privileged
 5844: 
 5845: sub privileged {
 5846:     my ($username,$domain,$possdomains,$possroles)=@_;
 5847:     my $now = time;
 5848:     my $roles;
 5849:     if (ref($possroles) eq 'ARRAY') {
 5850:         $roles = $possroles; 
 5851:     } else {
 5852:         $roles = ['dc','su'];
 5853:     }
 5854:     if (ref($possdomains) eq 'ARRAY') {
 5855:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5856:         foreach my $dom (@{$possdomains}) {
 5857:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5858:                 (ref($privileged{$dom}) eq 'HASH')) {
 5859:                 foreach my $role (@{$roles}) {
 5860:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5861:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5862:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5863:                             return 1 unless (($end && $end < $now) ||
 5864:                                              ($start && $start > $now));
 5865:                         }
 5866:                     }
 5867:                 }
 5868:             }
 5869:         }
 5870:     } else {
 5871:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5872:         my $now = time;
 5873: 
 5874:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5875:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5876:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5877:                 return 1 unless ($tend && $tend < $now) 
 5878:                         or ($tstart && $tstart > $now);
 5879:             }
 5880:         }
 5881:     }
 5882:     return 0;
 5883: }
 5884: 
 5885: sub privileged_by_domain {
 5886:     my ($domains,$roles) = @_;
 5887:     my %privileged = ();
 5888:     my $cachetime = 60*60*24;
 5889:     my $now = time;
 5890:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5891:         return %privileged;
 5892:     }
 5893:     foreach my $dom (@{$domains}) {
 5894:         next if (ref($privileged{$dom}) eq 'HASH');
 5895:         my $needroles;
 5896:         foreach my $role (@{$roles}) {
 5897:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5898:             if (defined($cached)) {
 5899:                 if (ref($result) eq 'HASH') {
 5900:                     $privileged{$dom}{$role} = $result;
 5901:                 }
 5902:             } else {
 5903:                 $needroles = 1;
 5904:             }
 5905:         }
 5906:         if ($needroles) {
 5907:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5908:             $privileged{$dom} = {};
 5909:             foreach my $server (keys(%dompersonnel)) {
 5910:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5911:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5912:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5913:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5914:                         next if ($end && $end < $now);
 5915:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5916:                             $dompersonnel{$server}{$item};
 5917:                     }
 5918:                 }
 5919:             }
 5920:             if (ref($privileged{$dom}) eq 'HASH') {
 5921:                 foreach my $role (@{$roles}) {
 5922:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5923:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5924:                     } else {
 5925:                         my %hash = ();
 5926:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5927:                     }
 5928:                 }
 5929:             }
 5930:         }
 5931:     }
 5932:     return %privileged;
 5933: }
 5934: 
 5935: # -------------------------------------------------------- Get user privileges
 5936: 
 5937: sub rolesinit {
 5938:     my ($domain, $username) = @_;
 5939:     my %userroles = ('user.login.time' => time);
 5940:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5941: 
 5942:     # firstaccess and timerinterval are related to timed maps/resources. 
 5943:     # also, blocking can be triggered by an activating timer
 5944:     # it's saved in the user's %env.
 5945:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5946:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5947:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5948:         %timerintchk, %timerintenv);
 5949: 
 5950:     foreach my $key (keys(%firstaccess)) {
 5951:         my ($cid, $rest) = split(/\0/, $key);
 5952:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5953:     }
 5954: 
 5955:     foreach my $key (keys(%timerinterval)) {
 5956:         my ($cid,$rest) = split(/\0/,$key);
 5957:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5958:     }
 5959: 
 5960:     my %allroles=();
 5961:     my %allgroups=();
 5962: 
 5963:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5964:         my $role = $rolesdump{$area};
 5965:         $area =~ s/\_\w\w$//;
 5966: 
 5967:         my ($trole, $tend, $tstart, $group_privs);
 5968: 
 5969:         if ($role =~ /^cr/) {
 5970:         # Custom role, defined by a user 
 5971:         # e.g., user.role.cr/msu/smith/mynewrole
 5972:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5973:                 $trole = $1;
 5974:                 ($tend, $tstart) = split('_', $2);
 5975:             } else {
 5976:                 $trole = $role;
 5977:             }
 5978:         } elsif ($role =~ m|^gr/|) {
 5979:         # Role of member in a group, defined within a course/community
 5980:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5981:             ($trole, $tend, $tstart) = split(/_/, $role);
 5982:             next if $tstart eq '-1';
 5983:             ($trole, $group_privs) = split(/\//, $trole);
 5984:             $group_privs = &unescape($group_privs);
 5985:         } else {
 5986:         # Just a normal role, defined in roles.tab
 5987:             ($trole, $tend, $tstart) = split(/_/,$role);
 5988:         }
 5989: 
 5990:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5991:                  $username);
 5992:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5993: 
 5994:         # role expired or not available yet?
 5995:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5996:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5997: 
 5998:         next if $area eq '' or $trole eq '';
 5999: 
 6000:         my $spec = "$trole.$area";
 6001:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6002: 
 6003:         if ($trole =~ /^cr\//) {
 6004:         # Custom role, defined by a user
 6005:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6006:         } elsif ($trole eq 'gr') {
 6007:         # Role of a member in a group, defined within a course/community
 6008:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6009:             next;
 6010:         } else {
 6011:         # Normal role, defined in roles.tab
 6012:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6013:         }
 6014: 
 6015:         my $cid = $tdomain.'_'.$trest;
 6016:         unless ($firstaccchk{$cid}) {
 6017:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6018:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6019:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6020:                         $coursetimerstarts{$cid}{$item}; 
 6021:                 }
 6022:             }
 6023:             $firstaccchk{$cid} = 1;
 6024:         }
 6025:         unless ($timerintchk{$cid}) {
 6026:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6027:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6028:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6029:                        $coursetimerintervals{$cid}{$item};
 6030:                 }
 6031:             }
 6032:             $timerintchk{$cid} = 1;
 6033:         }
 6034:     }
 6035: 
 6036:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6037:                                                           \%allroles, \%allgroups);
 6038:     $env{'user.adv'} = $userroles{'user.adv'};
 6039:     $env{'user.rar'} = $userroles{'user.rar'};
 6040: 
 6041:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6042: }
 6043: 
 6044: sub set_arearole {
 6045:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6046:     unless ($nolog) {
 6047: # log the associated role with the area
 6048:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6049:     }
 6050:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6051: }
 6052: 
 6053: sub custom_roleprivs {
 6054:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6055:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6056:     my $homsvr = &homeserver($rauthor,$rdomain);
 6057:     if (&hostname($homsvr) ne '') {
 6058:         my ($rdummy,$roledef)=
 6059:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6060:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6061:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6062:             if (defined($syspriv)) {
 6063:                 if ($trest =~ /^$match_community$/) {
 6064:                     $syspriv =~ s/bre\&S//; 
 6065:                 }
 6066:                 $$allroles{'cm./'}.=':'.$syspriv;
 6067:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6068:             }
 6069:             if ($tdomain ne '') {
 6070:                 if (defined($dompriv)) {
 6071:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6072:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6073:                 }
 6074:                 if (($trest ne '') && (defined($coursepriv))) {
 6075:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6076:                         my $rolename = $1;
 6077:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6078:                     }
 6079:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6080:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6081:                 }
 6082:             }
 6083:         }
 6084:     }
 6085: }
 6086: 
 6087: sub course_adhocrole_privs {
 6088:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6089:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6090:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6091:         my (%currprivs,%storeprivs);
 6092:         foreach my $item (split(/:/,$coursepriv)) {
 6093:             my ($priv,$restrict) = split(/\&/,$item);
 6094:             $currprivs{$priv} = $restrict;
 6095:         }
 6096:         my (%possadd,%possremove,%full);
 6097:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6098:             my ($priv,$restrict)=split(/\&/,$item);
 6099:             $full{$priv} = $restrict;
 6100:         }
 6101:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6102:              next if ($item eq '');
 6103:              my ($rule,$rest) = split(/=/,$item);
 6104:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6105:              foreach my $priv (split(/:/,$rest)) {
 6106:                  if ($priv ne '') {
 6107:                      if ($rule eq 'off') {
 6108:                          $possremove{$priv} = 1;
 6109:                      } else {
 6110:                          $possadd{$priv} = 1;
 6111:                      }
 6112:                  }
 6113:              }
 6114:          }
 6115:          foreach my $priv (sort(keys(%full))) {
 6116:              if (exists($currprivs{$priv})) {
 6117:                  unless (exists($possremove{$priv})) {
 6118:                      $storeprivs{$priv} = $currprivs{$priv};
 6119:                  }
 6120:              } elsif (exists($possadd{$priv})) {
 6121:                  $storeprivs{$priv} = $full{$priv};
 6122:              }
 6123:          }
 6124:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6125:      }
 6126:      return $coursepriv;
 6127: }
 6128: 
 6129: sub group_roleprivs {
 6130:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6131:     my $access = 1;
 6132:     my $now = time;
 6133:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6134:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6135:     if ($access) {
 6136:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6137:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6138:     }
 6139: }
 6140: 
 6141: sub standard_roleprivs {
 6142:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6143:     if (defined($pr{$trole.':s'})) {
 6144:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6145:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6146:     }
 6147:     if ($tdomain ne '') {
 6148:         if (defined($pr{$trole.':d'})) {
 6149:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6150:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6151:         }
 6152:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6153:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6154:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6155:         }
 6156:     }
 6157: }
 6158: 
 6159: sub set_userprivs {
 6160:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6161:     my $author=0;
 6162:     my $adv=0;
 6163:     my $rar=0;
 6164:     my %grouproles = ();
 6165:     if (keys(%{$allgroups}) > 0) {
 6166:         my @groupkeys; 
 6167:         foreach my $role (keys(%{$allroles})) {
 6168:             push(@groupkeys,$role);
 6169:         }
 6170:         if (ref($groups_roles) eq 'HASH') {
 6171:             foreach my $key (keys(%{$groups_roles})) {
 6172:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6173:                     push(@groupkeys,$key);
 6174:                 }
 6175:             }
 6176:         }
 6177:         if (@groupkeys > 0) {
 6178:             foreach my $role (@groupkeys) {
 6179:                 my ($trole,$area,$sec,$extendedarea);
 6180:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6181:                     $trole = $1;
 6182:                     $area = $2;
 6183:                     $sec = $3;
 6184:                     $extendedarea = $area.$sec;
 6185:                     if (exists($$allgroups{$area})) {
 6186:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6187:                             my $spec = $trole.'.'.$extendedarea;
 6188:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6189:                                                 $$allgroups{$area}{$group};
 6190:                         }
 6191:                     }
 6192:                 }
 6193:             }
 6194:         }
 6195:     }
 6196:     foreach my $group (keys(%grouproles)) {
 6197:         $$allroles{$group} = $grouproles{$group};
 6198:     }
 6199:     foreach my $role (keys(%{$allroles})) {
 6200:         my %thesepriv;
 6201:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6202:         foreach my $item (split(/:/,$$allroles{$role})) {
 6203:             if ($item ne '') {
 6204:                 my ($privilege,$restrictions)=split(/&/,$item);
 6205:                 if ($restrictions eq '') {
 6206:                     $thesepriv{$privilege}='F';
 6207:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6208:                     $thesepriv{$privilege}.=$restrictions;
 6209:                 }
 6210:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6211:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6212:             }
 6213:         }
 6214:         my $thesestr='';
 6215:         foreach my $priv (sort(keys(%thesepriv))) {
 6216: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6217: 	}
 6218:         $userroles->{'user.priv.'.$role} = $thesestr;
 6219:     }
 6220:     return ($author,$adv,$rar);
 6221: }
 6222: 
 6223: sub role_status {
 6224:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6225:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6226:         my ($one,$two) = split(m{\./},$rolekey,2);
 6227:         (undef,undef,$$role) = split(/\./,$one,3);
 6228:         unless (!defined($$role) || $$role eq '') {
 6229:             $$where = '/'.$two;
 6230:             $$trolecode=$$role.'.'.$$where;
 6231:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6232:             $$tstatus='is';
 6233:             if ($$tstart && $$tstart>$update) {
 6234:                 $$tstatus='future';
 6235:                 if ($$tstart<$now) {
 6236:                     if ($$tstart && $$tstart>$refresh) {
 6237:                         if (($$where ne '') && ($$role ne '')) {
 6238:                             my (%allroles,%allgroups,$group_privs,
 6239:                                 %groups_roles,@rolecodes);
 6240:                             my %userroles = (
 6241:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6242:                             );
 6243:                             @rolecodes = ('cm'); 
 6244:                             my $spec=$$role.'.'.$$where;
 6245:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6246:                             if ($$role =~ /^cr\//) {
 6247:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6248:                                 push(@rolecodes,'cr');
 6249:                             } elsif ($$role eq 'gr') {
 6250:                                 push(@rolecodes,$$role);
 6251:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6252:                                                     $env{'user.name'});
 6253:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6254:                                 (undef,my $group_privs) = split(/\//,$trole);
 6255:                                 $group_privs = &unescape($group_privs);
 6256:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6257:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6258:                                 &get_groups_roles($tdomain,$trest,
 6259:                                                   \%course_roles,\@rolecodes,
 6260:                                                   \%groups_roles);
 6261:                             } else {
 6262:                                 push(@rolecodes,$$role);
 6263:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6264:                             }
 6265:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6266:                                                                    \%groups_roles);
 6267:                             &appenv(\%userroles,\@rolecodes);
 6268:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6269:                         }
 6270:                     }
 6271:                     $$tstatus = 'is';
 6272:                 }
 6273:             }
 6274:             if ($$tend) {
 6275:                 if ($$tend<$update) {
 6276:                     $$tstatus='expired';
 6277:                 } elsif ($$tend<$now) {
 6278:                     $$tstatus='will_not';
 6279:                 }
 6280:             }
 6281:         }
 6282:     }
 6283: }
 6284: 
 6285: sub get_groups_roles {
 6286:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6287:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6288:                   (ref($rolecodes) eq 'ARRAY') && 
 6289:                   (ref($groups_roles) eq 'HASH')); 
 6290:     if (keys(%{$cdom_courseroles}) > 0) {
 6291:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6292:         if ($cdom ne '' && $cnum ne '') {
 6293:             foreach my $key (keys(%{$cdom_courseroles})) {
 6294:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6295:                     my $crsrole = $1;
 6296:                     my $crssec = $2;
 6297:                     if ($crsrole =~ /^cr/) {
 6298:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6299:                             push(@{$rolecodes},'cr');
 6300:                         }
 6301:                     } else {
 6302:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6303:                             push(@{$rolecodes},$crsrole);
 6304:                         }
 6305:                     }
 6306:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6307:                     if ($crssec ne '') {
 6308:                         $rolekey .= "/$crssec";
 6309:                     }
 6310:                     $rolekey .= './';
 6311:                     $groups_roles->{$rolekey} = $rolecodes;
 6312:                 }
 6313:             }
 6314:         }
 6315:     }
 6316:     return;
 6317: }
 6318: 
 6319: sub delete_env_groupprivs {
 6320:     my ($where,$courseroles,$possroles) = @_;
 6321:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6322:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6323:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6324:         %{$courseroles->{$udom}} =
 6325:             &get_my_roles('','','userroles',['active'],
 6326:                           $possroles,[$udom],1);
 6327:     }
 6328:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6329:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6330:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6331:             my $area = '/'.$cdom.'/'.$cnum;
 6332:             my $privkey = "user.priv.$crsrole.$area";
 6333:             if ($crssec ne '') {
 6334:                 $privkey .= '/'.$crssec;
 6335:             }
 6336:             $privkey .= ".$area/$group";
 6337:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6338:         }
 6339:     }
 6340:     return;
 6341: }
 6342: 
 6343: sub check_adhoc_privs {
 6344:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6345:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6346:     if ($sec) {
 6347:         $cckey .= '/'.$sec;
 6348:     } 
 6349:     my $setprivs;
 6350:     if ($env{$cckey}) {
 6351:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6352:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6353:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6354:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6355:             $setprivs = 1;
 6356:         }
 6357:     } else {
 6358:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6359:         $setprivs = 1;
 6360:     }
 6361:     return $setprivs;
 6362: }
 6363: 
 6364: sub set_adhoc_privileges {
 6365: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6366:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6367:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6368:     if ($sec ne '') {
 6369:         $area .= '/'.$sec;
 6370:     }
 6371:     my $spec = $role.'.'.$area;
 6372:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6373:                                   $env{'user.name'},1);
 6374:     my %rolehash = ();
 6375:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6376:         my $rolename = $1;
 6377:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6378:         my %domdef = &get_domain_defaults($dcdom);
 6379:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6380:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6381:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6382:             }
 6383:         }
 6384:     } else {
 6385:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6386:     }
 6387:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6388:     &appenv(\%userroles,[$role,'cm']);
 6389:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6390:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6391:         &appenv( {'request.role'        => $spec,
 6392:                   'request.role.domain' => $dcdom,
 6393:                   'request.course.sec'  => $sec,
 6394:                  }
 6395:                );
 6396:         my $tadv=0;
 6397:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6398:         &appenv({'request.role.adv'    => $tadv});
 6399:     }
 6400: }
 6401: 
 6402: # --------------------------------------------------------------- get interface
 6403: 
 6404: sub get {
 6405:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6406:    my $items='';
 6407:    foreach my $item (@$storearr) {
 6408:        $items.=&escape($item).'&';
 6409:    }
 6410:    $items=~s/\&$//;
 6411:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6412:    if (!$uname) { $uname=$env{'user.name'}; }
 6413:    my $uhome=&homeserver($uname,$udomain);
 6414: 
 6415:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6416:    my @pairs=split(/\&/,$rep);
 6417:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6418:      return @pairs;
 6419:    }
 6420:    my %returnhash=();
 6421:    my $i=0;
 6422:    foreach my $item (@$storearr) {
 6423:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6424:       $i++;
 6425:    }
 6426:    return %returnhash;
 6427: }
 6428: 
 6429: # --------------------------------------------------------------- del interface
 6430: 
 6431: sub del {
 6432:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6433:    my $items='';
 6434:    foreach my $item (@$storearr) {
 6435:        $items.=&escape($item).'&';
 6436:    }
 6437: 
 6438:    $items=~s/\&$//;
 6439:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6440:    if (!$uname) { $uname=$env{'user.name'}; }
 6441:    my $uhome=&homeserver($uname,$udomain);
 6442:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6443: }
 6444: 
 6445: # -------------------------------------------------------------- dump interface
 6446: 
 6447: sub unserialize {
 6448:     my ($rep, $escapedkeys) = @_;
 6449: 
 6450:     return {} if $rep =~ /^error/;
 6451: 
 6452:     my %returnhash=();
 6453: 	foreach my $item (split(/\&/,$rep)) {
 6454: 	    my ($key, $value) = split(/=/, $item, 2);
 6455: 	    $key = unescape($key) unless $escapedkeys;
 6456: 	    next if $key =~ /^error: 2 /;
 6457: 	    $returnhash{$key} = &thaw_unescape($value);
 6458: 	}
 6459:     #return %returnhash;
 6460:     return \%returnhash;
 6461: }        
 6462: 
 6463: # see Lond::dump_with_regexp
 6464: # if $escapedkeys hash keys won't get unescaped.
 6465: sub dump {
 6466:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6467:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6468:     if (!$uname) { $uname=$env{'user.name'}; }
 6469:     my $uhome=&homeserver($uname,$udomain);
 6470: 
 6471:     if ($regexp) {
 6472:         $regexp=&escape($regexp);
 6473:     } else {
 6474:         $regexp='.';
 6475:     }
 6476:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6477:         # user is hosted on this machine
 6478:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6479:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6480:         return %{unserialize($reply, $escapedkeys)};
 6481:     }
 6482:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6483:     my @pairs=split(/\&/,$rep);
 6484:     my %returnhash=();
 6485:     if (!($rep =~ /^error/ )) {
 6486: 	foreach my $item (@pairs) {
 6487: 	    my ($key,$value)=split(/=/,$item,2);
 6488:         $key = unescape($key) unless $escapedkeys;
 6489:         #$key = &unescape($key);
 6490: 	    next if ($key =~ /^error: 2 /);
 6491: 	    $returnhash{$key}=&thaw_unescape($value);
 6492: 	}
 6493:     }
 6494:     return %returnhash;
 6495: }
 6496: 
 6497: 
 6498: # --------------------------------------------------------- dumpstore interface
 6499: 
 6500: sub dumpstore {
 6501:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6502:    # same as dump but keys must be escaped. They may contain colon separated
 6503:    # lists of values that may themself contain colons (e.g. symbs).
 6504:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6505: }
 6506: 
 6507: # -------------------------------------------------------------- keys interface
 6508: 
 6509: sub getkeys {
 6510:    my ($namespace,$udomain,$uname)=@_;
 6511:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6512:    if (!$uname) { $uname=$env{'user.name'}; }
 6513:    my $uhome=&homeserver($uname,$udomain);
 6514:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6515:    my @keyarray=();
 6516:    foreach my $key (split(/\&/,$rep)) {
 6517:       next if ($key =~ /^error: 2 /);
 6518:       push(@keyarray,&unescape($key));
 6519:    }
 6520:    return @keyarray;
 6521: }
 6522: 
 6523: # --------------------------------------------------------------- currentdump
 6524: sub currentdump {
 6525:    my ($courseid,$sdom,$sname)=@_;
 6526:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6527:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6528:    $sname    = $env{'user.name'}         if (! defined($sname));
 6529:    my $uhome = &homeserver($sname,$sdom);
 6530:    my $rep;
 6531: 
 6532:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6533:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6534:                    $courseid)));
 6535:    } else {
 6536:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6537:    }
 6538: 
 6539:    return if ($rep =~ /^(error:|no_such_host)/);
 6540:    #
 6541:    my %returnhash=();
 6542:    #
 6543:    if ($rep eq 'unknown_cmd') {
 6544:        # an old lond will not know currentdump
 6545:        # Do a dump and make it look like a currentdump
 6546:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6547:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6548:        my %hash = @tmp;
 6549:        @tmp=();
 6550:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6551:    } else {
 6552:        my @pairs=split(/\&/,$rep);
 6553:        foreach my $pair (@pairs) {
 6554:            my ($key,$value)=split(/=/,$pair,2);
 6555:            my ($symb,$param) = split(/:/,$key);
 6556:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6557:                                                         &thaw_unescape($value);
 6558:        }
 6559:    }
 6560:    return %returnhash;
 6561: }
 6562: 
 6563: sub convert_dump_to_currentdump{
 6564:     my %hash = %{shift()};
 6565:     my %returnhash;
 6566:     # Code ripped from lond, essentially.  The only difference
 6567:     # here is the unescaping done by lonnet::dump().  Conceivably
 6568:     # we might run in to problems with parameter names =~ /^v\./
 6569:     while (my ($key,$value) = each(%hash)) {
 6570:         my ($v,$symb,$param) = split(/:/,$key);
 6571: 	$symb  = &unescape($symb);
 6572: 	$param = &unescape($param);
 6573:         next if ($v eq 'version' || $symb eq 'keys');
 6574:         next if (exists($returnhash{$symb}) &&
 6575:                  exists($returnhash{$symb}->{$param}) &&
 6576:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6577:         $returnhash{$symb}->{$param}=$value;
 6578:         $returnhash{$symb}->{'v.'.$param}=$v;
 6579:     }
 6580:     #
 6581:     # Remove all of the keys in the hashes which keep track of
 6582:     # the version of the parameter.
 6583:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6584:         # use a foreach because we are going to delete from the hash.
 6585:         foreach my $key (keys(%$param_hash)) {
 6586:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6587:         }
 6588:     }
 6589:     return \%returnhash;
 6590: }
 6591: 
 6592: # ------------------------------------------------------ critical inc interface
 6593: 
 6594: sub cinc {
 6595:     return &inc(@_,'critical');
 6596: }
 6597: 
 6598: # --------------------------------------------------------------- inc interface
 6599: 
 6600: sub inc {
 6601:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6602:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6603:     if (!$uname) { $uname=$env{'user.name'}; }
 6604:     my $uhome=&homeserver($uname,$udomain);
 6605:     my $items='';
 6606:     if (! ref($store)) {
 6607:         # got a single value, so use that instead
 6608:         $items = &escape($store).'=&';
 6609:     } elsif (ref($store) eq 'SCALAR') {
 6610:         $items = &escape($$store).'=&';        
 6611:     } elsif (ref($store) eq 'ARRAY') {
 6612:         $items = join('=&',map {&escape($_);} @{$store});
 6613:     } elsif (ref($store) eq 'HASH') {
 6614:         while (my($key,$value) = each(%{$store})) {
 6615:             $items.= &escape($key).'='.&escape($value).'&';
 6616:         }
 6617:     }
 6618:     $items=~s/\&$//;
 6619:     if ($critical) {
 6620: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6621:     } else {
 6622: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6623:     }
 6624: }
 6625: 
 6626: # --------------------------------------------------------------- put interface
 6627: 
 6628: sub put {
 6629:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6630:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6631:    if (!$uname) { $uname=$env{'user.name'}; }
 6632:    my $uhome=&homeserver($uname,$udomain);
 6633:    my $items='';
 6634:    foreach my $item (keys(%$storehash)) {
 6635:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6636:    }
 6637:    $items=~s/\&$//;
 6638:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6639: }
 6640: 
 6641: # ------------------------------------------------------------ newput interface
 6642: 
 6643: sub newput {
 6644:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6645:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6646:    if (!$uname) { $uname=$env{'user.name'}; }
 6647:    my $uhome=&homeserver($uname,$udomain);
 6648:    my $items='';
 6649:    foreach my $key (keys(%$storehash)) {
 6650:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6651:    }
 6652:    $items=~s/\&$//;
 6653:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6654: }
 6655: 
 6656: # ---------------------------------------------------------  putstore interface
 6657: 
 6658: sub putstore {
 6659:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6660:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6661:    if (!$uname) { $uname=$env{'user.name'}; }
 6662:    my $uhome=&homeserver($uname,$udomain);
 6663:    my $items='';
 6664:    foreach my $key (keys(%$storehash)) {
 6665:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6666:    }
 6667:    $items=~s/\&$//;
 6668:    my $esc_symb=&escape($symb);
 6669:    my $esc_v=&escape($version);
 6670:    my $reply =
 6671:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6672: 	      $uhome);
 6673:    if (($tolog) && ($reply eq 'ok')) {
 6674:        my $namevalue='';
 6675:        foreach my $key (keys(%{$storehash})) {
 6676:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6677:        }
 6678:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6679:                      '&host='.&escape($perlvar{'lonHostID'}).
 6680:                      '&version='.$esc_v.
 6681:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6682:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6683:    }
 6684:    if ($reply eq 'unknown_cmd') {
 6685:        # gfall back to way things use to be done
 6686:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6687: 			    $uname);
 6688:    }
 6689:    return $reply;
 6690: }
 6691: 
 6692: sub old_putstore {
 6693:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6694:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6695:     if (!$uname) { $uname=$env{'user.name'}; }
 6696:     my $uhome=&homeserver($uname,$udomain);
 6697:     my %newstorehash;
 6698:     foreach my $item (keys(%$storehash)) {
 6699: 	my $key = $version.':'.&escape($symb).':'.$item;
 6700: 	$newstorehash{$key} = $storehash->{$item};
 6701:     }
 6702:     my $items='';
 6703:     my %allitems = ();
 6704:     foreach my $item (keys(%newstorehash)) {
 6705: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6706: 	    my $key = $1.':keys:'.$2;
 6707: 	    $allitems{$key} .= $3.':';
 6708: 	}
 6709: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6710:     }
 6711:     foreach my $item (keys(%allitems)) {
 6712: 	$allitems{$item} =~ s/\:$//;
 6713: 	$items.= $item.'='.$allitems{$item}.'&';
 6714:     }
 6715:     $items=~s/\&$//;
 6716:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6717: }
 6718: 
 6719: # ------------------------------------------------------ critical put interface
 6720: 
 6721: sub cput {
 6722:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6723:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6724:    if (!$uname) { $uname=$env{'user.name'}; }
 6725:    my $uhome=&homeserver($uname,$udomain);
 6726:    my $items='';
 6727:    foreach my $item (keys(%$storehash)) {
 6728:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6729:    }
 6730:    $items=~s/\&$//;
 6731:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6732: }
 6733: 
 6734: # -------------------------------------------------------------- eget interface
 6735: 
 6736: sub eget {
 6737:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6738:    my $items='';
 6739:    foreach my $item (@$storearr) {
 6740:        $items.=&escape($item).'&';
 6741:    }
 6742:    $items=~s/\&$//;
 6743:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6744:    if (!$uname) { $uname=$env{'user.name'}; }
 6745:    my $uhome=&homeserver($uname,$udomain);
 6746:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6747:    my @pairs=split(/\&/,$rep);
 6748:    my %returnhash=();
 6749:    my $i=0;
 6750:    foreach my $item (@$storearr) {
 6751:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6752:       $i++;
 6753:    }
 6754:    return %returnhash;
 6755: }
 6756: 
 6757: # ------------------------------------------------------------ tmpput interface
 6758: sub tmpput {
 6759:     my ($storehash,$server,$context)=@_;
 6760:     my $items='';
 6761:     foreach my $item (keys(%$storehash)) {
 6762: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6763:     }
 6764:     $items=~s/\&$//;
 6765:     if (defined($context)) {
 6766:         $items .= ':'.&escape($context);
 6767:     }
 6768:     return &reply("tmpput:$items",$server);
 6769: }
 6770: 
 6771: # ------------------------------------------------------------ tmpget interface
 6772: sub tmpget {
 6773:     my ($token,$server)=@_;
 6774:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6775:     my $rep=&reply("tmpget:$token",$server);
 6776:     my %returnhash;
 6777:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6778:         return %returnhash;
 6779:     }
 6780:     foreach my $item (split(/\&/,$rep)) {
 6781: 	my ($key,$value)=split(/=/,$item);
 6782: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6783:     }
 6784:     return %returnhash;
 6785: }
 6786: 
 6787: # ------------------------------------------------------------ tmpdel interface
 6788: sub tmpdel {
 6789:     my ($token,$server)=@_;
 6790:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6791:     return &reply("tmpdel:$token",$server);
 6792: }
 6793: 
 6794: # ------------------------------------------------------------ get_timebased_id 
 6795: 
 6796: sub get_timebased_id {
 6797:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6798:         $maxtries) = @_;
 6799:     my ($newid,$error,$dellock);
 6800:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6801:         return ('','ok','invalid call to get suffix');
 6802:     }
 6803: 
 6804: # set defaults for any optional args for which values were not supplied
 6805:     if ($who eq '') {
 6806:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6807:     }
 6808:     if (!$locktries) {
 6809:         $locktries = 3;
 6810:     }
 6811:     if (!$maxtries) {
 6812:         $maxtries = 10;
 6813:     }
 6814:     
 6815:     if (($cdom eq '') || ($cnum eq '')) {
 6816:         if ($env{'request.course.id'}) {
 6817:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6818:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6819:         }
 6820:         if (($cdom eq '') || ($cnum eq '')) {
 6821:             return ('','ok','call to get suffix not in course context');
 6822:         }
 6823:     }
 6824: 
 6825: # construct locking item
 6826:     my $lockhash = {
 6827:                       $prefix."\0".'locked_'.$keyid => $who,
 6828:                    };
 6829:     my $tries = 0;
 6830: 
 6831: # attempt to get lock on nohist_$namespace file
 6832:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6833:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6834:         $tries ++;
 6835:         sleep 1;
 6836:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6837:     }
 6838: 
 6839: # attempt to get unique identifier, based on current timestamp
 6840:     if ($gotlock eq 'ok') {
 6841:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6842:         my $id = time;
 6843:         $newid = $id;
 6844:         if ($idtype eq 'addcode') {
 6845:             $newid .= &sixnum_code();
 6846:         }
 6847:         my $idtries = 0;
 6848:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6849:             if ($idtype eq 'concat') {
 6850:                 $newid = $id.$idtries;
 6851:             } elsif ($idtype eq 'addcode') {
 6852:                 $newid = $newid.&sixnum_code();
 6853:             } else {
 6854:                 $newid ++;
 6855:             }
 6856:             $idtries ++;
 6857:         }
 6858:         if (!exists($inuse{$prefix."\0".$newid})) {
 6859:             my %new_item =  (
 6860:                               $prefix."\0".$newid => $who,
 6861:                             );
 6862:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6863:                                                  $cdom,$cnum);
 6864:             if ($putresult ne 'ok') {
 6865:                 undef($newid);
 6866:                 $error = 'error saving new item: '.$putresult;
 6867:             }
 6868:         } else {
 6869:              undef($newid);
 6870:              $error = ('error: no unique suffix available for the new item ');
 6871:         }
 6872: #  remove lock
 6873:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6874:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6875:     } else {
 6876:         $error = "error: could not obtain lockfile\n";
 6877:         $dellock = 'ok';
 6878:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6879:             $dellock = 'nolock';
 6880:         }
 6881:     }
 6882:     return ($newid,$dellock,$error);
 6883: }
 6884: 
 6885: sub sixnum_code {
 6886:     my $code;
 6887:     for (0..6) {
 6888:         $code .= int( rand(9) );
 6889:     }
 6890:     return $code;
 6891: }
 6892: 
 6893: # -------------------------------------------------- portfolio access checking
 6894: 
 6895: sub portfolio_access {
 6896:     my ($requrl,$clientip) = @_;
 6897:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6898:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6899:     if ($result) {
 6900:         my %setters;
 6901:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6902:             my ($startblock,$endblock) =
 6903:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6904:             if ($startblock && $endblock) {
 6905:                 return 'B';
 6906:             }
 6907:         } else {
 6908:             my ($startblock,$endblock) =
 6909:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6910:             if ($startblock && $endblock) {
 6911:                 return 'B';
 6912:             }
 6913:         }
 6914:     }
 6915:     if ($result eq 'ok') {
 6916:        return 'F';
 6917:     } elsif ($result =~ /^[^:]+:guest_/) {
 6918:        return 'A';
 6919:     }
 6920:     return '';
 6921: }
 6922: 
 6923: sub get_portfolio_access {
 6924:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6925: 
 6926:     if (!ref($access_hash)) {
 6927: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6928: 	my %access_controls = &get_access_controls($current_perms,$group,
 6929: 						   $file_name);
 6930: 	$access_hash = $access_controls{$file_name};
 6931:     }
 6932: 
 6933:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6934:     my $now = time;
 6935:     if (ref($access_hash) eq 'HASH') {
 6936:         foreach my $key (keys(%{$access_hash})) {
 6937:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6938:             if ($start > $now) {
 6939:                 next;
 6940:             }
 6941:             if ($end && $end<$now) {
 6942:                 next;
 6943:             }
 6944:             if ($scope eq 'public') {
 6945:                 $public = $key;
 6946:                 last;
 6947:             } elsif ($scope eq 'guest') {
 6948:                 $guest = $key;
 6949:             } elsif ($scope eq 'domains') {
 6950:                 push(@domains,$key);
 6951:             } elsif ($scope eq 'users') {
 6952:                 push(@users,$key);
 6953:             } elsif ($scope eq 'course') {
 6954:                 push(@courses,$key);
 6955:             } elsif ($scope eq 'group') {
 6956:                 push(@groups,$key);
 6957:             } elsif ($scope eq 'ip') {
 6958:                 push(@ips,$key);
 6959:             }
 6960:         }
 6961:         if ($public) {
 6962:             return 'ok';
 6963:         } elsif (@ips > 0) {
 6964:             my $allowed;
 6965:             foreach my $ipkey (@ips) {
 6966:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6967:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6968:                         $allowed = 1;
 6969:                         last; 
 6970:                     }
 6971:                 }
 6972:             }
 6973:             if ($allowed) {
 6974:                 return 'ok';
 6975:             }
 6976:         }
 6977:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6978:             if ($guest) {
 6979:                 return $guest;
 6980:             }
 6981:         } else {
 6982:             if (@domains > 0) {
 6983:                 foreach my $domkey (@domains) {
 6984:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6985:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6986:                             return 'ok';
 6987:                         }
 6988:                     }
 6989:                 }
 6990:             }
 6991:             if (@users > 0) {
 6992:                 foreach my $userkey (@users) {
 6993:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6994:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6995:                             if (ref($item) eq 'HASH') {
 6996:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6997:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6998:                                     return 'ok';
 6999:                                 }
 7000:                             }
 7001:                         }
 7002:                     } 
 7003:                 }
 7004:             }
 7005:             my %roleshash;
 7006:             my @courses_and_groups = @courses;
 7007:             push(@courses_and_groups,@groups); 
 7008:             if (@courses_and_groups > 0) {
 7009:                 my (%allgroups,%allroles); 
 7010:                 my ($start,$end,$role,$sec,$group);
 7011:                 foreach my $envkey (%env) {
 7012:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7013:                         my $cid = $2.'_'.$3; 
 7014:                         if ($1 eq 'gr') {
 7015:                             $group = $4;
 7016:                             $allgroups{$cid}{$group} = $env{$envkey};
 7017:                         } else {
 7018:                             if ($4 eq '') {
 7019:                                 $sec = 'none';
 7020:                             } else {
 7021:                                 $sec = $4;
 7022:                             }
 7023:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7024:                         }
 7025:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7026:                         my $cid = $2.'_'.$3;
 7027:                         if ($4 eq '') {
 7028:                             $sec = 'none';
 7029:                         } else {
 7030:                             $sec = $4;
 7031:                         }
 7032:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7033:                     }
 7034:                 }
 7035:                 if (keys(%allroles) == 0) {
 7036:                     return;
 7037:                 }
 7038:                 foreach my $key (@courses_and_groups) {
 7039:                     my %content = %{$$access_hash{$key}};
 7040:                     my $cnum = $content{'number'};
 7041:                     my $cdom = $content{'domain'};
 7042:                     my $cid = $cdom.'_'.$cnum;
 7043:                     if (!exists($allroles{$cid})) {
 7044:                         next;
 7045:                     }    
 7046:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7047:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7048:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7049:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7050:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7051:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7052:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7053:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7054:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7055:                                         if (grep/^all$/,@sections) {
 7056:                                             return 'ok';
 7057:                                         } else {
 7058:                                             if (grep/^$sec$/,@sections) {
 7059:                                                 return 'ok';
 7060:                                             }
 7061:                                         }
 7062:                                     }
 7063:                                 }
 7064:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7065:                                     if (grep/^none$/,@groups) {
 7066:                                         return 'ok';
 7067:                                     }
 7068:                                 } else {
 7069:                                     if (grep/^all$/,@groups) {
 7070:                                         return 'ok';
 7071:                                     } 
 7072:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7073:                                         if (grep/^$group$/,@groups) {
 7074:                                             return 'ok';
 7075:                                         }
 7076:                                     }
 7077:                                 } 
 7078:                             }
 7079:                         }
 7080:                     }
 7081:                 }
 7082:             }
 7083:             if ($guest) {
 7084:                 return $guest;
 7085:             }
 7086:         }
 7087:     }
 7088:     return;
 7089: }
 7090: 
 7091: sub course_group_datechecker {
 7092:     my ($dates,$now,$status) = @_;
 7093:     my ($start,$end) = split(/\./,$dates);
 7094:     if (!$start && !$end) {
 7095:         return 'ok';
 7096:     }
 7097:     if (grep/^active$/,@{$status}) {
 7098:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7099:             return 'ok';
 7100:         }
 7101:     }
 7102:     if (grep/^previous$/,@{$status}) {
 7103:         if ($end > $now ) {
 7104:             return 'ok';
 7105:         }
 7106:     }
 7107:     if (grep/^future$/,@{$status}) {
 7108:         if ($start > $now) {
 7109:             return 'ok';
 7110:         }
 7111:     }
 7112:     return; 
 7113: }
 7114: 
 7115: sub parse_portfolio_url {
 7116:     my ($url) = @_;
 7117: 
 7118:     my ($type,$udom,$unum,$group,$file_name);
 7119:     
 7120:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7121: 	$type = 1;
 7122:         $udom = $1;
 7123:         $unum = $2;
 7124:         $file_name = $3;
 7125:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7126: 	$type = 2;
 7127:         $udom = $1;
 7128:         $unum = $2;
 7129:         $group = $3;
 7130:         $file_name = $3.'/'.$4;
 7131:     }
 7132:     if (wantarray) {
 7133: 	return ($type,$udom,$unum,$file_name,$group);
 7134:     }
 7135:     return $type;
 7136: }
 7137: 
 7138: sub is_portfolio_url {
 7139:     my ($url) = @_;
 7140:     return scalar(&parse_portfolio_url($url));
 7141: }
 7142: 
 7143: sub is_portfolio_file {
 7144:     my ($file) = @_;
 7145:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7146:         return 1;
 7147:     }
 7148:     return;
 7149: }
 7150: 
 7151: sub usertools_access {
 7152:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7153:     my ($access,%tools);
 7154:     if ($context eq '') {
 7155:         $context = 'tools';
 7156:     }
 7157:     if ($context eq 'requestcourses') {
 7158:         %tools = (
 7159:                       official   => 1,
 7160:                       unofficial => 1,
 7161:                       community  => 1,
 7162:                       textbook   => 1,
 7163:                       placement  => 1,
 7164:                       lti        => 1,
 7165:                  );
 7166:     } elsif ($context eq 'requestauthor') {
 7167:         %tools = (
 7168:                       requestauthor => 1,
 7169:                  );
 7170:     } else {
 7171:         %tools = (
 7172:                       aboutme   => 1,
 7173:                       blog      => 1,
 7174:                       webdav    => 1,
 7175:                       portfolio => 1,
 7176:                  );
 7177:     }
 7178:     return if (!defined($tools{$tool}));
 7179: 
 7180:     if (($udom eq '') || ($uname eq '')) {
 7181:         $udom = $env{'user.domain'};
 7182:         $uname = $env{'user.name'};
 7183:     }
 7184: 
 7185:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7186:         if ($action ne 'reload') {
 7187:             if ($context eq 'requestcourses') {
 7188:                 return $env{'environment.canrequest.'.$tool};
 7189:             } elsif ($context eq 'requestauthor') {
 7190:                 return $env{'environment.canrequest.author'};
 7191:             } else {
 7192:                 return $env{'environment.availabletools.'.$tool};
 7193:             }
 7194:         }
 7195:     }
 7196: 
 7197:     my ($toolstatus,$inststatus,$envkey);
 7198:     if ($context eq 'requestauthor') {
 7199:         $envkey = $context; 
 7200:     } else {
 7201:         $envkey = $context.'.'.$tool;
 7202:     }
 7203: 
 7204:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7205:          ($action ne 'reload')) {
 7206:         $toolstatus = $env{'environment.'.$envkey};
 7207:         $inststatus = $env{'environment.inststatus'};
 7208:     } else {
 7209:         if (ref($userenvref) eq 'HASH') {
 7210:             $toolstatus = $userenvref->{$envkey};
 7211:             $inststatus = $userenvref->{'inststatus'};
 7212:         } else {
 7213:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7214:             $toolstatus = $userenv{$envkey};
 7215:             $inststatus = $userenv{'inststatus'};
 7216:         }
 7217:     }
 7218: 
 7219:     if ($toolstatus ne '') {
 7220:         if ($toolstatus) {
 7221:             $access = 1;
 7222:         } else {
 7223:             $access = 0;
 7224:         }
 7225:         return $access;
 7226:     }
 7227: 
 7228:     my ($is_adv,%domdef);
 7229:     if (ref($is_advref) eq 'HASH') {
 7230:         $is_adv = $is_advref->{'is_adv'};
 7231:     } else {
 7232:         $is_adv = &is_advanced_user($udom,$uname);
 7233:     }
 7234:     if (ref($domdefref) eq 'HASH') {
 7235:         %domdef = %{$domdefref};
 7236:     } else {
 7237:         %domdef = &get_domain_defaults($udom);
 7238:     }
 7239:     if (ref($domdef{$tool}) eq 'HASH') {
 7240:         if ($is_adv) {
 7241:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7242:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7243:                     $access = 1;
 7244:                 } else {
 7245:                     $access = 0;
 7246:                 }
 7247:                 return $access;
 7248:             }
 7249:         }
 7250:         if ($inststatus ne '') {
 7251:             my ($hasaccess,$hasnoaccess);
 7252:             foreach my $affiliation (split(/:/,$inststatus)) {
 7253:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7254:                     if ($domdef{$tool}{$affiliation}) {
 7255:                         $hasaccess = 1;
 7256:                     } else {
 7257:                         $hasnoaccess = 1;
 7258:                     }
 7259:                 }
 7260:             }
 7261:             if ($hasaccess || $hasnoaccess) {
 7262:                 if ($hasaccess) {
 7263:                     $access = 1;
 7264:                 } elsif ($hasnoaccess) {
 7265:                     $access = 0; 
 7266:                 }
 7267:                 return $access;
 7268:             }
 7269:         } else {
 7270:             if ($domdef{$tool}{'default'} ne '') {
 7271:                 if ($domdef{$tool}{'default'}) {
 7272:                     $access = 1;
 7273:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7274:                     $access = 0;
 7275:                 }
 7276:                 return $access;
 7277:             }
 7278:         }
 7279:     } else {
 7280:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7281:             $access = 1;
 7282:         } else {
 7283:             $access = 0;
 7284:         }
 7285:         return $access;
 7286:     }
 7287: }
 7288: 
 7289: sub is_course_owner {
 7290:     my ($cdom,$cnum,$udom,$uname) = @_;
 7291:     if (($udom eq '') || ($uname eq '')) {
 7292:         $udom = $env{'user.domain'};
 7293:         $uname = $env{'user.name'};
 7294:     }
 7295:     unless (($udom eq '') || ($uname eq '')) {
 7296:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7297:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7298:                 return 1;
 7299:             } else {
 7300:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7301:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7302:                     return 1;
 7303:                 }
 7304:             }
 7305:         }
 7306:     }
 7307:     return;
 7308: }
 7309: 
 7310: sub is_advanced_user {
 7311:     my ($udom,$uname) = @_;
 7312:     if ($udom ne '' && $uname ne '') {
 7313:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7314:             if (wantarray) {
 7315:                 return ($env{'user.adv'},$env{'user.author'});
 7316:             } else {
 7317:                 return $env{'user.adv'};
 7318:             }
 7319:         }
 7320:     }
 7321:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7322:     my %allroles;
 7323:     my ($is_adv,$is_author);
 7324:     foreach my $role (keys(%roleshash)) {
 7325:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7326:         my $area = '/'.$tdomain.'/'.$trest;
 7327:         if ($sec ne '') {
 7328:             $area .= '/'.$sec;
 7329:         }
 7330:         if (($area ne '') && ($trole ne '')) {
 7331:             my $spec=$trole.'.'.$area;
 7332:             if ($trole =~ /^cr\//) {
 7333:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7334:             } elsif ($trole ne 'gr') {
 7335:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7336:             }
 7337:             if ($trole eq 'au') {
 7338:                 $is_author = 1;
 7339:             }
 7340:         }
 7341:     }
 7342:     foreach my $role (keys(%allroles)) {
 7343:         last if ($is_adv);
 7344:         foreach my $item (split(/:/,$allroles{$role})) {
 7345:             if ($item ne '') {
 7346:                 my ($privilege,$restrictions)=split(/&/,$item);
 7347:                 if ($privilege eq 'adv') {
 7348:                     $is_adv = 1;
 7349:                     last;
 7350:                 }
 7351:             }
 7352:         }
 7353:     }
 7354:     if (wantarray) {
 7355:         return ($is_adv,$is_author);
 7356:     }
 7357:     return $is_adv;
 7358: }
 7359: 
 7360: sub check_can_request {
 7361:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7362:     my $canreq = 0;
 7363:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7364:         $uname = $env{'user.name'};
 7365:         $udom = $env{'user.domain'};
 7366:     }
 7367:     my ($types,$typename) = &Apache::loncommon::course_types();
 7368:     my @options = ('approval','validate','autolimit');
 7369:     my $optregex = join('|',@options);
 7370:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7371:         foreach my $type (@{$types}) {
 7372:             if (&usertools_access($uname,$udom,$type,undef,
 7373:                                   'requestcourses')) {
 7374:                 $canreq ++;
 7375:                 if (ref($request_domains) eq 'HASH') {
 7376:                     push(@{$request_domains->{$type}},$udom);
 7377:                 }
 7378:                 if ($dom eq $udom) {
 7379:                     $can_request->{$type} = 1;
 7380:                 }
 7381:             }
 7382:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7383:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7384:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7385:                 if (@curr > 0) {
 7386:                     foreach my $item (@curr) {
 7387:                         if (ref($request_domains) eq 'HASH') {
 7388:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7389:                             if ($otherdom ne '') {
 7390:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7391:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7392:                                         push(@{$request_domains->{$type}},$otherdom);
 7393:                                     }
 7394:                                 } else {
 7395:                                     push(@{$request_domains->{$type}},$otherdom);
 7396:                                 }
 7397:                             }
 7398:                         }
 7399:                     }
 7400:                     unless ($dom eq $env{'user.domain'}) {
 7401:                         $canreq ++;
 7402:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7403:                             $can_request->{$type} = 1;
 7404:                         }
 7405:                     }
 7406:                 }
 7407:             }
 7408:         }
 7409:     }
 7410:     return $canreq;
 7411: }
 7412: 
 7413: # ---------------------------------------------- Custom access rule evaluation
 7414: 
 7415: sub customaccess {
 7416:     my ($priv,$uri)=@_;
 7417:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7418:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7419:     $udom = &LONCAPA::clean_domain($udom);
 7420:     $ucrs = &LONCAPA::clean_username($ucrs);
 7421:     my $access=0;
 7422:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7423: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7424: 	if ($type eq 'user') {
 7425: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7426: 		my ($tdom,$tuname)=split(m{/},$scope);
 7427: 		if ($tdom) {
 7428: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7429: 		}
 7430: 		if ($tuname) {
 7431: 		    if ($tuname ne $env{'user.name'}) { next; }
 7432: 		}
 7433: 		$access=($effect eq 'allow');
 7434: 		last;
 7435: 	    }
 7436: 	} else {
 7437: 	    if ($role) {
 7438: 		if ($role ne $urole) { next; }
 7439: 	    }
 7440: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7441: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7442: 		if ($tdom) {
 7443: 		    if ($tdom ne $udom) { next; }
 7444: 		}
 7445: 		if ($tcrs) {
 7446: 		    if ($tcrs ne $ucrs) { next; }
 7447: 		}
 7448: 		if ($tsec) {
 7449: 		    if ($tsec ne $usec) { next; }
 7450: 		}
 7451: 		$access=($effect eq 'allow');
 7452: 		last;
 7453: 	    }
 7454: 	    if ($realm eq '' && $role eq '') {
 7455: 		$access=($effect eq 'allow');
 7456: 	    }
 7457: 	}
 7458:     }
 7459:     return $access;
 7460: }
 7461: 
 7462: # ------------------------------------------------- Check for a user privilege
 7463: 
 7464: sub allowed {
 7465:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7466:     my $ver_orguri=$uri;
 7467:     $uri=&deversion($uri);
 7468:     my $orguri=$uri;
 7469:     $uri=&declutter($uri);
 7470: 
 7471:     if ($priv eq 'evb') {
 7472: # Evade communication block restrictions for specified role in a course
 7473:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7474:             return $1;
 7475:         } else {
 7476:             return;
 7477:         }
 7478:     }
 7479: 
 7480:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7481: # Free bre access to adm and meta resources
 7482:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7483: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7484: 	&& ($priv eq 'bre')) {
 7485: 	return 'F';
 7486:     }
 7487: 
 7488: # Free bre access to user's own portfolio contents
 7489:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7490:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7491: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7492:         my %setters;
 7493:         my ($startblock,$endblock) = 
 7494:             &Apache::loncommon::blockcheck(\%setters,'port');
 7495:         if ($startblock && $endblock) {
 7496:             return 'B';
 7497:         } else {
 7498:             return 'F';
 7499:         }
 7500:     }
 7501: 
 7502: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7503:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7504:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7505:         if (exists($env{'request.course.id'})) {
 7506:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7507:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7508:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7509:                 my $courseprivid=$env{'request.course.id'};
 7510:                 $courseprivid=~s/\_/\//;
 7511:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7512:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7513:                     return $1; 
 7514:                 } else {
 7515:                     if ($env{'request.course.sec'}) {
 7516:                         $courseprivid.='/'.$env{'request.course.sec'};
 7517:                     }
 7518:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7519:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7520:                         return $2;
 7521:                     }
 7522:                 }
 7523:             }
 7524:         }
 7525:     }
 7526: 
 7527: # Free bre to public access
 7528: 
 7529:     if ($priv eq 'bre') {
 7530:         my $copyright;
 7531:         unless ($uri =~ /ext\.tool/) {
 7532:             $copyright=&metadata($uri,'copyright');
 7533:         }
 7534: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7535:            return 'F'; 
 7536:         }
 7537:         if ($copyright eq 'priv') {
 7538:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7539: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7540: 		return '';
 7541:             }
 7542:         }
 7543:         if ($copyright eq 'domain') {
 7544:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7545: 	    unless (($env{'user.domain'} eq $1) ||
 7546:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7547: 		return '';
 7548:             }
 7549:         }
 7550:         if ($env{'request.role'}=~ /li\.\//) {
 7551:             # Library role, so allow browsing of resources in this domain.
 7552:             return 'F';
 7553:         }
 7554:         if ($copyright eq 'custom') {
 7555: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7556:         }
 7557:     }
 7558:     # Domain coordinator is trying to create a course
 7559:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7560:         # uri is the requested domain in this case.
 7561:         # comparison to 'request.role.domain' shows if the user has selected
 7562:         # a role of dc for the domain in question.
 7563:         return 'F' if ($uri eq $env{'request.role.domain'});
 7564:     }
 7565: 
 7566:     my $thisallowed='';
 7567:     my $statecond=0;
 7568:     my $courseprivid='';
 7569: 
 7570:     my $ownaccess;
 7571:     # Community Coordinator or Assistant Co-author browsing resource space.
 7572:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7573:         if ($uri eq '') {
 7574:             $ownaccess = 1;
 7575:         } else {
 7576:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7577:                 my $udom = $env{'user.domain'};
 7578:                 my $uname = $env{'user.name'};
 7579:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7580:                     $ownaccess = 1;
 7581:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7582:                     unless ($uri =~ m{\.\./}) {
 7583:                         $ownaccess = 1;
 7584:                     }
 7585:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7586:                     my $now = time;
 7587:                     if ($uri =~ m{^([^/]+)/?$}) {
 7588:                         my $adom = $1;
 7589:                         foreach my $key (keys(%env)) {
 7590:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7591:                                 my ($start,$end) = split('.',$env{$key});
 7592:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7593:                                     $ownaccess = 1;
 7594:                                     last;
 7595:                                 }
 7596:                             }
 7597:                         }
 7598:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7599:                         my $adom = $1;
 7600:                         my $aname = $2;
 7601:                         foreach my $role ('ca','aa') { 
 7602:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7603:                                 my ($start,$end) =
 7604:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7605:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7606:                                     $ownaccess = 1;
 7607:                                     last;
 7608:                                 }
 7609:                             }
 7610:                         }
 7611:                     }
 7612:                 }
 7613:             }
 7614:         }
 7615:     }
 7616: 
 7617: # Course
 7618: 
 7619:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7620:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7621:             $thisallowed.=$1;
 7622:         }
 7623:     }
 7624: 
 7625: # Domain
 7626: 
 7627:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7628:        =~/\Q$priv\E\&([^\:]*)/) {
 7629:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7630:             $thisallowed.=$1;
 7631:         }
 7632:     }
 7633: 
 7634: # User who is not author or co-author might still be able to edit
 7635: # resource of an author in the domain (e.g., if Domain Coordinator).
 7636:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7637:         (&allowed('mdc',$env{'request.course.id'}))) {
 7638:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7639:             $thisallowed.=$1;
 7640:         }
 7641:     }
 7642: 
 7643: # Course: uri itself is a course
 7644:     my $courseuri=$uri;
 7645:     $courseuri=~s/\_(\d)/\/$1/;
 7646:     $courseuri=~s/^([^\/])/\/$1/;
 7647: 
 7648:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7649:        =~/\Q$priv\E\&([^\:]*)/) {
 7650:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7651:             $thisallowed.=$1;
 7652:         }
 7653:     }
 7654: 
 7655: # URI is an uploaded document for this course, default permissions don't matter
 7656: # not allowing 'edit' access (editupload) to uploaded course docs
 7657:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7658: 	$thisallowed='';
 7659:         my ($match)=&is_on_map($uri);
 7660:         if ($match) {
 7661:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7662:                   =~/\Q$priv\E\&([^\:]*)/) {
 7663:                 my $value = $1;
 7664:                 if ($noblockcheck) {
 7665:                     $thisallowed.=$value;
 7666:                 } else {
 7667:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7668:                     if (@blockers > 0) {
 7669:                         $thisallowed = 'B';
 7670:                     } else {
 7671:                         $thisallowed.=$value;
 7672:                     }
 7673:                 }
 7674:             }
 7675:         } else {
 7676:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7677:             if ($refuri) {
 7678:                 if ($refuri =~ m|^/adm/|) {
 7679:                     $thisallowed='F';
 7680:                 } else {
 7681:                     $refuri=&declutter($refuri);
 7682:                     my ($match) = &is_on_map($refuri);
 7683:                     if ($match) {
 7684:                         if ($noblockcheck) {
 7685:                             $thisallowed='F';
 7686:                         } else {
 7687:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7688:                             if (@blockers > 0) {
 7689:                                 $thisallowed = 'B';
 7690:                             } else {
 7691:                                 $thisallowed='F';
 7692:                             }
 7693:                         }
 7694:                     }
 7695:                 }
 7696:             }
 7697:         }
 7698:     }
 7699: 
 7700:     if ($priv eq 'bre'
 7701: 	&& $thisallowed ne 'F' 
 7702: 	&& $thisallowed ne '2'
 7703: 	&& &is_portfolio_url($uri)) {
 7704: 	$thisallowed = &portfolio_access($uri,$clientip);
 7705:     }
 7706: 
 7707: # Full access at system, domain or course-wide level? Exit.
 7708:     if ($thisallowed=~/F/) {
 7709: 	return 'F';
 7710:     }
 7711: 
 7712: # If this is generating or modifying users, exit with special codes
 7713: 
 7714:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7715: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7716: 	    my ($audom,$auname)=split('/',$uri);
 7717: # no author name given, so this just checks on the general right to make a co-author in this domain
 7718: 	    unless ($auname) { return $thisallowed; }
 7719: # an author name is given, so we are about to actually make a co-author for a certain account
 7720: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7721: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7722: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7723: 	}
 7724: 	return $thisallowed;
 7725:     }
 7726: #
 7727: # Gathered so far: system, domain and course wide privileges
 7728: #
 7729: # Course: See if uri or referer is an individual resource that is part of 
 7730: # the course
 7731: 
 7732:     if ($env{'request.course.id'}) {
 7733: 
 7734:        $courseprivid=$env{'request.course.id'};
 7735:        if ($env{'request.course.sec'}) {
 7736:           $courseprivid.='/'.$env{'request.course.sec'};
 7737:        }
 7738:        $courseprivid=~s/\_/\//;
 7739:        my $checkreferer=1;
 7740:        my ($match,$cond)=&is_on_map($uri);
 7741:        if ($match) {
 7742:            $statecond=$cond;
 7743:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7744:                =~/\Q$priv\E\&([^\:]*)/) {
 7745:                my $value = $1;
 7746:                if ($priv eq 'bre') {
 7747:                    if ($noblockcheck) {
 7748:                        $thisallowed.=$value;
 7749:                    } else {
 7750:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7751:                        if (@blockers > 0) {
 7752:                            $thisallowed = 'B';
 7753:                        } else {
 7754:                            $thisallowed.=$value;
 7755:                        }
 7756:                    }
 7757:                } else {
 7758:                    $thisallowed.=$value;
 7759:                }
 7760:                $checkreferer=0;
 7761:            }
 7762:        }
 7763:        
 7764:        if ($checkreferer) {
 7765: 	  my $refuri=$env{'httpref.'.$orguri};
 7766:             unless ($refuri) {
 7767:                 foreach my $key (keys(%env)) {
 7768: 		    if ($key=~/^httpref\..*\*/) {
 7769: 			my $pattern=$key;
 7770:                         $pattern=~s/^httpref\.\/res\///;
 7771:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7772:                         $pattern=~s/\//\\\//g;
 7773:                         if ($orguri=~/$pattern/) {
 7774: 			    $refuri=$env{$key};
 7775:                         }
 7776:                     }
 7777:                 }
 7778:             }
 7779: 
 7780:          if ($refuri) { 
 7781: 	  $refuri=&declutter($refuri);
 7782:           my ($match,$cond)=&is_on_map($refuri);
 7783:             if ($match) {
 7784:               my $refstatecond=$cond;
 7785:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7786:                   =~/\Q$priv\E\&([^\:]*)/) {
 7787:                   my $value = $1;
 7788:                   if ($priv eq 'bre') {
 7789:                       if ($noblockcheck) {
 7790:                           $thisallowed.=$value;
 7791:                       } else {
 7792:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7793:                           if (@blockers > 0) {
 7794:                               $thisallowed = 'B';
 7795:                           } else {
 7796:                               $thisallowed.=$value;
 7797:                           }
 7798:                       }
 7799:                   } else {
 7800:                       $thisallowed.=$value;
 7801:                   }
 7802:                   $uri=$refuri;
 7803:                   $statecond=$refstatecond;
 7804:               }
 7805:           }
 7806:         }
 7807:        }
 7808:    }
 7809: 
 7810: #
 7811: # Gathered now: all privileges that could apply, and condition number
 7812: # 
 7813: #
 7814: # Full or no access?
 7815: #
 7816: 
 7817:     if ($thisallowed=~/F/) {
 7818: 	return 'F';
 7819:     }
 7820: 
 7821:     unless ($thisallowed) {
 7822:         return '';
 7823:     }
 7824: 
 7825: # Restrictions exist, deal with them
 7826: #
 7827: #   C:according to course preferences
 7828: #   R:according to resource settings
 7829: #   L:unless locked
 7830: #   X:according to user session state
 7831: #
 7832: 
 7833: # Possibly locked functionality, check all courses
 7834: # Locks might take effect only after 10 minutes cache expiration for other
 7835: # courses, and 2 minutes for current course
 7836: 
 7837:     my $envkey;
 7838:     if ($thisallowed=~/L/) {
 7839:         foreach $envkey (keys(%env)) {
 7840:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7841:                my $courseid=$2;
 7842:                my $roleid=$1.'.'.$2;
 7843:                $courseid=~s/^\///;
 7844:                my $expiretime=600;
 7845:                if ($env{'request.role'} eq $roleid) {
 7846: 		  $expiretime=120;
 7847:                }
 7848: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7849:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7850:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7851: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7852:                }
 7853:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7854:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7855: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7856:                        &log($env{'user.domain'},$env{'user.name'},
 7857:                             $env{'user.home'},
 7858:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7859:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7860:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7861: 		       return '';
 7862:                    }
 7863:                }
 7864:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7865:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7866: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7867:                        &log($env{'user.domain'},$env{'user.name'},
 7868:                             $env{'user.home'},
 7869:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7870:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7871:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7872: 		       return '';
 7873:                    }
 7874:                }
 7875: 	   }
 7876:        }
 7877:     }
 7878:    
 7879: #
 7880: # Rest of the restrictions depend on selected course
 7881: #
 7882: 
 7883:     unless ($env{'request.course.id'}) {
 7884: 	if ($thisallowed eq 'A') {
 7885: 	    return 'A';
 7886:         } elsif ($thisallowed eq 'B') {
 7887:             return 'B';
 7888: 	} else {
 7889: 	    return '1';
 7890: 	}
 7891:     }
 7892: 
 7893: #
 7894: # Now user is definitely in a course
 7895: #
 7896: 
 7897: 
 7898: # Course preferences
 7899: 
 7900:    if ($thisallowed=~/C/) {
 7901:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7902:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7903:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7904: 	   =~/\Q$rolecode\E/) {
 7905: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7906: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7907: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7908: 			$env{'request.course.id'});
 7909: 	   }
 7910:            return '';
 7911:        }
 7912: 
 7913:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7914: 	   =~/\Q$unamedom\E/) {
 7915: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7916: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7917: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7918: 			$env{'request.course.id'});
 7919: 	   }
 7920:            return '';
 7921:        }
 7922:    }
 7923: 
 7924: # Resource preferences
 7925: 
 7926:    if ($thisallowed=~/R/) {
 7927:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7928:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7929: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7930: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7931: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7932: 	   }
 7933: 	   return '';
 7934:        }
 7935:    }
 7936: 
 7937: # Restricted by state or randomout?
 7938: 
 7939:    if ($thisallowed=~/X/) {
 7940:       if ($env{'acc.randomout'}) {
 7941: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7942:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7943:             return ''; 
 7944:          }
 7945:       }
 7946:       if (&condval($statecond)) {
 7947: 	 return '2';
 7948:       } else {
 7949:          return '';
 7950:       }
 7951:    }
 7952: 
 7953:     if ($thisallowed eq 'A') {
 7954: 	return 'A';
 7955:     } elsif ($thisallowed eq 'B') {
 7956:         return 'B';
 7957:     }
 7958:    return 'F';
 7959: }
 7960: 
 7961: # ------------------------------------------- Check construction space access
 7962: 
 7963: sub constructaccess {
 7964:     my ($url,$setpriv)=@_;
 7965: 
 7966: # We do not allow editing of previous versions of files
 7967:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7968: 
 7969: # Get username and domain from URL
 7970:     my ($ownername,$ownerdomain,$ownerhome);
 7971: 
 7972:     ($ownerdomain,$ownername) =
 7973:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 7974: 
 7975: # The URL does not really point to any authorspace, forget it
 7976:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7977: 
 7978: # Now we need to see if the user has access to the authorspace of
 7979: # $ownername at $ownerdomain
 7980: 
 7981:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7982: # Real author for this?
 7983:        $ownerhome = $env{'user.home'};
 7984:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7985:           return ($ownername,$ownerdomain,$ownerhome);
 7986:        }
 7987:     } else {
 7988: # Co-author for this?
 7989:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7990:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7991:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7992:             return ($ownername,$ownerdomain,$ownerhome);
 7993:         }
 7994:         if ($env{'request.course.id'}) {
 7995:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 7996:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 7997:                 if (&allowed('mdc',$env{'request.course.id'})) {
 7998:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 7999:                     return ($ownername,$ownerdomain,$ownerhome);
 8000:                 }
 8001:             }
 8002:         }
 8003:     }
 8004: 
 8005: # We don't have any access right now. If we are not possibly going to do anything about this,
 8006: # we might as well leave
 8007:    unless ($setpriv) { return ''; }
 8008: 
 8009: # Backdoor access?
 8010:     my $allowed=&allowed('eco',$ownerdomain);
 8011: # Nope
 8012:     unless ($allowed) { return ''; }
 8013: # Looks like we may have access, but could be locked by the owner of the construction space
 8014:     if ($allowed eq 'U') {
 8015:         my %blocked=&get('environment',['domcoord.author'],
 8016:                          $ownerdomain,$ownername);
 8017: # Is blocked by owner
 8018:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8019:     }
 8020:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8021: # Grant temporary access
 8022:         my $then=$env{'user.login.time'};
 8023:         my $update=$env{'user.update.time'};
 8024:         if (!$update) { $update = $then; }
 8025:         my $refresh=$env{'user.refresh.time'};
 8026:         if (!$refresh) { $refresh = $update; }
 8027:         my $now = time;
 8028:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8029:                            $now,'ca','constructaccess');
 8030:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8031:         return($ownername,$ownerdomain,$ownerhome);
 8032:     }
 8033: # No business here
 8034:     return '';
 8035: }
 8036: 
 8037: # ----------------------------------------------------------- Content Blocking
 8038: 
 8039: {
 8040: # Caches for faster Course Contents display where content blocking
 8041: # is in operation (i.e., interval param set) for timed quiz.
 8042: #
 8043: # User for whom data are being temporarily cached.
 8044: my $cacheduser='';
 8045: # Cached blockers for this user (a hash of blocking items). 
 8046: my %cachedblockers=();
 8047: # When the data were last cached.
 8048: my $cachedlast='';
 8049: 
 8050: sub load_all_blockers {
 8051:     my ($uname,$udom,$blocks)=@_;
 8052:     if (($uname ne '') && ($udom ne '')) { 
 8053:         if (($cacheduser eq $uname.':'.$udom) &&
 8054:             (abs($cachedlast-time)<5)) {
 8055:             return;
 8056:         }
 8057:     }
 8058:     $cachedlast=time;
 8059:     $cacheduser=$uname.':'.$udom;
 8060:     %cachedblockers = &get_commblock_resources($blocks);
 8061: }
 8062: 
 8063: sub get_comm_blocks {
 8064:     my ($cdom,$cnum) = @_;
 8065:     if ($cdom eq '' || $cnum eq '') {
 8066:         return unless ($env{'request.course.id'});
 8067:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8068:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8069:     }
 8070:     my %commblocks;
 8071:     my $hashid=$cdom.'_'.$cnum;
 8072:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8073:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8074:         %commblocks = %{$blocksref};
 8075:     } else {
 8076:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8077:         my $cachetime = 600;
 8078:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8079:     }
 8080:     return %commblocks;
 8081: }
 8082: 
 8083: sub get_commblock_resources {
 8084:     my ($blocks) = @_;
 8085:     my %blockers = ();
 8086:     return %blockers unless ($env{'request.course.id'});
 8087:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8088:     my %commblocks;
 8089:     if (ref($blocks) eq 'HASH') {
 8090:         %commblocks = %{$blocks};
 8091:     } else {
 8092:         %commblocks = &get_comm_blocks();
 8093:     }
 8094:     return %blockers unless (keys(%commblocks) > 0); 
 8095:     my $navmap = Apache::lonnavmaps::navmap->new();
 8096:     return %blockers unless (ref($navmap));
 8097:     my $now = time;
 8098:     foreach my $block (keys(%commblocks)) {
 8099:         if ($block =~ /^(\d+)____(\d+)$/) {
 8100:             my ($start,$end) = ($1,$2);
 8101:             if ($start <= $now && $end >= $now) {
 8102:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8103:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8104:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8105:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8106:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8107:                             }
 8108:                         }
 8109:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8110:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8111:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8112:                             }
 8113:                         }
 8114:                     }
 8115:                 }
 8116:             }
 8117:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8118:             my $item = $1;
 8119:             my @to_test;
 8120:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8121:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8122:                     my @interval;
 8123:                     my $type = 'map';
 8124:                     if ($item eq 'course') {
 8125:                         $type = 'course';
 8126:                         @interval=&EXT("resource.0.interval");
 8127:                     } else {
 8128:                         if ($item =~ /___\d+___/) {
 8129:                             $type = 'resource';
 8130:                             @interval=&EXT("resource.0.interval",$item);
 8131:                             if (ref($navmap)) {                        
 8132:                                 my $res = $navmap->getBySymb($item); 
 8133:                                 push(@to_test,$res);
 8134:                             }
 8135:                         } else {
 8136:                             my $mapsymb = &symbread($item,1);
 8137:                             if ($mapsymb) {
 8138:                                 if (ref($navmap)) {
 8139:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8140:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8141:                                     foreach my $res (@to_test) {
 8142:                                         my $symb = $res->symb();
 8143:                                         next if ($symb eq $mapsymb);
 8144:                                         if ($symb ne '') {
 8145:                                             @interval=&EXT("resource.0.interval",$symb);
 8146:                                             if ($interval[1] eq 'map') {
 8147:                                                 last;
 8148:                                             }
 8149:                                         }
 8150:                                     }
 8151:                                 }
 8152:                             }
 8153:                         }
 8154:                     }
 8155:                     if ($interval[0] =~ /^(\d+)/) {
 8156:                         my $timelimit = $1; 
 8157:                         my $first_access;
 8158:                         if ($type eq 'resource') {
 8159:                             $first_access=&get_first_access($interval[1],$item);
 8160:                         } elsif ($type eq 'map') {
 8161:                             $first_access=&get_first_access($interval[1],undef,$item);
 8162:                         } else {
 8163:                             $first_access=&get_first_access($interval[1]);
 8164:                         }
 8165:                         if ($first_access) {
 8166:                             my $timesup = $first_access+$timelimit;
 8167:                             if ($timesup > $now) {
 8168:                                 my $activeblock;
 8169:                                 foreach my $res (@to_test) {
 8170:                                     if ($res->answerable()) {
 8171:                                         $activeblock = 1;
 8172:                                         last;
 8173:                                     }
 8174:                                 }
 8175:                                 if ($activeblock) {
 8176:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8177:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8178:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8179:                                          }
 8180:                                     }
 8181:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8182:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8183:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8184:                                         }
 8185:                                     }
 8186:                                 }
 8187:                             }
 8188:                         }
 8189:                     }
 8190:                 }
 8191:             }
 8192:         }
 8193:     }
 8194:     return %blockers;
 8195: }
 8196: 
 8197: sub has_comm_blocking {
 8198:     my ($priv,$symb,$uri,$blocks) = @_;
 8199:     my @blockers;
 8200:     return unless ($env{'request.course.id'});
 8201:     return unless ($priv eq 'bre');
 8202:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8203:     return if ($env{'request.state'} eq 'construct');
 8204:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8205:     return unless (keys(%cachedblockers) > 0);
 8206:     my (%possibles,@symbs);
 8207:     if (!$symb) {
 8208:         $symb = &symbread($uri,1,1,1,\%possibles);
 8209:     }
 8210:     if ($symb) {
 8211:         @symbs = ($symb);
 8212:     } elsif (keys(%possibles)) { 
 8213:         @symbs = keys(%possibles);
 8214:     }
 8215:     my $noblock;
 8216:     foreach my $symb (@symbs) {
 8217:         last if ($noblock);
 8218:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8219:         foreach my $block (keys(%cachedblockers)) {
 8220:             if ($block =~ /^firstaccess____(.+)$/) {
 8221:                 my $item = $1;
 8222:                 if (($item eq $map) || ($item eq $symb)) {
 8223:                     $noblock = 1;
 8224:                     last;
 8225:                 }
 8226:             }
 8227:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8228:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8229:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8230:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8231:                             push(@blockers,$block);
 8232:                         }
 8233:                     }
 8234:                 }
 8235:             }
 8236:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8237:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8238:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8239:                         push(@blockers,$block);
 8240:                     }
 8241:                 }
 8242:             }
 8243:         }
 8244:     }
 8245:     return if ($noblock);
 8246:     return @blockers;
 8247: }
 8248: }
 8249: 
 8250: # -------------------------------- Deversion and split uri into path an filename   
 8251: 
 8252: #
 8253: #   Removes the version from a URI and
 8254: #   splits it in to its filename and path to the filename.
 8255: #   Seems like File::Basename could have done this more clearly.
 8256: #   Parameters:
 8257: #      $uri   - input URI
 8258: #   Returns:
 8259: #     Two element list consisting of 
 8260: #     $pathname  - the URI up to and excluding the trailing /
 8261: #     $filename  - The part of the URI following the last /
 8262: #  NOTE:
 8263: #    Another realization of this is simply:
 8264: #    use File::Basename;
 8265: #    ...
 8266: #    $uri = shift;
 8267: #    $filename = basename($uri);
 8268: #    $path     = dirname($uri);
 8269: #    return ($filename, $path);
 8270: #
 8271: #     The implementation below is probably faster however.
 8272: #
 8273: sub split_uri_for_cond {
 8274:     my $uri=&deversion(&declutter(shift));
 8275:     my @uriparts=split(/\//,$uri);
 8276:     my $filename=pop(@uriparts);
 8277:     my $pathname=join('/',@uriparts);
 8278:     return ($pathname,$filename);
 8279: }
 8280: # --------------------------------------------------- Is a resource on the map?
 8281: 
 8282: sub is_on_map {
 8283:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8284:     #Trying to find the conditional for the file
 8285:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8286: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8287:     if ($match) {
 8288: 	return (1,$1);
 8289:     } else {
 8290: 	return (0,0);
 8291:     }
 8292: }
 8293: 
 8294: # --------------------------------------------------------- Get symb from alias
 8295: 
 8296: sub get_symb_from_alias {
 8297:     my $symb=shift;
 8298:     my ($map,$resid,$url)=&decode_symb($symb);
 8299: # Already is a symb
 8300:     if ($url) { return $symb; }
 8301: # Must be an alias
 8302:     my $aliassymb='';
 8303:     my %bighash;
 8304:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8305:                             &GDBM_READER(),0640)) {
 8306:         my $rid=$bighash{'mapalias_'.$symb};
 8307: 	if ($rid) {
 8308: 	    my ($mapid,$resid)=split(/\./,$rid);
 8309: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8310: 				    $resid,$bighash{'src_'.$rid});
 8311: 	}
 8312:         untie %bighash;
 8313:     }
 8314:     return $aliassymb;
 8315: }
 8316: 
 8317: # ----------------------------------------------------------------- Define Role
 8318: 
 8319: sub definerole {
 8320:   if (allowed('mcr','/')) {
 8321:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8322:     foreach my $role (split(':',$sysrole)) {
 8323: 	my ($crole,$cqual)=split(/\&/,$role);
 8324:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8325:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8326: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8327:                return "refused:s:$crole&$cqual"; 
 8328:             }
 8329:         }
 8330:     }
 8331:     foreach my $role (split(':',$domrole)) {
 8332: 	my ($crole,$cqual)=split(/\&/,$role);
 8333:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8334:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8335: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8336:                return "refused:d:$crole&$cqual"; 
 8337:             }
 8338:         }
 8339:     }
 8340:     foreach my $role (split(':',$courole)) {
 8341: 	my ($crole,$cqual)=split(/\&/,$role);
 8342:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8343:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8344: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8345:                return "refused:c:$crole&$cqual"; 
 8346:             }
 8347:         }
 8348:     }
 8349:     my $uhome;
 8350:     if (($uname ne '') && ($udom ne '')) {
 8351:         $uhome = &homeserver($uname,$udom);
 8352:         return $uhome if ($uhome eq 'no_host');
 8353:     } else {
 8354:         $uname = $env{'user.name'};
 8355:         $udom = $env{'user.domain'};
 8356:         $uhome = $env{'user.home'};
 8357:     }
 8358:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8359:                 "$udom:$uname:rolesdef_$rolename=".
 8360:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8361:     return reply($command,$uhome);
 8362:   } else {
 8363:     return 'refused';
 8364:   }
 8365: }
 8366: 
 8367: # ---------------- Make a metadata query against the network of library servers
 8368: 
 8369: sub metadata_query {
 8370:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8371:     my %rhash;
 8372:     my %libserv = &all_library();
 8373:     my @server_list = (defined($server_array) ? @$server_array
 8374:                                               : keys(%libserv) );
 8375:     for my $server (@server_list) {
 8376:         my $domains = ''; 
 8377:         if (ref($domains_hash) eq 'HASH') {
 8378:             $domains = $domains_hash->{$server}; 
 8379:         }
 8380: 	unless ($custom or $customshow) {
 8381: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8382: 	    $rhash{$server}=$reply;
 8383: 	}
 8384: 	else {
 8385: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8386: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8387: 			     $server);
 8388: 	    $rhash{$server}=$reply;
 8389: 	}
 8390:     }
 8391:     return \%rhash;
 8392: }
 8393: 
 8394: # ----------------------------------------- Send log queries and wait for reply
 8395: 
 8396: sub log_query {
 8397:     my ($uname,$udom,$query,%filters)=@_;
 8398:     my $uhome=&homeserver($uname,$udom);
 8399:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8400:     my $uhost=&hostname($uhome);
 8401:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8402:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8403:                        $uhome);
 8404:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8405:     return get_query_reply($queryid);
 8406: }
 8407: 
 8408: # -------------------------- Update MySQL table for portfolio file
 8409: 
 8410: sub update_portfolio_table {
 8411:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8412:     if ($group ne '') {
 8413:         $file_name =~s /^\Q$group\E//;
 8414:     }
 8415:     my $homeserver = &homeserver($uname,$udom);
 8416:     my $queryid=
 8417:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8418:                ':'.&escape($file_name).':'.$action,$homeserver);
 8419:     my $reply = &get_query_reply($queryid);
 8420:     return $reply;
 8421: }
 8422: 
 8423: # -------------------------- Update MySQL allusers table
 8424: 
 8425: sub update_allusers_table {
 8426:     my ($uname,$udom,$names) = @_;
 8427:     my $homeserver = &homeserver($uname,$udom);
 8428:     my $queryid=
 8429:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8430:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8431:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8432:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8433:                'generation='.&escape($names->{'generation'}).'%%'.
 8434:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8435:                'id='.&escape($names->{'id'}),$homeserver);
 8436:     return;
 8437: }
 8438: 
 8439: # ------- Request retrieval of institutional classlists for course(s)
 8440: 
 8441: sub fetch_enrollment_query {
 8442:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8443:     my ($homeserver,$sleep,$loopmax);
 8444:     my $maxtries = 1;
 8445:     if ($context eq 'automated') {
 8446:         $homeserver = $perlvar{'lonHostID'};
 8447:         $sleep = 2;
 8448:         $loopmax = 100;
 8449:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8450:     } else {
 8451:         $homeserver = &homeserver($cnum,$dom);
 8452:     }
 8453:     my $host=&hostname($homeserver);
 8454:     my $cmd = '';
 8455:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8456:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8457:     }
 8458:     $cmd =~ s/%%$//;
 8459:     $cmd = &escape($cmd);
 8460:     my $query = 'fetchenrollment';
 8461:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8462:     unless ($queryid=~/^\Q$host\E\_/) { 
 8463:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8464:         return 'error: '.$queryid;
 8465:     }
 8466:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8467:     my $tries = 1;
 8468:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8469:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8470:         $tries ++;
 8471:     }
 8472:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8473:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8474:     } else {
 8475:         my @responses = split(/:/,$reply);
 8476:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8477:             foreach my $line (@responses) {
 8478:                 my ($key,$value) = split(/=/,$line,2);
 8479:                 $$replyref{$key} = $value;
 8480:             }
 8481:         } else {
 8482:             my $pathname = LONCAPA::tempdir();
 8483:             foreach my $line (@responses) {
 8484:                 my ($key,$value) = split(/=/,$line);
 8485:                 $$replyref{$key} = $value;
 8486:                 if ($value > 0) {
 8487:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8488:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8489:                         my $destname = $pathname.'/'.$filename;
 8490:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8491:                         if ($xml_classlist =~ /^error/) {
 8492:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8493:                         } else {
 8494:                             if ( open(FILE,">",$destname) ) {
 8495:                                 print FILE &unescape($xml_classlist);
 8496:                                 close(FILE);
 8497:                             } else {
 8498:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8499:                             }
 8500:                         }
 8501:                     }
 8502:                 }
 8503:             }
 8504:         }
 8505:         return 'ok';
 8506:     }
 8507:     return 'error';
 8508: }
 8509: 
 8510: sub get_query_reply {
 8511:     my ($queryid,$sleep,$loopmax) = @_;;
 8512:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8513:         $sleep = 0.2;
 8514:     }
 8515:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8516:         $loopmax = 100;
 8517:     }
 8518:     my $replyfile=LONCAPA::tempdir().$queryid;
 8519:     my $reply='';
 8520:     for (1..$loopmax) {
 8521: 	sleep($sleep);
 8522:         if (-e $replyfile.'.end') {
 8523: 	    if (open(my $fh,"<",$replyfile)) {
 8524: 		$reply = join('',<$fh>);
 8525: 		close($fh);
 8526: 	   } else { return 'error: reply_file_error'; }
 8527:            return &unescape($reply);
 8528: 	}
 8529:     }
 8530:     return 'timeout:'.$queryid;
 8531: }
 8532: 
 8533: sub courselog_query {
 8534: #
 8535: # possible filters:
 8536: # url: url or symb
 8537: # username
 8538: # domain
 8539: # action: view, submit, grade
 8540: # start: timestamp
 8541: # end: timestamp
 8542: #
 8543:     my (%filters)=@_;
 8544:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8545:     if ($filters{'url'}) {
 8546: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8547:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8548:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8549:     }
 8550:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8551:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8552:     return &log_query($cname,$cdom,'courselog',%filters);
 8553: }
 8554: 
 8555: sub userlog_query {
 8556: #
 8557: # possible filters:
 8558: # action: log check role
 8559: # start: timestamp
 8560: # end: timestamp
 8561: #
 8562:     my ($uname,$udom,%filters)=@_;
 8563:     return &log_query($uname,$udom,'userlog',%filters);
 8564: }
 8565: 
 8566: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8567: 
 8568: sub auto_run {
 8569:     my ($cnum,$cdom) = @_;
 8570:     my $response = 0;
 8571:     my $settings;
 8572:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8573:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8574:         $settings = $domconfig{'autoenroll'};
 8575:         if ($settings->{'run'} eq '1') {
 8576:             $response = 1;
 8577:         }
 8578:     } else {
 8579:         my $homeserver;
 8580:         if (&is_course($cdom,$cnum)) {
 8581:             $homeserver = &homeserver($cnum,$cdom);
 8582:         } else {
 8583:             $homeserver = &domain($cdom,'primary');
 8584:         }
 8585:         if ($homeserver ne 'no_host') {
 8586:             $response = &reply('autorun:'.$cdom,$homeserver);
 8587:         }
 8588:     }
 8589:     return $response;
 8590: }
 8591: 
 8592: sub auto_get_sections {
 8593:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8594:     my $homeserver;
 8595:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8596:         $homeserver = &homeserver($cnum,$cdom);
 8597:     }
 8598:     if (!defined($homeserver)) { 
 8599:         if ($cdom =~ /^$match_domain$/) {
 8600:             $homeserver = &domain($cdom,'primary');
 8601:         }
 8602:     }
 8603:     my @secs;
 8604:     if (defined($homeserver)) {
 8605:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8606:         unless ($response eq 'refused') {
 8607:             @secs = split(/:/,$response);
 8608:         }
 8609:     }
 8610:     return @secs;
 8611: }
 8612: 
 8613: sub auto_new_course {
 8614:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8615:     my $homeserver = &homeserver($cnum,$cdom);
 8616:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8617:     return $response;
 8618: }
 8619: 
 8620: sub auto_validate_courseID {
 8621:     my ($cnum,$cdom,$inst_course_id) = @_;
 8622:     my $homeserver = &homeserver($cnum,$cdom);
 8623:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8624:     return $response;
 8625: }
 8626: 
 8627: sub auto_validate_instcode {
 8628:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8629:     my ($homeserver,$response);
 8630:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8631:         $homeserver = &homeserver($cnum,$cdom);
 8632:     }
 8633:     if (!defined($homeserver)) {
 8634:         if ($cdom =~ /^$match_domain$/) {
 8635:             $homeserver = &domain($cdom,'primary');
 8636:         }
 8637:     }
 8638:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8639:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8640:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8641:     return ($outcome,$description,$defaultcredits);
 8642: }
 8643: 
 8644: sub auto_create_password {
 8645:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8646:     my ($homeserver,$response);
 8647:     my $create_passwd = 0;
 8648:     my $authchk = '';
 8649:     if ($udom =~ /^$match_domain$/) {
 8650:         $homeserver = &domain($udom,'primary');
 8651:     }
 8652:     if ($homeserver eq '') {
 8653:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8654:             $homeserver = &homeserver($cnum,$cdom);
 8655:         }
 8656:     }
 8657:     if ($homeserver eq '') {
 8658:         $authchk = 'nodomain';
 8659:     } else {
 8660:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8661:         if ($response eq 'refused') {
 8662:             $authchk = 'refused';
 8663:         } else {
 8664:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8665:         }
 8666:     }
 8667:     return ($authparam,$create_passwd,$authchk);
 8668: }
 8669: 
 8670: sub auto_photo_permission {
 8671:     my ($cnum,$cdom,$students) = @_;
 8672:     my $homeserver = &homeserver($cnum,$cdom);
 8673:     my ($outcome,$perm_reqd,$conditions) = 
 8674: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8675:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8676: 	return (undef,undef);
 8677:     }
 8678:     return ($outcome,$perm_reqd,$conditions);
 8679: }
 8680: 
 8681: sub auto_checkphotos {
 8682:     my ($uname,$udom,$pid) = @_;
 8683:     my $homeserver = &homeserver($uname,$udom);
 8684:     my ($result,$resulttype);
 8685:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8686: 				   &escape($uname).':'.&escape($pid),
 8687: 				   $homeserver));
 8688:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8689: 	return (undef,undef);
 8690:     }
 8691:     if ($outcome) {
 8692:         ($result,$resulttype) = split(/:/,$outcome);
 8693:     } 
 8694:     return ($result,$resulttype);
 8695: }
 8696: 
 8697: sub auto_photochoice {
 8698:     my ($cnum,$cdom) = @_;
 8699:     my $homeserver = &homeserver($cnum,$cdom);
 8700:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8701: 						       &escape($cdom),
 8702: 						       $homeserver)));
 8703:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8704: 	return (undef,undef);
 8705:     }
 8706:     return ($update,$comment);
 8707: }
 8708: 
 8709: sub auto_photoupdate {
 8710:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8711:     my $homeserver = &homeserver($cnum,$dom);
 8712:     my $host=&hostname($homeserver);
 8713:     my $cmd = '';
 8714:     my $maxtries = 1;
 8715:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8716:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8717:     }
 8718:     $cmd =~ s/%%$//;
 8719:     $cmd = &escape($cmd);
 8720:     my $query = 'institutionalphotos';
 8721:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8722:     unless ($queryid=~/^\Q$host\E\_/) {
 8723:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8724:         return 'error: '.$queryid;
 8725:     }
 8726:     my $reply = &get_query_reply($queryid);
 8727:     my $tries = 1;
 8728:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8729:         $reply = &get_query_reply($queryid);
 8730:         $tries ++;
 8731:     }
 8732:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8733:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8734:     } else {
 8735:         my @responses = split(/:/,$reply);
 8736:         my $outcome = shift(@responses); 
 8737:         foreach my $item (@responses) {
 8738:             my ($key,$value) = split(/=/,$item);
 8739:             $$photo{$key} = $value;
 8740:         }
 8741:         return $outcome;
 8742:     }
 8743:     return 'error';
 8744: }
 8745: 
 8746: sub auto_instcode_format {
 8747:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8748: 	$cat_order) = @_;
 8749:     my $courses = '';
 8750:     my @homeservers;
 8751:     if ($caller eq 'global') {
 8752: 	my %servers = &get_servers($codedom,'library');
 8753: 	foreach my $tryserver (keys(%servers)) {
 8754: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8755: 		push(@homeservers,$tryserver);
 8756: 	    }
 8757:         }
 8758:     } elsif ($caller eq 'requests') {
 8759:         if ($codedom =~ /^$match_domain$/) {
 8760:             my $chome = &domain($codedom,'primary');
 8761:             unless ($chome eq 'no_host') {
 8762:                 push(@homeservers,$chome);
 8763:             }
 8764:         }
 8765:     } else {
 8766:         push(@homeservers,&homeserver($caller,$codedom));
 8767:     }
 8768:     foreach my $code (keys(%{$instcodes})) {
 8769:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8770:     }
 8771:     chop($courses);
 8772:     my $ok_response = 0;
 8773:     my $response;
 8774:     while (@homeservers > 0 && $ok_response == 0) {
 8775:         my $server = shift(@homeservers); 
 8776:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8777:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8778:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8779: 		split(/:/,$response);
 8780:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8781:             push(@{$codetitles},&str2array($codetitles_str));
 8782:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8783:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8784:             $ok_response = 1;
 8785:         }
 8786:     }
 8787:     if ($ok_response) {
 8788:         return 'ok';
 8789:     } else {
 8790:         return $response;
 8791:     }
 8792: }
 8793: 
 8794: sub auto_instcode_defaults {
 8795:     my ($domain,$returnhash,$code_order) = @_;
 8796:     my @homeservers;
 8797: 
 8798:     my %servers = &get_servers($domain,'library');
 8799:     foreach my $tryserver (keys(%servers)) {
 8800: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8801: 	    push(@homeservers,$tryserver);
 8802: 	}
 8803:     }
 8804: 
 8805:     my $response;
 8806:     foreach my $server (@homeservers) {
 8807:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8808:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8809: 	
 8810: 	foreach my $pair (split(/\&/,$response)) {
 8811: 	    my ($name,$value)=split(/\=/,$pair);
 8812: 	    if ($name eq 'code_order') {
 8813: 		@{$code_order} = split(/\&/,&unescape($value));
 8814: 	    } else {
 8815: 		$returnhash->{&unescape($name)}=&unescape($value);
 8816: 	    }
 8817: 	}
 8818: 	return 'ok';
 8819:     }
 8820: 
 8821:     return $response;
 8822: }
 8823: 
 8824: sub auto_possible_instcodes {
 8825:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8826:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8827:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8828:         return;
 8829:     }
 8830:     my (@homeservers,$uhome);
 8831:     if (defined(&domain($domain,'primary'))) {
 8832:         $uhome=&domain($domain,'primary');
 8833:         push(@homeservers,&domain($domain,'primary'));
 8834:     } else {
 8835:         my %servers = &get_servers($domain,'library');
 8836:         foreach my $tryserver (keys(%servers)) {
 8837:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8838:                 push(@homeservers,$tryserver);
 8839:             }
 8840:         }
 8841:     }
 8842:     my $response;
 8843:     foreach my $server (@homeservers) {
 8844:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8845:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8846:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8847:             split(':',$response);
 8848:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8849:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8850:         foreach my $item (split('&',$cat_title)) {   
 8851:             my ($name,$value)=split('=',$item);
 8852:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8853:         }
 8854:         foreach my $item (split('&',$cat_order)) {
 8855:             my ($name,$value)=split('=',$item);
 8856:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8857:         }
 8858:         return 'ok';
 8859:     }
 8860:     return $response;
 8861: }
 8862: 
 8863: sub auto_courserequest_checks {
 8864:     my ($dom) = @_;
 8865:     my ($homeserver,%validations);
 8866:     if ($dom =~ /^$match_domain$/) {
 8867:         $homeserver = &domain($dom,'primary');
 8868:     }
 8869:     unless ($homeserver eq 'no_host') {
 8870:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8871:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8872:             my @items = split(/&/,$response);
 8873:             foreach my $item (@items) {
 8874:                 my ($key,$value) = split('=',$item);
 8875:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8876:             }
 8877:         }
 8878:     }
 8879:     return %validations; 
 8880: }
 8881: 
 8882: sub auto_courserequest_validation {
 8883:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8884:     my ($homeserver,$response);
 8885:     if ($dom =~ /^$match_domain$/) {
 8886:         $homeserver = &domain($dom,'primary');
 8887:     }
 8888:     unless ($homeserver eq 'no_host') {
 8889:         my $customdata;
 8890:         if (ref($custominfo) eq 'HASH') {
 8891:             $customdata = &freeze_escape($custominfo);
 8892:         }
 8893:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8894:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8895:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8896:                                     $customdata,$homeserver));
 8897:     }
 8898:     return $response;
 8899: }
 8900: 
 8901: sub auto_validate_class_sec {
 8902:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8903:     my $homeserver = &homeserver($cnum,$cdom);
 8904:     my $ownerlist;
 8905:     if (ref($owners) eq 'ARRAY') {
 8906:         $ownerlist = join(',',@{$owners});
 8907:     } else {
 8908:         $ownerlist = $owners;
 8909:     }
 8910:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8911:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8912:     return $response;
 8913: }
 8914: 
 8915: sub auto_validate_instclasses {
 8916:     my ($cdom,$cnum,$owners,$classesref) = @_;
 8917:     my ($homeserver,%validations);
 8918:     $homeserver = &homeserver($cnum,$cdom);
 8919:     unless ($homeserver eq 'no_host') {
 8920:         my $ownerlist;
 8921:         if (ref($owners) eq 'ARRAY') {
 8922:             $ownerlist = join(',',@{$owners});
 8923:         } else {
 8924:             $ownerlist = $owners;
 8925:         }
 8926:         if (ref($classesref) eq 'HASH') {
 8927:             my $classes = &freeze_escape($classesref);
 8928:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 8929:                                 ':'.$cdom.':'.$classes,$homeserver);
 8930:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8931:                 my @items = split(/&/,$response);
 8932:                 foreach my $item (@items) {
 8933:                     my ($key,$value) = split('=',$item);
 8934:                     $validations{&unescape($key)} = &thaw_unescape($value);
 8935:                 }
 8936:             }
 8937:         }
 8938:     }
 8939:     return %validations;
 8940: }
 8941: 
 8942: sub auto_crsreq_update {
 8943:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8944:         $code,$accessstart,$accessend,$inbound) = @_;
 8945:     my ($homeserver,%crsreqresponse);
 8946:     if ($cdom =~ /^$match_domain$/) {
 8947:         $homeserver = &domain($cdom,'primary');
 8948:     }
 8949:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8950:         my $info;
 8951:         if (ref($inbound) eq 'HASH') {
 8952:             $info = &freeze_escape($inbound);
 8953:         }
 8954:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8955:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8956:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8957:                             &escape($title).':'.&escape($code).':'.
 8958:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8959:                             $homeserver);
 8960:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8961:             my @items = split(/&/,$response);
 8962:             foreach my $item (@items) {
 8963:                 my ($key,$value) = split('=',$item);
 8964:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8965:             }
 8966:         }
 8967:     }
 8968:     return \%crsreqresponse;
 8969: }
 8970: 
 8971: sub auto_export_grades {
 8972:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 8973:     my ($homeserver,%exportresponse);
 8974:     if ($cdom =~ /^$match_domain$/) {
 8975:         $homeserver = &domain($cdom,'primary');
 8976:     }
 8977:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8978:         my $info;
 8979:         if (ref($inforef) eq 'HASH') {
 8980:             $info = &freeze_escape($inforef);
 8981:         }
 8982:         if (ref($gradesref) eq 'HASH') {
 8983:             my $grades = &freeze_escape($gradesref);
 8984:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 8985:                                 $info.':'.$grades,$homeserver);
 8986:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 8987:                 my @items = split(/&/,$response);
 8988:                 foreach my $item (@items) {
 8989:                     my ($key,$value) = split('=',$item);
 8990:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 8991:                 }
 8992:             }
 8993:         }
 8994:     }
 8995:     return \%exportresponse;
 8996: }
 8997: 
 8998: sub check_instcode_cloning {
 8999:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9000:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9001:         return;
 9002:     }
 9003:     my $canclone;
 9004:     if (@{$code_order} > 0) {
 9005:         my $instcoderegexp ='^';
 9006:         my @clonecodes = split(/\&/,$cloner);
 9007:         foreach my $item (@{$code_order}) {
 9008:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9009:                 foreach my $pair (@clonecodes) {
 9010:                     my ($key,$val) = split(/\=/,$pair,2);
 9011:                     $val = &unescape($val);
 9012:                     if ($key eq $item) {
 9013:                         $instcoderegexp .= '('.$val.')';
 9014:                         last;
 9015:                     }
 9016:                 }
 9017:             } else {
 9018:                 $instcoderegexp .= $codedefaults->{$item};
 9019:             }
 9020:         }
 9021:         $instcoderegexp .= '$';
 9022:         my (@from,@to);
 9023:         eval {
 9024:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9025:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9026:         };
 9027:         if ((@from > 0) && (@to > 0)) {
 9028:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9029:             if (!@diffs) {
 9030:                 $canclone = 1;
 9031:             }
 9032:         }
 9033:     }
 9034:     return $canclone;
 9035: }
 9036: 
 9037: sub default_instcode_cloning {
 9038:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9039:     my (%codedefaults,@code_order,$canclone);
 9040:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9041:         %codedefaults = %{$codedefaultsref};
 9042:         @code_order = @{$codeorderref};
 9043:     } elsif ($clonedom) {
 9044:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9045:     }
 9046:     if (($domdefclone) && (@code_order)) {
 9047:         my @clonecodes = split(/\+/,$domdefclone);
 9048:         my $instcoderegexp ='^';
 9049:         foreach my $item (@code_order) {
 9050:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9051:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9052:             } else {
 9053:                 $instcoderegexp .= $codedefaults{$item};
 9054:             }
 9055:         }
 9056:         $instcoderegexp .= '$';
 9057:         my (@from,@to);
 9058:         eval {
 9059:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9060:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9061:         };
 9062:         if ((@from > 0) && (@to > 0)) {
 9063:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9064:             if (!@diffs) {
 9065:                 $canclone = 1;
 9066:             }
 9067:         }
 9068:     }
 9069:     return $canclone;
 9070: }
 9071: 
 9072: # ------------------------------------------------------- Course Group routines
 9073: 
 9074: sub get_coursegroups {
 9075:     my ($cdom,$cnum,$group,$namespace) = @_;
 9076:     return(&dump($namespace,$cdom,$cnum,$group));
 9077: }
 9078: 
 9079: sub modify_coursegroup {
 9080:     my ($cdom,$cnum,$groupsettings) = @_;
 9081:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9082: }
 9083: 
 9084: sub toggle_coursegroup_status {
 9085:     my ($cdom,$cnum,$group,$action) = @_;
 9086:     my ($from_namespace,$to_namespace);
 9087:     if ($action eq 'delete') {
 9088:         $from_namespace = 'coursegroups';
 9089:         $to_namespace = 'deleted_groups';
 9090:     } else {
 9091:         $from_namespace = 'deleted_groups';
 9092:         $to_namespace = 'coursegroups';
 9093:     }
 9094:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9095:     if (my $tmp = &error(%curr_group)) {
 9096:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9097:         return ('read error',$tmp);
 9098:     } else {
 9099:         my %savedsettings = %curr_group; 
 9100:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9101:         my $deloutcome;
 9102:         if ($result eq 'ok') {
 9103:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9104:         } else {
 9105:             return ('write error',$result);
 9106:         }
 9107:         if ($deloutcome eq 'ok') {
 9108:             return 'ok';
 9109:         } else {
 9110:             return ('delete error',$deloutcome);
 9111:         }
 9112:     }
 9113: }
 9114: 
 9115: sub modify_group_roles {
 9116:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9117:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9118:     my $role = 'gr/'.&escape($userprivs);
 9119:     my ($uname,$udom) = split(/:/,$user);
 9120:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9121:     if ($result eq 'ok') {
 9122:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9123:     }
 9124:     return $result;
 9125: }
 9126: 
 9127: sub modify_coursegroup_membership {
 9128:     my ($cdom,$cnum,$membership) = @_;
 9129:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9130:     return $result;
 9131: }
 9132: 
 9133: sub get_active_groups {
 9134:     my ($udom,$uname,$cdom,$cnum) = @_;
 9135:     my $now = time;
 9136:     my %groups = ();
 9137:     foreach my $key (keys(%env)) {
 9138:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9139:             my ($start,$end) = split(/\./,$env{$key});
 9140:             if (($end!=0) && ($end<$now)) { next; }
 9141:             if (($start!=0) && ($start>$now)) { next; }
 9142:             if ($1 eq $cdom && $2 eq $cnum) {
 9143:                 $groups{$3} = $env{$key} ;
 9144:             }
 9145:         }
 9146:     }
 9147:     return %groups;
 9148: }
 9149: 
 9150: sub get_group_membership {
 9151:     my ($cdom,$cnum,$group) = @_;
 9152:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9153: }
 9154: 
 9155: sub get_users_groups {
 9156:     my ($udom,$uname,$courseid) = @_;
 9157:     my @usersgroups;
 9158:     my $cachetime=1800;
 9159: 
 9160:     my $hashid="$udom:$uname:$courseid";
 9161:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9162:     if (defined($cached)) {
 9163:         @usersgroups = split(/:/,$grouplist);
 9164:     } else {  
 9165:         $grouplist = '';
 9166:         my $courseurl = &courseid_to_courseurl($courseid);
 9167:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9168:         my $access_end = $env{'course.'.$courseid.
 9169:                               '.default_enrollment_end_date'};
 9170:         my $now = time;
 9171:         foreach my $key (keys(%roleshash)) {
 9172:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9173:                 my $group = $1;
 9174:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9175:                     my $start = $2;
 9176:                     my $end = $1;
 9177:                     if ($start == -1) { next; } # deleted from group
 9178:                     if (($start!=0) && ($start>$now)) { next; }
 9179:                     if (($end!=0) && ($end<$now)) {
 9180:                         if ($access_end && $access_end < $now) {
 9181:                             if ($access_end - $end < 86400) {
 9182:                                 push(@usersgroups,$group);
 9183:                             }
 9184:                         }
 9185:                         next;
 9186:                     }
 9187:                     push(@usersgroups,$group);
 9188:                 }
 9189:             }
 9190:         }
 9191:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9192:         $grouplist = join(':',@usersgroups);
 9193:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9194:     }
 9195:     return @usersgroups;
 9196: }
 9197: 
 9198: sub devalidate_getgroups_cache {
 9199:     my ($udom,$uname,$cdom,$cnum)=@_;
 9200:     my $courseid = $cdom.'_'.$cnum;
 9201: 
 9202:     my $hashid="$udom:$uname:$courseid";
 9203:     &devalidate_cache_new('getgroups',$hashid);
 9204: }
 9205: 
 9206: # ------------------------------------------------------------------ Plain Text
 9207: 
 9208: sub plaintext {
 9209:     my ($short,$type,$cid,$forcedefault) = @_;
 9210:     if ($short =~ m{^cr/}) {
 9211: 	return (split('/',$short))[-1];
 9212:     }
 9213:     if (!defined($cid)) {
 9214:         $cid = $env{'request.course.id'};
 9215:     }
 9216:     my %rolenames = (
 9217:                       Course    => 'std',
 9218:                       Community => 'alt1',
 9219:                       Placement => 'std',
 9220:                     );
 9221:     if ($cid ne '') {
 9222:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9223:             unless ($forcedefault) {
 9224:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9225:                 &Apache::lonlocal::mt_escape(\$roletext);
 9226:                 return &Apache::lonlocal::mt($roletext);
 9227:             }
 9228:         }
 9229:     }
 9230:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9231:         (defined($rolenames{$type})) && 
 9232:         (defined($prp{$short}{$rolenames{$type}}))) {
 9233:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9234:     } elsif ($cid ne '') {
 9235:         my $crstype = $env{'course.'.$cid.'.type'};
 9236:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9237:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9238:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9239:         }
 9240:     }
 9241:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9242: }
 9243: 
 9244: # ----------------------------------------------------------------- Assign Role
 9245: 
 9246: sub assignrole {
 9247:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9248:         $context)=@_;
 9249:     my $mrole;
 9250:     if ($role =~ /^cr\//) {
 9251:         my $cwosec=$url;
 9252:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9253: 	unless (&allowed('ccr',$cwosec)) {
 9254:            my $refused = 1;
 9255:            if ($context eq 'requestcourses') {
 9256:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9257:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9258:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9259:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9260:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9261:                            if ($crsenv{'internal.courseowner'} eq
 9262:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9263:                                $refused = '';
 9264:                            }
 9265:                        }
 9266:                    }
 9267:                }
 9268:            }
 9269:            if ($refused) {
 9270:                &logthis('Refused custom assignrole: '.
 9271:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9272:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9273:                return 'refused';
 9274:            }
 9275:         }
 9276:         $mrole='cr';
 9277:     } elsif ($role =~ /^gr\//) {
 9278:         my $cwogrp=$url;
 9279:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9280:         unless (&allowed('mdg',$cwogrp)) {
 9281:             &logthis('Refused group assignrole: '.
 9282:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9283:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9284:             return 'refused';
 9285:         }
 9286:         $mrole='gr';
 9287:     } else {
 9288:         my $cwosec=$url;
 9289:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9290:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9291:             my $refused;
 9292:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9293:                 if (!(&allowed('c'.$role,$url))) {
 9294:                     $refused = 1;
 9295:                 }
 9296:             } else {
 9297:                 $refused = 1;
 9298:             }
 9299:             if ($refused) {
 9300:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9301:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9302:                     my %crsenv;
 9303:                     if ($role eq 'cc' || $role eq 'co') {
 9304:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9305:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9306:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9307:                                 if ($crsenv{'internal.courseowner'} eq 
 9308:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9309:                                     $refused = '';
 9310:                                 }
 9311:                             }
 9312:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9313:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9314:                                 if ($crsenv{'internal.courseowner'} eq 
 9315:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9316:                                     $refused = '';
 9317:                                 }
 9318:                             }
 9319:                         }
 9320:                     }
 9321:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9322:                     if ($role eq 'st') {
 9323:                         $refused = '';
 9324:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9325:                         $refused = '';
 9326:                     }
 9327:                 } elsif ($context eq 'requestcourses') {
 9328:                     my @possroles = ('st','ta','ep','in','cc','co');
 9329:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9330:                         my $wrongcc;
 9331:                         if ($cnum =~ /^$match_community$/) {
 9332:                             $wrongcc = 1 if ($role eq 'cc');
 9333:                         } else {
 9334:                             $wrongcc = 1 if ($role eq 'co');
 9335:                         }
 9336:                         unless ($wrongcc) {
 9337:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9338:                             if ($crsenv{'internal.courseowner'} eq 
 9339:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9340:                                 $refused = '';
 9341:                             }
 9342:                         }
 9343:                     }
 9344:                 } elsif ($context eq 'requestauthor') {
 9345:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9346:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9347:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9348:                             $refused = '';
 9349:                         } else {
 9350:                             my %domdefaults = &get_domain_defaults($udom);
 9351:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9352:                                 my $checkbystatus;
 9353:                                 if ($env{'user.adv'}) { 
 9354:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9355:                                     if ($disposition eq 'automatic') {
 9356:                                         $refused = '';
 9357:                                     } elsif ($disposition eq '') {
 9358:                                         $checkbystatus = 1;
 9359:                                     } 
 9360:                                 } else {
 9361:                                     $checkbystatus = 1;
 9362:                                 }
 9363:                                 if ($checkbystatus) {
 9364:                                     if ($env{'environment.inststatus'}) {
 9365:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9366:                                         foreach my $type (@inststatuses) {
 9367:                                             if (($type ne '') &&
 9368:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9369:                                                 $refused = '';
 9370:                                             }
 9371:                                         }
 9372:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9373:                                         $refused = '';
 9374:                                     }
 9375:                                 }
 9376:                             }
 9377:                         }
 9378:                     }
 9379:                 }
 9380:                 if ($refused) {
 9381:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9382:                              ' '.$role.' '.$end.' '.$start.' by '.
 9383: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9384:                     return 'refused';
 9385:                 }
 9386:             }
 9387:         } elsif ($role eq 'au') {
 9388:             if ($url ne '/'.$udom.'/') {
 9389:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9390:                          ' to assign author role for '.$uname.':'.$udom.
 9391:                          ' in domain: '.$url.' refused (wrong domain).');
 9392:                 return 'refused';
 9393:             }
 9394:         }
 9395:         $mrole=$role;
 9396:     }
 9397:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9398:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9399:     if ($end) { $command.='_'.$end; }
 9400:     if ($start) {
 9401: 	if ($end) { 
 9402:            $command.='_'.$start; 
 9403:         } else {
 9404:            $command.='_0_'.$start;
 9405:         }
 9406:     }
 9407:     my $origstart = $start;
 9408:     my $origend = $end;
 9409:     my $delflag;
 9410: # actually delete
 9411:     if ($deleteflag) {
 9412: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9413: # modify command to delete the role
 9414:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9415:                 "$udom:$uname:$url".'_'."$mrole";
 9416: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9417: # set start and finish to negative values for userrolelog
 9418:            $start=-1;
 9419:            $end=-1;
 9420:            $delflag = 1;
 9421:         }
 9422:     }
 9423: # send command
 9424:     my $answer=&reply($command,&homeserver($uname,$udom));
 9425: # log new user role if status is ok
 9426:     if ($answer eq 'ok') {
 9427: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9428:         if (($role eq 'cc') || ($role eq 'in') ||
 9429:             ($role eq 'ep') || ($role eq 'ad') ||
 9430:             ($role eq 'ta') || ($role eq 'st') ||
 9431:             ($role=~/^cr/) || ($role eq 'gr') ||
 9432:             ($role eq 'co')) {
 9433: # for course roles, perform group memberships changes triggered by role change.
 9434:             unless ($role =~ /^gr/) {
 9435:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9436:                                                  $origstart,$selfenroll,$context);
 9437:             }
 9438:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9439:                            $selfenroll,$context);
 9440:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9441:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9442:                  ($role eq 'da')) {
 9443:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9444:                            $context);
 9445:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9446:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9447:                              $context); 
 9448:         }
 9449:         if ($role eq 'cc') {
 9450:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9451:         }
 9452:     }
 9453:     return $answer;
 9454: }
 9455: 
 9456: sub autoupdate_coowners {
 9457:     my ($url,$end,$start,$uname,$udom) = @_;
 9458:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9459:     if (($cdom ne '') && ($cnum ne '')) {
 9460:         my $now = time;
 9461:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9462:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9463:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9464:             my $instcode = $coursehash{'internal.coursecode'};
 9465:             if ($instcode ne '') {
 9466:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9467:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9468:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9469:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9470:                         if ($result eq 'valid') {
 9471:                             if ($coursehash{'internal.co-owners'}) {
 9472:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9473:                                     push(@newcoowners,$coowner);
 9474:                                 }
 9475:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9476:                                     push(@newcoowners,$uname.':'.$udom);
 9477:                                 }
 9478:                                 @newcoowners = sort(@newcoowners);
 9479:                             } else {
 9480:                                 push(@newcoowners,$uname.':'.$udom);
 9481:                             }
 9482:                         } else {
 9483:                             if ($coursehash{'internal.co-owners'}) {
 9484:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9485:                                     unless ($coowner eq $uname.':'.$udom) {
 9486:                                         push(@newcoowners,$coowner);
 9487:                                     }
 9488:                                 }
 9489:                                 unless (@newcoowners > 0) {
 9490:                                     $delcoowners = 1;
 9491:                                     $coowners = '';
 9492:                                 }
 9493:                             }
 9494:                         }
 9495:                         if (@newcoowners || $delcoowners) {
 9496:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9497:                                             $delcoowners,@newcoowners);
 9498:                         }
 9499:                     }
 9500:                 }
 9501:             }
 9502:         }
 9503:     }
 9504: }
 9505: 
 9506: sub store_coowners {
 9507:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9508:     my $cid = $cdom.'_'.$cnum;
 9509:     my ($coowners,$delresult,$putresult);
 9510:     if (@newcoowners) {
 9511:         $coowners = join(',',@newcoowners);
 9512:         my %coownershash = (
 9513:                             'internal.co-owners' => $coowners,
 9514:                            );
 9515:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9516:         if ($putresult eq 'ok') {
 9517:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9518:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9519:             }
 9520:         }
 9521:     }
 9522:     if ($delcoowners) {
 9523:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9524:         if ($delresult eq 'ok') {
 9525:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9526:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9527:             }
 9528:         }
 9529:     }
 9530:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9531:         my %crsinfo =
 9532:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9533:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9534:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9535:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9536:         }
 9537:     }
 9538: }
 9539: 
 9540: # -------------------------------------------------- Modify user authentication
 9541: # Overrides without validation
 9542: 
 9543: sub modifyuserauth {
 9544:     my ($udom,$uname,$umode,$upass)=@_;
 9545:     my $uhome=&homeserver($uname,$udom);
 9546:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9547:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9548:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9549:              ' in domain '.$env{'request.role.domain'});  
 9550:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9551: 		     &escape($upass),$uhome);
 9552:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9553:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9554:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9555:     &log($udom,,$uname,$uhome,
 9556:         'Authentication changed by '.$env{'user.domain'}.', '.
 9557:                                      $env{'user.name'}.', '.$umode.
 9558:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9559:     unless ($reply eq 'ok') {
 9560:         &logthis('Authentication mode error: '.$reply);
 9561: 	return 'error: '.$reply;
 9562:     }   
 9563:     return 'ok';
 9564: }
 9565: 
 9566: # --------------------------------------------------------------- Modify a user
 9567: 
 9568: sub modifyuser {
 9569:     my ($udom,    $uname, $uid,
 9570:         $umode,   $upass, $first,
 9571:         $middle,  $last,  $gene,
 9572:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9573:     $udom= &LONCAPA::clean_domain($udom);
 9574:     $uname=&LONCAPA::clean_username($uname);
 9575:     my $showcandelete = 'none';
 9576:     if (ref($candelete) eq 'ARRAY') {
 9577:         if (@{$candelete} > 0) {
 9578:             $showcandelete = join(', ',@{$candelete});
 9579:         }
 9580:     }
 9581:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9582:              $umode.', '.$first.', '.$middle.', '.
 9583: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9584:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9585:                                      ' desiredhome not specified'). 
 9586:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9587:              ' in domain '.$env{'request.role.domain'});
 9588:     my $uhome=&homeserver($uname,$udom,'true');
 9589:     my $newuser;
 9590:     if ($uhome eq 'no_host') {
 9591:         $newuser = 1;
 9592:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
 9593:                 ($umode eq 'lti')) {
 9594:             return 'error: more information needed to create new user';
 9595:         }
 9596:     }
 9597: # ----------------------------------------------------------------- Create User
 9598:     if (($uhome eq 'no_host') && 
 9599: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
 9600:         my $unhome='';
 9601:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9602:             $unhome = $desiredhome;
 9603: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9604: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9605:         } else { # load balancing routine for determining $unhome
 9606:             my $loadm=10000000;
 9607: 	    my %servers = &get_servers($udom,'library');
 9608: 	    foreach my $tryserver (keys(%servers)) {
 9609: 		my $answer=reply('load',$tryserver);
 9610: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9611: 		    $loadm=$answer;
 9612: 		    $unhome=$tryserver;
 9613: 		}
 9614: 	    }
 9615:         }
 9616:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9617: 	    return 'error: unable to find a home server for '.$uname.
 9618:                    ' in domain '.$udom;
 9619:         }
 9620:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9621:                          &escape($upass),$unhome);
 9622: 	unless ($reply eq 'ok') {
 9623:             return 'error: '.$reply;
 9624:         }   
 9625:         $uhome=&homeserver($uname,$udom,'true');
 9626:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9627: 	    return 'error: unable verify users home machine.';
 9628:         }
 9629:     }   # End of creation of new user
 9630: # ---------------------------------------------------------------------- Add ID
 9631:     if ($uid) {
 9632:        $uid=~tr/A-Z/a-z/;
 9633:        my %uidhash=&idrget($udom,$uname);
 9634:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9635:          && (!$forceid)) {
 9636: 	  unless ($uid eq $uidhash{$uname}) {
 9637: 	      return 'error: user id "'.$uid.'" does not match '.
 9638:                   'current user id "'.$uidhash{$uname}.'".';
 9639:           }
 9640:        } else {
 9641: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9642:        }
 9643:     }
 9644: # -------------------------------------------------------------- Add names, etc
 9645:     my @tmp=&get('environment',
 9646: 		   ['firstname','middlename','lastname','generation','id',
 9647:                     'permanentemail','inststatus'],
 9648: 		   $udom,$uname);
 9649:     my (%names,%oldnames);
 9650:     if ($tmp[0] =~ m/^error:.*/) { 
 9651:         %names=(); 
 9652:     } else {
 9653:         %names = @tmp;
 9654:         %oldnames = %names;
 9655:     }
 9656: #
 9657: # If name, email and/or uid are blank (e.g., because an uploaded file
 9658: # of users did not contain them), do not overwrite existing values
 9659: # unless field is in $candelete array ref.  
 9660: #
 9661: 
 9662:     my @fields = ('firstname','middlename','lastname','generation',
 9663:                   'permanentemail','id');
 9664:     my %newvalues;
 9665:     if (ref($candelete) eq 'ARRAY') {
 9666:         foreach my $field (@fields) {
 9667:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9668:                 if ($field eq 'firstname') {
 9669:                     $names{$field} = $first;
 9670:                 } elsif ($field eq 'middlename') {
 9671:                     $names{$field} = $middle;
 9672:                 } elsif ($field eq 'lastname') {
 9673:                     $names{$field} = $last;
 9674:                 } elsif ($field eq 'generation') { 
 9675:                     $names{$field} = $gene;
 9676:                 } elsif ($field eq 'permanentemail') {
 9677:                     $names{$field} = $email;
 9678:                 } elsif ($field eq 'id') {
 9679:                     $names{$field}  = $uid;
 9680:                 }
 9681:             }
 9682:         }
 9683:     }
 9684:     if ($first)  { $names{'firstname'}  = $first; }
 9685:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9686:     if ($last)   { $names{'lastname'}   = $last; }
 9687:     if (defined($gene))   { $names{'generation'} = $gene; }
 9688:     if ($email) {
 9689:        $email=~s/[^\w\@\.\-\,]//gs;
 9690:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9691:     }
 9692:     if ($uid) { $names{'id'}  = $uid; }
 9693:     if (defined($inststatus)) {
 9694:         $names{'inststatus'} = '';
 9695:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9696:         if (ref($usertypes) eq 'HASH') {
 9697:             my @okstatuses; 
 9698:             foreach my $item (split(/:/,$inststatus)) {
 9699:                 if (defined($usertypes->{$item})) {
 9700:                     push(@okstatuses,$item);  
 9701:                 }
 9702:             }
 9703:             if (@okstatuses) {
 9704:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9705:             }
 9706:         }
 9707:     }
 9708:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9709:                  $umode.', '.$first.', '.$middle.', '.
 9710:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9711:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9712:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9713:     } else {
 9714:         $logmsg .= ' during self creation';
 9715:     }
 9716:     my $changed;
 9717:     if ($newuser) {
 9718:         $changed = 1;
 9719:     } else {
 9720:         foreach my $field (@fields) {
 9721:             if ($names{$field} ne $oldnames{$field}) {
 9722:                 $changed = 1;
 9723:                 last;
 9724:             }
 9725:         }
 9726:     }
 9727:     unless ($changed) {
 9728:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9729:         &logthis($logmsg);
 9730:         return 'ok';
 9731:     }
 9732:     my $reply = &put('environment', \%names, $udom,$uname);
 9733:     if ($reply ne 'ok') { 
 9734:         return 'error: '.$reply;
 9735:     }
 9736:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9737:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9738:     }
 9739:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9740:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9741:     $logmsg = 'Success modifying user '.$logmsg;
 9742:     &logthis($logmsg);
 9743:     return 'ok';
 9744: }
 9745: 
 9746: # -------------------------------------------------------------- Modify student
 9747: 
 9748: sub modifystudent {
 9749:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9750:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9751:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9752:     if (!$cid) {
 9753: 	unless ($cid=$env{'request.course.id'}) {
 9754: 	    return 'not_in_class';
 9755: 	}
 9756:     }
 9757: # --------------------------------------------------------------- Make the user
 9758:     my $reply=&modifyuser
 9759: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9760:          $desiredhome,$email,$inststatus);
 9761:     unless ($reply eq 'ok') { return $reply; }
 9762:     # This will cause &modify_student_enrollment to get the uid from the
 9763:     # student's environment
 9764:     $uid = undef if (!$forceid);
 9765:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9766:                                         $gene,$usec,$end,$start,$type,$locktype,
 9767:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9768:     return $reply;
 9769: }
 9770: 
 9771: sub modify_student_enrollment {
 9772:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9773:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9774:     my ($cdom,$cnum,$chome);
 9775:     if (!$cid) {
 9776: 	unless ($cid=$env{'request.course.id'}) {
 9777: 	    return 'not_in_class';
 9778: 	}
 9779: 	$cdom=$env{'course.'.$cid.'.domain'};
 9780: 	$cnum=$env{'course.'.$cid.'.num'};
 9781:     } else {
 9782: 	($cdom,$cnum)=split(/_/,$cid);
 9783:     }
 9784:     $chome=$env{'course.'.$cid.'.home'};
 9785:     if (!$chome) {
 9786: 	$chome=&homeserver($cnum,$cdom);
 9787:     }
 9788:     if (!$chome) { return 'unknown_course'; }
 9789:     # Make sure the user exists
 9790:     my $uhome=&homeserver($uname,$udom);
 9791:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9792: 	return 'error: no such user';
 9793:     }
 9794:     # Get student data if we were not given enough information
 9795:     if (!defined($first)  || $first  eq '' || 
 9796:         !defined($last)   || $last   eq '' || 
 9797:         !defined($uid)    || $uid    eq '' || 
 9798:         !defined($middle) || $middle eq '' || 
 9799:         !defined($gene)   || $gene   eq '') {
 9800:         # They did not supply us with enough data to enroll the student, so
 9801:         # we need to pick up more information.
 9802:         my %tmp = &get('environment',
 9803:                        ['firstname','middlename','lastname', 'generation','id']
 9804:                        ,$udom,$uname);
 9805: 
 9806:         #foreach my $key (keys(%tmp)) {
 9807:         #    &logthis("key $key = ".$tmp{$key});
 9808:         #}
 9809:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9810:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9811:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9812:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9813:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9814:     }
 9815:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9816:     my $user = "$uname:$udom";
 9817:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9818:     my $reply=cput('classlist',
 9819: 		   {$user => 
 9820: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9821: 		   $cdom,$cnum);
 9822:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9823:         &devalidate_getsection_cache($udom,$uname,$cid);
 9824:     } else { 
 9825: 	return 'error: '.$reply;
 9826:     }
 9827:     # Add student role to user
 9828:     my $uurl='/'.$cid;
 9829:     $uurl=~s/\_/\//g;
 9830:     if ($usec) {
 9831: 	$uurl.='/'.$usec;
 9832:     }
 9833:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9834:                              $selfenroll,$context);
 9835:     if ($result ne 'ok') {
 9836:         if ($old_entry{$user} ne '') {
 9837:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9838:         } else {
 9839:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9840:         }
 9841:     }
 9842:     return $result; 
 9843: }
 9844: 
 9845: sub format_name {
 9846:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9847:     my $name;
 9848:     if ($first ne 'lastname') {
 9849: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9850:     } else {
 9851: 	if ($lastname=~/\S/) {
 9852: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9853: 	    $name=~s/\s+,/,/;
 9854: 	} else {
 9855: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9856: 	}
 9857:     }
 9858:     $name=~s/^\s+//;
 9859:     $name=~s/\s+$//;
 9860:     $name=~s/\s+/ /g;
 9861:     return $name;
 9862: }
 9863: 
 9864: # ------------------------------------------------- Write to course preferences
 9865: 
 9866: sub writecoursepref {
 9867:     my ($courseid,%prefs)=@_;
 9868:     $courseid=~s/^\///;
 9869:     $courseid=~s/\_/\//g;
 9870:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9871:     my $chome=homeserver($cnum,$cdomain);
 9872:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9873: 	return 'error: no such course';
 9874:     }
 9875:     my $cstring='';
 9876:     foreach my $pref (keys(%prefs)) {
 9877: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9878:     }
 9879:     $cstring=~s/\&$//;
 9880:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9881: }
 9882: 
 9883: # ---------------------------------------------------------- Make/modify course
 9884: 
 9885: sub createcourse {
 9886:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9887:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9888:     $url=&declutter($url);
 9889:     my $cid='';
 9890:     if ($context eq 'requestcourses') {
 9891:         my $can_create = 0;
 9892:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9893:         if ($udom eq $ownerdom) {
 9894:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9895:                                   $context)) {
 9896:                 $can_create = 1;
 9897:             }
 9898:         } else {
 9899:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9900:                                            $category);
 9901:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9902:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9903:                 if (@curr > 0) {
 9904:                     my @options = qw(approval validate autolimit);
 9905:                     my $optregex = join('|',@options);
 9906:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9907:                         $can_create = 1;
 9908:                     }
 9909:                 }
 9910:             }
 9911:         }
 9912:         if ($can_create) {
 9913:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 9914:                 unless (&allowed('ccc',$udom)) {
 9915:                     return 'refused'; 
 9916:                 }
 9917:             }
 9918:         } else {
 9919:             return 'refused';
 9920:         }
 9921:     } elsif (!&allowed('ccc',$udom)) {
 9922:         return 'refused';
 9923:     }
 9924: # --------------------------------------------------------------- Get Unique ID
 9925:     my $uname;
 9926:     if ($cnum =~ /^$match_courseid$/) {
 9927:         my $chome=&homeserver($cnum,$udom,'true');
 9928:         if (($chome eq '') || ($chome eq 'no_host')) {
 9929:             $uname = $cnum;
 9930:         } else {
 9931:             $uname = &generate_coursenum($udom,$crstype);
 9932:         }
 9933:     } else {
 9934:         $uname = &generate_coursenum($udom,$crstype);
 9935:     }
 9936:     return $uname if ($uname =~ /^error/);
 9937: # -------------------------------------------------- Check supplied server name
 9938:     if (!defined($course_server)) {
 9939:         if (defined(&domain($udom,'primary'))) {
 9940:             $course_server = &domain($udom,'primary');
 9941:         } else {
 9942:             $course_server = $env{'user.home'}; 
 9943:         }
 9944:     }
 9945:     my %host_servers =
 9946:         &Apache::lonnet::get_servers($udom,'library');
 9947:     unless ($host_servers{$course_server}) {
 9948:         return 'error: invalid home server for course: '.$course_server;
 9949:     }
 9950: # ------------------------------------------------------------- Make the course
 9951:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 9952:                       $course_server);
 9953:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 9954:     my $uhome=&homeserver($uname,$udom,'true');
 9955:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9956: 	return 'error: no such course';
 9957:     }
 9958: # ----------------------------------------------------------------- Course made
 9959: # log existence
 9960:     my $now = time;
 9961:     my $newcourse = {
 9962:                     $udom.'_'.$uname => {
 9963:                                      description => $description,
 9964:                                      inst_code   => $inst_code,
 9965:                                      owner       => $course_owner,
 9966:                                      type        => $crstype,
 9967:                                      creator     => $env{'user.name'}.':'.
 9968:                                                     $env{'user.domain'},
 9969:                                      created     => $now,
 9970:                                      context     => $context,
 9971:                                                 },
 9972:                     };
 9973:     &courseidput($udom,$newcourse,$uhome,'notime');
 9974: # set toplevel url
 9975:     my $topurl=$url;
 9976:     unless ($nonstandard) {
 9977: # ------------------------------------------ For standard courses, make top url
 9978:         my $mapurl=&clutter($url);
 9979:         if ($mapurl eq '/res/') { $mapurl=''; }
 9980:         $env{'form.initmap'}=(<<ENDINITMAP);
 9981: <map>
 9982: <resource id="1" type="start"></resource>
 9983: <resource id="2" src="$mapurl"></resource>
 9984: <resource id="3" type="finish"></resource>
 9985: <link index="1" from="1" to="2"></link>
 9986: <link index="2" from="2" to="3"></link>
 9987: </map>
 9988: ENDINITMAP
 9989:         $topurl=&declutter(
 9990:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 9991:                           );
 9992:     }
 9993: # ----------------------------------------------------------- Write preferences
 9994:     &writecoursepref($udom.'_'.$uname,
 9995:                      ('description'              => $description,
 9996:                       'url'                      => $topurl,
 9997:                       'internal.creator'         => $env{'user.name'}.':'.
 9998:                                                     $env{'user.domain'},
 9999:                       'internal.created'         => $now,
10000:                       'internal.creationcontext' => $context)
10001:                     );
10002:     return '/'.$udom.'/'.$uname;
10003: }
10004: 
10005: # ------------------------------------------------------------------- Create ID
10006: sub generate_coursenum {
10007:     my ($udom,$crstype) = @_;
10008:     my $domdesc = &domain($udom);
10009:     return 'error: invalid domain' if ($domdesc eq '');
10010:     my $first;
10011:     if ($crstype eq 'Community') {
10012:         $first = '0';
10013:     } else {
10014:         $first = int(1+rand(9)); 
10015:     } 
10016:     my $uname=$first.
10017:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10018:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10019:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10020: # ----------------------------------------------- Make sure that does not exist
10021:     my $uhome=&homeserver($uname,$udom,'true');
10022:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10023:         if ($crstype eq 'Community') {
10024:             $first = '0';
10025:         } else {
10026:             $first = int(1+rand(9));
10027:         }
10028:         $uname=$first.
10029:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10030:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10031:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10032:         $uhome=&homeserver($uname,$udom,'true');
10033:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10034:             return 'error: unable to generate unique course-ID';
10035:         }
10036:     }
10037:     return $uname;
10038: }
10039: 
10040: sub is_course {
10041:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10042:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10043: 
10044:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10045:     my $uhome=&homeserver($cnum,$cdom);
10046:     my $iscourse;
10047:     if (grep { $_ eq $uhome } current_machine_ids()) {
10048:         $iscourse = &Lond::is_course($cdom,$cnum);
10049:     } else {
10050:         my $hashid = $cdom.':'.$cnum;
10051:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10052:         unless (defined($cached)) {
10053:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10054:                                         $cnum,undef,undef,'.');
10055:             $iscourse = 0;
10056:             if (exists($courses{$cdom.'_'.$cnum})) {
10057:                 $iscourse = 1;
10058:             }
10059:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10060:         }
10061:     }
10062:     return unless ($iscourse);
10063:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10064: }
10065: 
10066: sub store_userdata {
10067:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10068:     my $result;
10069:     if ($datakey ne '') {
10070:         if (ref($storehash) eq 'HASH') {
10071:             if ($udom eq '' || $uname eq '') {
10072:                 $udom = $env{'user.domain'};
10073:                 $uname = $env{'user.name'};
10074:             }
10075:             my $uhome=&homeserver($uname,$udom);
10076:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10077:                 $result = 'error: no_host';
10078:             } else {
10079:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10080:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10081: 
10082:                 my $namevalue='';
10083:                 foreach my $key (keys(%{$storehash})) {
10084:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10085:                 }
10086:                 $namevalue=~s/\&$//;
10087:                 unless ($namespace eq 'courserequests') {
10088:                     $datakey = &escape($datakey);
10089:                 }
10090:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10091:                                   $namevalue,$uhome);
10092:             }
10093:         } else {
10094:             $result = 'error: data to store was not a hash reference'; 
10095:         }
10096:     } else {
10097:         $result= 'error: invalid requestkey'; 
10098:     }
10099:     return $result;
10100: }
10101: 
10102: # ---------------------------------------------------------- Assign Custom Role
10103: 
10104: sub assigncustomrole {
10105:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10106:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10107:                        $end,$start,$deleteflag,$selfenroll,$context);
10108: }
10109: 
10110: # ----------------------------------------------------------------- Revoke Role
10111: 
10112: sub revokerole {
10113:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10114:     my $now=time;
10115:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10116: }
10117: 
10118: # ---------------------------------------------------------- Revoke Custom Role
10119: 
10120: sub revokecustomrole {
10121:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10122:     my $now=time;
10123:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10124:            $deleteflag,$selfenroll,$context);
10125: }
10126: 
10127: # ------------------------------------------------------------ Disk usage
10128: sub diskusage {
10129:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10130:     $directorypath =~ s/\/$//;
10131:     my $listing=&reply('du2:'.&escape($directorypath).':'
10132:                        .&escape($getpropath).':'.&escape($uname).':'
10133:                        .&escape($udom),homeserver($uname,$udom));
10134:     if ($listing eq 'unknown_cmd') {
10135:         if ($getpropath) {
10136:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10137:         }
10138:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10139:     }
10140:     return $listing;
10141: }
10142: 
10143: sub is_locked {
10144:     my ($file_name, $domain, $user, $which) = @_;
10145:     my @check;
10146:     my $is_locked;
10147:     push (@check,$file_name);
10148:     my %locked = &get('file_permissions',\@check,
10149: 		      $env{'user.domain'},$env{'user.name'});
10150:     my ($tmp)=keys(%locked);
10151:     if ($tmp=~/^error:/) { undef(%locked); }
10152:     
10153:     if (ref($locked{$file_name}) eq 'ARRAY') {
10154:         $is_locked = 'false';
10155:         foreach my $entry (@{$locked{$file_name}}) {
10156:            if (ref($entry) eq 'ARRAY') {
10157:                $is_locked = 'true';
10158:                if (ref($which) eq 'ARRAY') {
10159:                    push(@{$which},$entry);
10160:                } else {
10161:                    last;
10162:                }
10163:            }
10164:        }
10165:     } else {
10166:         $is_locked = 'false';
10167:     }
10168:     return $is_locked;
10169: }
10170: 
10171: sub declutter_portfile {
10172:     my ($file) = @_;
10173:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10174:     return $file;
10175: }
10176: 
10177: # ------------------------------------------------------------- Mark as Read Only
10178: 
10179: sub mark_as_readonly {
10180:     my ($domain,$user,$files,$what) = @_;
10181:     my %current_permissions = &dump('file_permissions',$domain,$user);
10182:     my ($tmp)=keys(%current_permissions);
10183:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10184:     foreach my $file (@{$files}) {
10185: 	$file = &declutter_portfile($file);
10186:         push(@{$current_permissions{$file}},$what);
10187:     }
10188:     &put('file_permissions',\%current_permissions,$domain,$user);
10189:     return;
10190: }
10191: 
10192: # ------------------------------------------------------------Save Selected Files
10193: 
10194: sub save_selected_files {
10195:     my ($user, $path, @files) = @_;
10196:     my $filename = $user."savedfiles";
10197:     my @other_files = &files_not_in_path($user, $path);
10198:     open (OUT,'>',LONCAPA::tempdir().$filename);
10199:     foreach my $file (@files) {
10200:         print (OUT $env{'form.currentpath'}.$file."\n");
10201:     }
10202:     foreach my $file (@other_files) {
10203:         print (OUT $file."\n");
10204:     }
10205:     close (OUT);
10206:     return 'ok';
10207: }
10208: 
10209: sub clear_selected_files {
10210:     my ($user) = @_;
10211:     my $filename = $user."savedfiles";
10212:     open (OUT,'>',LONCAPA::tempdir().$filename);
10213:     print (OUT undef);
10214:     close (OUT);
10215:     return ("ok");    
10216: }
10217: 
10218: sub files_in_path {
10219:     my ($user, $path) = @_;
10220:     my $filename = $user."savedfiles";
10221:     my %return_files;
10222:     open (IN,'<',LONCAPA::tempdir().$filename);
10223:     while (my $line_in = <IN>) {
10224:         chomp ($line_in);
10225:         my @paths_and_file = split (m!/!, $line_in);
10226:         my $file_part = pop (@paths_and_file);
10227:         my $path_part = join ('/', @paths_and_file);
10228:         $path_part.='/';
10229:         my $path_and_file = $path_part.$file_part;
10230:         if ($path_part eq $path) {
10231:             $return_files{$file_part}= 'selected';
10232:         }
10233:     }
10234:     close (IN);
10235:     return (\%return_files);
10236: }
10237: 
10238: # called in portfolio select mode, to show files selected NOT in current directory
10239: sub files_not_in_path {
10240:     my ($user, $path) = @_;
10241:     my $filename = $user."savedfiles";
10242:     my @return_files;
10243:     my $path_part;
10244:     open(IN, '<',LONCAPA::tempdir().$filename);
10245:     while (my $line = <IN>) {
10246:         #ok, I know it's clunky, but I want it to work
10247:         my @paths_and_file = split(m|/|, $line);
10248:         my $file_part = pop(@paths_and_file);
10249:         chomp($file_part);
10250:         my $path_part = join('/', @paths_and_file);
10251:         $path_part .= '/';
10252:         my $path_and_file = $path_part.$file_part;
10253:         if ($path_part ne $path) {
10254:             push(@return_files, ($path_and_file));
10255:         }
10256:     }
10257:     close(OUT);
10258:     return (@return_files);
10259: }
10260: 
10261: #------------------------------Submitted/Handedback Portfolio Files Versioning
10262:  
10263: sub portfiles_versioning {
10264:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10265:     my $portfolio_root = '/userfiles/portfolio';
10266:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10267:     foreach my $file (@{$portfiles}) {
10268:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10269:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10270:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10271:         my $getpropath = 1;
10272:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10273:                                              $stu_name,$getpropath);
10274:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10275:         my $new_answer = 
10276:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10277:         if ($new_answer ne 'problem getting file') {
10278:             push(@{$versioned_portfiles}, $directory.$new_answer);
10279:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10280:                               [$symb,$env{'request.course.id'},'graded']);
10281:         }
10282:     }
10283: }
10284: 
10285: sub get_next_version {
10286:     my ($answer_name, $answer_ext, $dir_list) = @_;
10287:     my $version;
10288:     if (ref($dir_list) eq 'ARRAY') {
10289:         foreach my $row (@{$dir_list}) {
10290:             my ($file) = split(/\&/,$row,2);
10291:             my ($file_name,$file_version,$file_ext) =
10292:                 &file_name_version_ext($file);
10293:             if (($file_name eq $answer_name) &&
10294:                 ($file_ext eq $answer_ext)) {
10295:                      # gets here if filename and extension match,
10296:                      # regardless of version
10297:                 if ($file_version ne '') {
10298:                     # a versioned file is found  so save it for later
10299:                     if ($file_version > $version) {
10300:                         $version = $file_version;
10301:                     }
10302:                 }
10303:             }
10304:         }
10305:     }
10306:     $version ++;
10307:     return($version);
10308: }
10309: 
10310: sub version_selected_portfile {
10311:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10312:     my ($answer_name,$answer_ver,$answer_ext) =
10313:         &file_name_version_ext($file_name);
10314:     my $new_answer;
10315:     $env{'form.copy'} =
10316:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10317:     if($env{'form.copy'} eq '-1') {
10318:         $new_answer = 'problem getting file';
10319:     } else {
10320:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10321:         my $copy_result = 
10322:             &finishuserfileupload($stu_name,$domain,'copy',
10323:                                   '/portfolio'.$directory.$new_answer);
10324:     }
10325:     undef($env{'form.copy'});
10326:     return ($new_answer);
10327: }
10328: 
10329: sub file_name_version_ext {
10330:     my ($file)=@_;
10331:     my @file_parts = split(/\./, $file);
10332:     my ($name,$version,$ext);
10333:     if (@file_parts > 1) {
10334:         $ext=pop(@file_parts);
10335:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10336:             $version=pop(@file_parts);
10337:         }
10338:         $name=join('.',@file_parts);
10339:     } else {
10340:         $name=join('.',@file_parts);
10341:     }
10342:     return($name,$version,$ext);
10343: }
10344: 
10345: #----------------------------------------------Get portfolio file permissions
10346: 
10347: sub get_portfile_permissions {
10348:     my ($domain,$user) = @_;
10349:     my %current_permissions = &dump('file_permissions',$domain,$user);
10350:     my ($tmp)=keys(%current_permissions);
10351:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10352:     return \%current_permissions;
10353: }
10354: 
10355: #---------------------------------------------Get portfolio file access controls
10356: 
10357: sub get_access_controls {
10358:     my ($current_permissions,$group,$file) = @_;
10359:     my %access;
10360:     my $real_file = $file;
10361:     $file =~ s/\.meta$//;
10362:     if (defined($file)) {
10363:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10364:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10365:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10366:             }
10367:         }
10368:     } else {
10369:         foreach my $key (keys(%{$current_permissions})) {
10370:             if ($key =~ /\0accesscontrol$/) {
10371:                 if (defined($group)) {
10372:                     if ($key !~ m-^\Q$group\E/-) {
10373:                         next;
10374:                     }
10375:                 }
10376:                 my ($fullpath) = split(/\0/,$key);
10377:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10378:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10379:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10380:                     }
10381:                 }
10382:             }
10383:         }
10384:     }
10385:     return %access;
10386: }
10387: 
10388: sub modify_access_controls {
10389:     my ($file_name,$changes,$domain,$user)=@_;
10390:     my ($outcome,$deloutcome);
10391:     my %store_permissions;
10392:     my %new_values;
10393:     my %new_control;
10394:     my %translation;
10395:     my @deletions = ();
10396:     my $now = time;
10397:     if (exists($$changes{'activate'})) {
10398:         if (ref($$changes{'activate'}) eq 'HASH') {
10399:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10400:             my $numnew = scalar(@newitems);
10401:             for (my $i=0; $i<$numnew; $i++) {
10402:                 my $newkey = $newitems[$i];
10403:                 my $newid = &Apache::loncommon::get_cgi_id();
10404:                 if ($newkey =~ /^\d+:/) { 
10405:                     $newkey =~ s/^(\d+)/$newid/;
10406:                     $translation{$1} = $newid;
10407:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10408:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10409:                     $translation{$1} = $newid;
10410:                 }
10411:                 $new_values{$file_name."\0".$newkey} = 
10412:                                           $$changes{'activate'}{$newitems[$i]};
10413:                 $new_control{$newkey} = $now;
10414:             }
10415:         }
10416:     }
10417:     my %todelete;
10418:     my %changed_items;
10419:     foreach my $action ('delete','update') {
10420:         if (exists($$changes{$action})) {
10421:             if (ref($$changes{$action}) eq 'HASH') {
10422:                 foreach my $key (keys(%{$$changes{$action}})) {
10423:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10424:                     if ($action eq 'delete') { 
10425:                         $todelete{$itemnum} = 1;
10426:                     } else {
10427:                         $changed_items{$itemnum} = $key;
10428:                     }
10429:                 }
10430:             }
10431:         }
10432:     }
10433:     # get lock on access controls for file.
10434:     my $lockhash = {
10435:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10436:                                                        ':'.$env{'user.domain'},
10437:                    }; 
10438:     my $tries = 0;
10439:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10440:    
10441:     while (($gotlock ne 'ok') && $tries < 10) {
10442:         $tries ++;
10443:         sleep(0.1);
10444:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10445:     }
10446:     if ($gotlock eq 'ok') {
10447:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10448:         my ($tmp)=keys(%curr_permissions);
10449:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10450:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10451:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10452:             if (ref($curr_controls) eq 'HASH') {
10453:                 foreach my $control_item (keys(%{$curr_controls})) {
10454:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10455:                     if (defined($todelete{$itemnum})) {
10456:                         push(@deletions,$file_name."\0".$control_item);
10457:                     } else {
10458:                         if (defined($changed_items{$itemnum})) {
10459:                             $new_control{$changed_items{$itemnum}} = $now;
10460:                             push(@deletions,$file_name."\0".$control_item);
10461:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10462:                         } else {
10463:                             $new_control{$control_item} = $$curr_controls{$control_item};
10464:                         }
10465:                     }
10466:                 }
10467:             }
10468:         }
10469:         my ($group);
10470:         if (&is_course($domain,$user)) {
10471:             ($group,my $file) = split(/\//,$file_name,2);
10472:         }
10473:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10474:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10475:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10476:         #  remove lock
10477:         my @del_lock = ($file_name."\0".'locked_access_records');
10478:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10479:         my $sqlresult =
10480:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10481:                                     $group);
10482:     } else {
10483:         $outcome = "error: could not obtain lockfile\n";  
10484:     }
10485:     return ($outcome,$deloutcome,\%new_values,\%translation);
10486: }
10487: 
10488: sub make_public_indefinitely {
10489:     my (@requrl) = @_;
10490:     return &automated_portfile_access('public',\@requrl);
10491: }
10492: 
10493: sub automated_portfile_access {
10494:     my ($accesstype,$addsref,$delsref,$info) = @_;
10495:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10496:         return 'invalid';
10497:     }
10498:     my %urls;
10499:     if (ref($addsref) eq 'ARRAY') {
10500:         foreach my $requrl (@{$addsref}) {
10501:             if (&is_portfolio_url($requrl)) {
10502:                 unless (exists($urls{$requrl})) {
10503:                     $urls{$requrl} = 'add';
10504:                 }
10505:             }
10506:         }
10507:     }
10508:     if (ref($delsref) eq 'ARRAY') {
10509:         foreach my $requrl (@{$delsref}) { 
10510:             if (&is_portfolio_url($requrl)) {
10511:                 unless (exists($urls{$requrl})) {
10512:                     $urls{$requrl} = 'delete'; 
10513:                 }
10514:             }
10515:         }
10516:     }
10517:     unless (keys(%urls)) {
10518:         return 'invalid';
10519:     }
10520:     my $ip;
10521:     if ($accesstype eq 'ip') {
10522:         if (ref($info) eq 'HASH') {
10523:             if ($info->{'ip'} ne '') {
10524:                 $ip = $info->{'ip'};
10525:             }
10526:         }
10527:         if ($ip eq '') {
10528:             return 'invalid';
10529:         }
10530:     }
10531:     my $errors;
10532:     my $now = time;
10533:     my %current_perms;
10534:     foreach my $requrl (sort(keys(%urls))) {
10535:         my $action;
10536:         if ($urls{$requrl} eq 'add') {
10537:             $action = 'activate';
10538:         } else {
10539:             $action = 'none';
10540:         }
10541:         my $aclnum = 0;
10542:         my (undef,$udom,$unum,$file_name,$group) =
10543:             &parse_portfolio_url($requrl);
10544:         unless (exists($current_perms{$unum.':'.$udom})) {
10545:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10546:         }
10547:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10548:                                                    $group,$file_name);
10549:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10550:             my ($num,$scope,$end,$start) = 
10551:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10552:             if ($scope eq $accesstype) {
10553:                 if (($start <= $now) && ($end == 0)) {
10554:                     if ($accesstype eq 'ip') {
10555:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10556:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10557:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10558:                                     if ($urls{$requrl} eq 'add') {
10559:                                         $action = 'none';
10560:                                         last;
10561:                                     } else {
10562:                                         $action = 'delete';
10563:                                         $aclnum = $num;
10564:                                         last;
10565:                                     }
10566:                                 }
10567:                             }
10568:                         }
10569:                     } elsif ($accesstype eq 'public') {
10570:                         if ($urls{$requrl} eq 'add') {
10571:                             $action = 'none';
10572:                             last;
10573:                         } else {
10574:                             $action = 'delete';
10575:                             $aclnum = $num;
10576:                             last;
10577:                         }
10578:                     }
10579:                 } elsif ($accesstype eq 'public') {
10580:                     $action = 'update';
10581:                     $aclnum = $num;
10582:                     last;
10583:                 }
10584:             }
10585:         }
10586:         if ($action eq 'none') {
10587:             next;
10588:         } else {
10589:             my %changes;
10590:             my $newend = 0;
10591:             my $newstart = $now;
10592:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10593:             $changes{$action}{$newkey} = {
10594:                 type => $accesstype,
10595:                 time => {
10596:                     start => $newstart,
10597:                     end   => $newend,
10598:                 },
10599:             };
10600:             if ($accesstype eq 'ip') {
10601:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10602:             }
10603:             my ($outcome,$deloutcome,$new_values,$translation) =
10604:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10605:             unless ($outcome eq 'ok') {
10606:                 $errors .= $outcome.' ';
10607:             }
10608:         }
10609:     }
10610:     if ($errors) {
10611:         $errors =~ s/\s$//;
10612:         return $errors;
10613:     } else {
10614:         return 'ok';
10615:     }
10616: }
10617: 
10618: #------------------------------------------------------Get Marked as Read Only
10619: 
10620: sub get_marked_as_readonly {
10621:     my ($domain,$user,$what,$group) = @_;
10622:     my $current_permissions = &get_portfile_permissions($domain,$user);
10623:     my @readonly_files;
10624:     my $cmp1=$what;
10625:     if (ref($what)) { $cmp1=join('',@{$what}) };
10626:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10627:         if (defined($group)) {
10628:             if ($file_name !~ m-^\Q$group\E/-) {
10629:                 next;
10630:             }
10631:         }
10632:         if (ref($value) eq "ARRAY"){
10633:             foreach my $stored_what (@{$value}) {
10634:                 my $cmp2=$stored_what;
10635:                 if (ref($stored_what) eq 'ARRAY') {
10636:                     $cmp2=join('',@{$stored_what});
10637:                 }
10638:                 if ($cmp1 eq $cmp2) {
10639:                     push(@readonly_files, $file_name);
10640:                     last;
10641:                 } elsif (!defined($what)) {
10642:                     push(@readonly_files, $file_name);
10643:                     last;
10644:                 }
10645:             }
10646:         }
10647:     }
10648:     return @readonly_files;
10649: }
10650: #-----------------------------------------------------------Get Marked as Read Only Hash
10651: 
10652: sub get_marked_as_readonly_hash {
10653:     my ($current_permissions,$group,$what) = @_;
10654:     my %readonly_files;
10655:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10656:         if (defined($group)) {
10657:             if ($file_name !~ m-^\Q$group\E/-) {
10658:                 next;
10659:             }
10660:         }
10661:         if (ref($value) eq "ARRAY"){
10662:             foreach my $stored_what (@{$value}) {
10663:                 if (ref($stored_what) eq 'ARRAY') {
10664:                     foreach my $lock_descriptor(@{$stored_what}) {
10665:                         if ($lock_descriptor eq 'graded') {
10666:                             $readonly_files{$file_name} = 'graded';
10667:                         } elsif ($lock_descriptor eq 'handback') {
10668:                             $readonly_files{$file_name} = 'handback';
10669:                         } else {
10670:                             if (!exists($readonly_files{$file_name})) {
10671:                                 $readonly_files{$file_name} = 'locked';
10672:                             }
10673:                         }
10674:                     }
10675:                 } 
10676:             }
10677:         } 
10678:     }
10679:     return %readonly_files;
10680: }
10681: # ------------------------------------------------------------ Unmark as Read Only
10682: 
10683: sub unmark_as_readonly {
10684:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10685:     # for portfolio submissions, $what contains [$symb,$crsid] 
10686:     my ($domain,$user,$what,$file_name,$group) = @_;
10687:     $file_name = &declutter_portfile($file_name);
10688:     my $symb_crs = $what;
10689:     if (ref($what)) { $symb_crs=join('',@$what); }
10690:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10691:     my ($tmp)=keys(%current_permissions);
10692:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10693:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10694:     foreach my $file (@readonly_files) {
10695: 	my $clean_file = &declutter_portfile($file);
10696: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10697: 	my $current_locks = $current_permissions{$file};
10698:         my @new_locks;
10699:         my @del_keys;
10700:         if (ref($current_locks) eq "ARRAY"){
10701:             foreach my $locker (@{$current_locks}) {
10702:                 my $compare=$locker;
10703:                 if (ref($locker) eq 'ARRAY') {
10704:                     $compare=join('',@{$locker});
10705:                     if ($compare ne $symb_crs) {
10706:                         push(@new_locks, $locker);
10707:                     }
10708:                 }
10709:             }
10710:             if (scalar(@new_locks) > 0) {
10711:                 $current_permissions{$file} = \@new_locks;
10712:             } else {
10713:                 push(@del_keys, $file);
10714:                 &del('file_permissions',\@del_keys, $domain, $user);
10715:                 delete($current_permissions{$file});
10716:             }
10717:         }
10718:     }
10719:     &put('file_permissions',\%current_permissions,$domain,$user);
10720:     return;
10721: }
10722: 
10723: # ------------------------------------------------------------ Directory lister
10724: 
10725: sub dirlist {
10726:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10727:     $uri=~s/^\///;
10728:     $uri=~s/\/$//;
10729:     my ($udom, $uname);
10730:     if ($getuserdir) {
10731:         $udom = $userdomain;
10732:         $uname = $username;
10733:     } else {
10734:         (undef,$udom,$uname)=split(/\//,$uri);
10735:         if(defined($userdomain)) {
10736:             $udom = $userdomain;
10737:         }
10738:         if(defined($username)) {
10739:             $uname = $username;
10740:         }
10741:     }
10742:     my ($dirRoot,$listing,@listing_results);
10743: 
10744:     $dirRoot = $perlvar{'lonDocRoot'};
10745:     if (defined($getpropath)) {
10746:         $dirRoot = &propath($udom,$uname);
10747:         $dirRoot =~ s/\/$//;
10748:     } elsif (defined($getuserdir)) {
10749:         my $subdir=$uname.'__';
10750:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10751:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10752:                    ."/$udom/$subdir/$uname";
10753:     } elsif (defined($alternateRoot)) {
10754:         $dirRoot = $alternateRoot;
10755:     }
10756: 
10757:     if($udom) {
10758:         if($uname) {
10759:             my $uhome = &homeserver($uname,$udom);
10760:             if ($uhome eq 'no_host') {
10761:                 return ([],'no_host');
10762:             }
10763:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10764:                               .$getuserdir.':'.&escape($dirRoot)
10765:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10766:             if ($listing eq 'unknown_cmd') {
10767:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10768:             } else {
10769:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10770:             }
10771:             if ($listing eq 'unknown_cmd') {
10772:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10773:                 @listing_results = split(/:/,$listing);
10774:             } else {
10775:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10776:             }
10777:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10778:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10779:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10780:                 return ([],$listing);
10781:             } else {
10782:                 return (\@listing_results);
10783:             }
10784:         } elsif(!$alternateRoot) {
10785:             my (%allusers,%listerror);
10786: 	    my %servers = &get_servers($udom,'library');
10787:  	    foreach my $tryserver (keys(%servers)) {
10788:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10789:                                   &escape($udom),$tryserver);
10790:                 if ($listing eq 'unknown_cmd') {
10791: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10792: 				      $udom, $tryserver);
10793:                 } else {
10794:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10795:                 }
10796: 		if ($listing eq 'unknown_cmd') {
10797: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10798: 				      $udom, $tryserver);
10799: 		    @listing_results = split(/:/,$listing);
10800: 		} else {
10801: 		    @listing_results =
10802: 			map { &unescape($_); } split(/:/,$listing);
10803: 		}
10804:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10805:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10806:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10807:                     $listerror{$tryserver} = $listing;
10808:                 } else {
10809: 		    foreach my $line (@listing_results) {
10810: 			my ($entry) = split(/&/,$line,2);
10811: 			$allusers{$entry} = 1;
10812: 		    }
10813: 		}
10814:             }
10815:             my @alluserslist=();
10816:             foreach my $user (sort(keys(%allusers))) {
10817:                 push(@alluserslist,$user.'&user');
10818:             }
10819: 
10820:             if (!%listerror) {
10821:                 # no errors
10822:                 return (\@alluserslist);
10823:             } elsif (scalar(keys(%servers)) == 1) {
10824:                 # one library server, one error 
10825:                 my ($key) = keys(%listerror);
10826:                 return (\@alluserslist, $listerror{$key});
10827:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10828:                 # con_lost indicates that we might miss data from at least one
10829:                 # library server
10830:                 return (\@alluserslist, 'con_lost');
10831:             } else {
10832:                 # multiple library servers and no con_lost -> data should be
10833:                 # complete. 
10834:                 return (\@alluserslist);
10835:             }
10836: 
10837:         } else {
10838:             return ([],'missing username');
10839:         }
10840:     } elsif(!defined($getpropath)) {
10841:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10842:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10843:         return (\@all_domains);
10844:     } else {
10845:         return ([],'missing domain');
10846:     }
10847: }
10848: 
10849: # --------------------------------------------- GetFileTimestamp
10850: # This function utilizes dirlist and returns the date stamp for
10851: # when it was last modified.  It will also return an error of -1
10852: # if an error occurs
10853: 
10854: sub GetFileTimestamp {
10855:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10856:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10857:     $studentName   = &LONCAPA::clean_username($studentName);
10858:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10859:                                     undef,$getuserdir);
10860:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10861:         return -1;
10862:     }
10863:     if (ref($fileref) eq 'ARRAY') {
10864:         my @stats = split('&',$fileref->[0]);
10865:         # @stats contains first the filename, then the stat output
10866:         return $stats[10]; # so this is 10 instead of 9.
10867:     } else {
10868:         return -1;
10869:     }
10870: }
10871: 
10872: sub stat_file {
10873:     my ($uri) = @_;
10874:     $uri = &clutter_with_no_wrapper($uri);
10875: 
10876:     my ($udom,$uname,$file);
10877:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10878: 	($udom,$uname,$file) =
10879: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10880: 	$file = 'userfiles/'.$file;
10881:     }
10882:     if ($uri =~ m-^/res/-) {
10883: 	($udom,$uname) = 
10884: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10885: 	$file = $uri;
10886:     }
10887: 
10888:     if (!$udom || !$uname || !$file) {
10889: 	# unable to handle the uri
10890: 	return ();
10891:     }
10892:     my $getpropath;
10893:     if ($file =~ /^userfiles\//) {
10894:         $getpropath = 1;
10895:     }
10896:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10897:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10898:         return ();
10899:     } else {
10900:         if (ref($listref) eq 'ARRAY') {
10901:             my @stats = split('&',$listref->[0]);
10902: 	    shift(@stats); #filename is first
10903: 	    return @stats;
10904:         }
10905:     }
10906:     return ();
10907: }
10908: 
10909: # --------------------------------------------------------- recursedirs
10910: # Recursive function to traverse either a specific user's Authoring Space
10911: # or corresponding Published Resource Space, and populate the hash ref:
10912: # $dirhashref with URLs of all directories, and if $filehashref hash
10913: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10914: # or .rights files in resource space, and .meta, .save, .log, and .bak
10915: # files in Authoring Space.
10916: #
10917: # Inputs:
10918: #
10919: # $is_home - true if current server is home server for user's space
10920: # $context - either: priv, or res respectively for Authoring or Resource Space.
10921: # $docroot - Document root (i.e., /home/httpd/html
10922: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10923: # $relpath - Current path (relative to top level).
10924: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10925: # $filehashref - reference to hash to populate with URLs of files (Optional)
10926: #
10927: # Returns: nothing
10928: #
10929: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10930: #
10931: # Currently used by interface/londocs.pm to create linked select boxes for
10932: # directory and filename to import a Course "Author" resource into a course, and
10933: # also to create linked select boxes for Authoring Space and Directory to choose
10934: # save location for creation of a new "standard" problem from the Course Editor.
10935: #
10936: 
10937: sub recursedirs {
10938:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10939:     return unless (ref($dirhashref) eq 'HASH');
10940:     my $currpath = $docroot.$toppath;
10941:     if ($relpath) {
10942:         $currpath .= "/$relpath";
10943:     }
10944:     my $savefile;
10945:     if (ref($filehashref)) {
10946:         $savefile = 1;
10947:     }
10948:     if ($is_home) {
10949:         if (opendir(my $dirh,$currpath)) {
10950:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10951:                 next if ($item eq '');
10952:                 if (-d "$currpath/$item") {
10953:                     my $newpath;
10954:                     if ($relpath) {
10955:                         $newpath = "$relpath/$item";
10956:                     } else {
10957:                         $newpath = $item;
10958:                     }
10959:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10960:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10961:                 } elsif ($savefile) {
10962:                     if ($context eq 'priv') {
10963:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10964:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10965:                         }
10966:                     } else {
10967:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10968:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10969:                         }
10970:                     }
10971:                 }
10972:             }
10973:             closedir($dirh);
10974:         }
10975:     } else {
10976:         my ($dirlistref,$listerror) =
10977:             &dirlist($toppath.$relpath);
10978:         my @dir_lines;
10979:         my $dirptr=16384;
10980:         if (ref($dirlistref) eq 'ARRAY') {
10981:             foreach my $dir_line (sort
10982:                               {
10983:                                   my ($afile)=split('&',$a,2);
10984:                                   my ($bfile)=split('&',$b,2);
10985:                                   return (lc($afile) cmp lc($bfile));
10986:                               } (@{$dirlistref})) {
10987:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10988:                     split(/\&/,$dir_line,16);
10989:                 $item =~ s/\s+$//;
10990:                 next if (($item =~ /^\.\.?$/) || ($obs));
10991:                 if ($dirptr&$testdir) {
10992:                     my $newpath;
10993:                     if ($relpath) {
10994:                         $newpath = "$relpath/$item";
10995:                     } else {
10996:                         $relpath = '/';
10997:                         $newpath = $item;
10998:                     }
10999:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11000:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11001:                 } elsif ($savefile) {
11002:                     if ($context eq 'priv') {
11003:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11004:                             $filehashref->{$relpath}{$item} = 1;
11005:                         }
11006:                     } else {
11007:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11008:                             $filehashref->{$relpath}{$item} = 1;
11009:                         }
11010:                     }
11011:                 }
11012:             }
11013:         }
11014:     }
11015:     return;
11016: }
11017: 
11018: # -------------------------------------------------------- Value of a Condition
11019: 
11020: # gets the value of a specific preevaluated condition
11021: #    stored in the string  $env{user.state.<cid>}
11022: # or looks up a condition reference in the bighash and if if hasn't
11023: # already been evaluated recurses into docondval to get the value of
11024: # the condition, then memoizing it to 
11025: #   $env{user.state.<cid>.<condition>}
11026: sub directcondval {
11027:     my $number=shift;
11028:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11029: 	&Apache::lonuserstate::evalstate();
11030:     }
11031:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11032: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11033:     } elsif ($number =~ /^_/) {
11034: 	my $sub_condition;
11035: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11036: 		&GDBM_READER(),0640)) {
11037: 	    $sub_condition=$bighash{'conditions'.$number};
11038: 	    untie(%bighash);
11039: 	}
11040: 	my $value = &docondval($sub_condition);
11041: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11042: 	return $value;
11043:     }
11044:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11045:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11046:     } else {
11047:        return 2;
11048:     }
11049: }
11050: 
11051: # get the collection of conditions for this resource
11052: sub condval {
11053:     my $condidx=shift;
11054:     my $allpathcond='';
11055:     foreach my $cond (split(/\|/,$condidx)) {
11056: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11057: 	    $allpathcond.=
11058: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11059: 	}
11060:     }
11061:     $allpathcond=~s/\|$//;
11062:     return &docondval($allpathcond);
11063: }
11064: 
11065: #evaluates an expression of conditions
11066: sub docondval {
11067:     my ($allpathcond) = @_;
11068:     my $result=0;
11069:     if ($env{'request.course.id'}
11070: 	&& defined($allpathcond)) {
11071: 	my $operand='|';
11072: 	my @stack;
11073: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11074: 	    if ($chunk eq '(') {
11075: 		push @stack,($operand,$result);
11076: 	    } elsif ($chunk eq ')') {
11077: 		my $before=pop @stack;
11078: 		if (pop @stack eq '&') {
11079: 		    $result=$result>$before?$before:$result;
11080: 		} else {
11081: 		    $result=$result>$before?$result:$before;
11082: 		}
11083: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11084: 		$operand=$chunk;
11085: 	    } else {
11086: 		my $new=directcondval($chunk);
11087: 		if ($operand eq '&') {
11088: 		    $result=$result>$new?$new:$result;
11089: 		} else {
11090: 		    $result=$result>$new?$result:$new;
11091: 		}
11092: 	    }
11093: 	}
11094:     }
11095:     return $result;
11096: }
11097: 
11098: # ---------------------------------------------------- Devalidate courseresdata
11099: 
11100: sub devalidatecourseresdata {
11101:     my ($coursenum,$coursedomain)=@_;
11102:     my $hashid=$coursenum.':'.$coursedomain;
11103:     &devalidate_cache_new('courseres',$hashid);
11104: }
11105: 
11106: 
11107: # --------------------------------------------------- Course Resourcedata Query
11108: #
11109: #  Parameters:
11110: #      $coursenum    - Number of the course.
11111: #      $coursedomain - Domain at which the course was created.
11112: #  Returns:
11113: #     A hash of the course parameters along (I think) with timestamps
11114: #     and version info.
11115: 
11116: sub get_courseresdata {
11117:     my ($coursenum,$coursedomain)=@_;
11118:     my $coursehom=&homeserver($coursenum,$coursedomain);
11119:     my $hashid=$coursenum.':'.$coursedomain;
11120:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11121:     my %dumpreply;
11122:     unless (defined($cached)) {
11123: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11124: 	$result=\%dumpreply;
11125: 	my ($tmp) = keys(%dumpreply);
11126: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11127: 	    &do_cache_new('courseres',$hashid,$result,600);
11128: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11129: 	    return $tmp;
11130: 	} elsif ($tmp =~ /^(error)/) {
11131: 	    $result=undef;
11132: 	    &do_cache_new('courseres',$hashid,$result,600);
11133: 	}
11134:     }
11135:     return $result;
11136: }
11137: 
11138: sub devalidateuserresdata {
11139:     my ($uname,$udom)=@_;
11140:     my $hashid="$udom:$uname";
11141:     &devalidate_cache_new('userres',$hashid);
11142: }
11143: 
11144: sub get_userresdata {
11145:     my ($uname,$udom)=@_;
11146:     #most student don\'t have any data set, check if there is some data
11147:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11148: 
11149:     my $hashid="$udom:$uname";
11150:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11151:     if (!defined($cached)) {
11152: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11153: 	$result=\%resourcedata;
11154: 	&do_cache_new('userres',$hashid,$result,600);
11155:     }
11156:     my ($tmp)=keys(%$result);
11157:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11158: 	return $result;
11159:     }
11160:     #error 2 occurs when the .db doesn't exist
11161:     if ($tmp!~/error: 2 /) {
11162:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11163: 	    &logthis("<font color=\"blue\">WARNING:".
11164: 		     " Trying to get resource data for ".
11165: 		     $uname." at ".$udom.": ".
11166: 		     $tmp."</font>");
11167:         }
11168:     } elsif ($tmp=~/error: 2 /) {
11169: 	#&EXT_cache_set($udom,$uname);
11170: 	&do_cache_new('userres',$hashid,undef,600);
11171: 	undef($tmp); # not really an error so don't send it back
11172:     }
11173:     return $tmp;
11174: }
11175: #----------------------------------------------- resdata - return resource data
11176: #  Purpose:
11177: #    Return resource data for either users or for a course.
11178: #  Parameters:
11179: #     $name      - Course/user name.
11180: #     $domain    - Name of the domain the user/course is registered on.
11181: #     $type      - Type of thing $name is (must be 'course' or 'user')
11182: #     $mapp      - decluttered URL of enclosing map  
11183: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11184: #     $recurseup - Ref to array of map URLs, starting with map containing
11185: #                  $mapp up through hierarchy of nested maps to top level map.  
11186: #     $courseid  - CourseID (first part of param identifier).
11187: #     $modifier  - Middle part of param identifier.
11188: #     $what      - Last part of param identifier.
11189: #     @which     - Array of names of resources desired.
11190: #  Returns:
11191: #     The value of the first reasource in @which that is found in the
11192: #     resource hash.
11193: #  Exceptional Conditions:
11194: #     If the $type passed in is not valid (not the string 'course' or 
11195: #     'user', an undefined  reference is returned.
11196: #     If none of the resources are found, an undef is returned
11197: sub resdata {
11198:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11199:         $modifier,$what,@which)=@_;
11200:     my $result;
11201:     if ($type eq 'course') {
11202: 	$result=&get_courseresdata($name,$domain);
11203:     } elsif ($type eq 'user') {
11204: 	$result=&get_userresdata($name,$domain);
11205:     }
11206:     if (!ref($result)) { return $result; }    
11207:     foreach my $item (@which) {
11208:         if ($item->[1] eq 'course') {
11209:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11210:                 unless ($$recursed) {
11211:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11212:                     $$recursed = 1;
11213:                 }
11214:                 foreach my $item (@${recurseup}) {
11215:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11216:                     last if (defined($result->{$norecursechk}));
11217:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11218:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11219:                 }
11220:             }
11221:         }
11222:         if (defined($result->{$item->[0]})) {
11223: 	    return [$result->{$item->[0]},$item->[1]];
11224: 	}
11225:     }
11226:     return undef;
11227: }
11228: 
11229: sub get_domain_lti {
11230:     my ($cdom,$context) = @_;
11231:     my ($name,%lti);
11232:     if ($context eq 'consumer') {
11233:         $name = 'ltitools';
11234:     } elsif ($context eq 'provider') {
11235:         $name = 'lti';
11236:     } else {
11237:         return %lti;
11238:     }
11239:     my ($result,$cached)=&is_cached_new($name,$cdom);
11240:     if (defined($cached)) {
11241:         if (ref($result) eq 'HASH') {
11242:             %lti = %{$result};
11243:         }
11244:     } else {
11245:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11246:         if (ref($domconfig{$name}) eq 'HASH') {
11247:             %lti = %{$domconfig{$name}};
11248:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11249:             if (ref($encdomconfig{$name}) eq 'HASH') {
11250:                 foreach my $id (keys(%lti)) {
11251:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11252:                         foreach my $item ('key','secret') {
11253:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11254:                         }
11255:                     }
11256:                 }
11257:             }
11258:         }
11259:         my $cachetime = 24*60*60;
11260:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11261:     }
11262:     return %lti;
11263: }
11264: 
11265: sub get_numsuppfiles {
11266:     my ($cnum,$cdom,$ignorecache)=@_;
11267:     my $hashid=$cnum.':'.$cdom;
11268:     my ($suppcount,$cached);
11269:     unless ($ignorecache) {
11270:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11271:     }
11272:     unless (defined($cached)) {
11273:         my $chome=&homeserver($cnum,$cdom);
11274:         unless ($chome eq 'no_host') {
11275:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11276:             my $suppmap = 'supplemental.sequence';
11277:             ($suppcount,$supptools,$errors) =
11278:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11279:                                                          $supptools,$errors);
11280:         }
11281:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11282:     }
11283:     return $suppcount;
11284: }
11285: 
11286: #
11287: # EXT resource caching routines
11288: #
11289: 
11290: {
11291: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11292: #
11293: # The course for which we cache
11294: my $cachedmapkey='';
11295: # The cached recursive maps for this course
11296: my %cachedmaps=();
11297: # When this was last done
11298: my $cachedmaptime='';
11299: 
11300: sub clear_EXT_cache_status {
11301:     &delenv('cache.EXT.');
11302: }
11303: 
11304: sub EXT_cache_status {
11305:     my ($target_domain,$target_user) = @_;
11306:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11307:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11308:         # We know already the user has no data
11309:         return 1;
11310:     } else {
11311:         return 0;
11312:     }
11313: }
11314: 
11315: sub EXT_cache_set {
11316:     my ($target_domain,$target_user) = @_;
11317:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11318:     #&appenv({$cachename => time});
11319: }
11320: 
11321: # --------------------------------------------------------- Value of a Variable
11322: sub EXT {
11323: 
11324:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11325:     unless ($varname) { return ''; }
11326:     #get real user name/domain, courseid and symb
11327:     my $courseid;
11328:     my $publicuser;
11329:     if ($symbparm) {
11330: 	$symbparm=&get_symb_from_alias($symbparm);
11331:     }
11332:     if (!($uname && $udom)) {
11333:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11334:       if (!$symbparm) {	$symbparm=$cursymb; }
11335:     } else {
11336: 	$courseid=$env{'request.course.id'};
11337:     }
11338:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11339:     my $rest;
11340:     if (defined($therest[0])) {
11341:        $rest=join('.',@therest);
11342:     } else {
11343:        $rest='';
11344:     }
11345: 
11346:     my $qualifierrest=$qualifier;
11347:     if ($rest) { $qualifierrest.='.'.$rest; }
11348:     my $spacequalifierrest=$space;
11349:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11350:     if ($realm eq 'user') {
11351: # --------------------------------------------------------------- user.resource
11352: 	if ($space eq 'resource') {
11353: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11354: 		  || defined($Apache::lonhomework::parsing_a_task))
11355: 		 &&
11356: 		 ($symbparm eq &symbread()) ) {	
11357: 		# if we are in the middle of processing the resource the
11358: 		# get the value we are planning on committing
11359:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11360:                     return $Apache::lonhomework::results{$qualifierrest};
11361:                 } else {
11362:                     return $Apache::lonhomework::history{$qualifierrest};
11363:                 }
11364: 	    } else {
11365: 		my %restored;
11366: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11367: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11368: 		} else {
11369: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11370: 		}
11371: 		return $restored{$qualifierrest};
11372: 	    }
11373: # ----------------------------------------------------------------- user.access
11374:         } elsif ($space eq 'access') {
11375: 	    # FIXME - not supporting calls for a specific user
11376:             return &allowed($qualifier,$rest);
11377: # ------------------------------------------ user.preferences, user.environment
11378:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11379: 	    if (($uname eq $env{'user.name'}) &&
11380: 		($udom eq $env{'user.domain'})) {
11381: 		return $env{join('.',('environment',$qualifierrest))};
11382: 	    } else {
11383: 		my %returnhash;
11384: 		if (!$publicuser) {
11385: 		    %returnhash=&userenvironment($udom,$uname,
11386: 						 $qualifierrest);
11387: 		}
11388: 		return $returnhash{$qualifierrest};
11389: 	    }
11390: # ----------------------------------------------------------------- user.course
11391:         } elsif ($space eq 'course') {
11392: 	    # FIXME - not supporting calls for a specific user
11393:             return $env{join('.',('request.course',$qualifier))};
11394: # ------------------------------------------------------------------- user.role
11395:         } elsif ($space eq 'role') {
11396: 	    # FIXME - not supporting calls for a specific user
11397:             my ($role,$where)=split(/\./,$env{'request.role'});
11398:             if ($qualifier eq 'value') {
11399: 		return $role;
11400:             } elsif ($qualifier eq 'extent') {
11401:                 return $where;
11402:             }
11403: # ----------------------------------------------------------------- user.domain
11404:         } elsif ($space eq 'domain') {
11405:             return $udom;
11406: # ------------------------------------------------------------------- user.name
11407:         } elsif ($space eq 'name') {
11408:             return $uname;
11409: # ---------------------------------------------------- Any other user namespace
11410:         } else {
11411: 	    my %reply;
11412: 	    if (!$publicuser) {
11413: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11414: 	    }
11415: 	    return $reply{$qualifierrest};
11416:         }
11417:     } elsif ($realm eq 'query') {
11418: # ---------------------------------------------- pull stuff out of query string
11419:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11420: 						[$spacequalifierrest]);
11421: 	return $env{'form.'.$spacequalifierrest}; 
11422:    } elsif ($realm eq 'request') {
11423: # ------------------------------------------------------------- request.browser
11424:         if ($space eq 'browser') {
11425:             return $env{'browser.'.$qualifier};
11426: # ------------------------------------------------------------ request.filename
11427:         } else {
11428:             return $env{'request.'.$spacequalifierrest};
11429:         }
11430:     } elsif ($realm eq 'course') {
11431: # ---------------------------------------------------------- course.description
11432:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11433:     } elsif ($realm eq 'resource') {
11434: 
11435: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11436: 	    if (!$symbparm) { $symbparm=&symbread(); }
11437: 	}
11438: 
11439:         if ($qualifier eq '') {
11440: 	    if ($space eq 'title') {
11441: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11442: 	        return &gettitle($symbparm);
11443: 	    }
11444: 	
11445: 	    if ($space eq 'map') {
11446: 	        my ($map) = &decode_symb($symbparm);
11447: 	        return &symbread($map);
11448: 	    }
11449:             if ($space eq 'maptitle') {
11450:                 my ($map) = &decode_symb($symbparm);
11451:                 return &gettitle($map);
11452:             }
11453: 	    if ($space eq 'filename') {
11454: 	        if ($symbparm) {
11455: 		    return &clutter((&decode_symb($symbparm))[2]);
11456: 	        }
11457: 	        return &hreflocation('',$env{'request.filename'});
11458: 	    }
11459: 
11460:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11461:                 if ($space eq 'visibleparts') {
11462:                     my $navmap = Apache::lonnavmaps::navmap->new();
11463:                     my $item;
11464:                     if (ref($navmap)) {
11465:                         my $res = $navmap->getBySymb($symbparm);
11466:                         my $parts = $res->parts();
11467:                         if (ref($parts) eq 'ARRAY') {
11468:                             $item = join(',',@{$parts});
11469:                         }
11470:                         undef($navmap);
11471:                     }
11472:                     return $item;
11473:                 }
11474:             }
11475:         }
11476: 
11477: 	my ($section, $group, @groups, @recurseup, $recursed);
11478: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11479:         if (($courseid eq '') && ($cid)) {
11480:             $courseid = $cid;
11481:         }
11482: 	if (($symbparm && $courseid) && 
11483: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11484: 
11485: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11486: 
11487: # ----------------------------------------------------- Cascading lookup scheme
11488: 	    my $symbp=$symbparm;
11489: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11490: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11491:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11492: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11493: 	    if (($env{'user.name'} eq $uname) &&
11494: 		($env{'user.domain'} eq $udom)) {
11495: 		$section=$env{'request.course.sec'};
11496:                 @groups = split(/:/,$env{'request.course.groups'});  
11497:                 @groups=&sort_course_groups($courseid,@groups); 
11498: 	    } else {
11499: 		if (! defined($usection)) {
11500: 		    $section=&getsection($udom,$uname,$courseid);
11501: 		} else {
11502: 		    $section = $usection;
11503: 		}
11504:                 @groups = &get_users_groups($udom,$uname,$courseid);
11505: 	    }
11506: 
11507: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11508: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11509:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11510: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11511: 
11512: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11513: 	    my $courselevelr=$courseid.'.'.$symbparm;
11514:             $courseleveli=$courseid.'.'.$recurseparm;
11515: 	    $courselevelm=$courseid.'.'.$mapparm;
11516: 
11517: # ----------------------------------------------------------- first, check user
11518: 
11519: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11520:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11521: 				       ([$courselevelr,'resource'],
11522: 					[$courselevelm,'map'     ],
11523:                                         [$courseleveli,'map'     ],
11524: 					[$courselevel, 'course'  ]));
11525: 	    if (defined($userreply)) { return &get_reply($userreply); }
11526: 
11527: # ------------------------------------------------ second, check some of course
11528:             my $coursereply;
11529:             if (@groups > 0) {
11530:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11531:                                        $recurseparm,$mapparm,$spacequalifierrest,
11532:                                        $mapp,\$recursed,\@recurseup);
11533:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11534:             }
11535: 
11536: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11537: 				  $env{'course.'.$courseid.'.domain'},
11538: 				  'course',$mapp,\$recursed,\@recurseup,
11539:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11540: 				  ([$seclevelr,   'resource'],
11541: 				   [$seclevelm,   'map'     ],
11542:                                    [$secleveli,   'map'     ],
11543: 				   [$seclevel,    'course'  ],
11544: 				   [$courselevelr,'resource']));
11545: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11546: 
11547: # ------------------------------------------------------ third, check map parms
11548: 	    my %parmhash=();
11549: 	    my $thisparm='';
11550: 	    if (tie(%parmhash,'GDBM_File',
11551: 		    $env{'request.course.fn'}.'_parms.db',
11552: 		    &GDBM_READER(),0640)) {
11553: 		$thisparm=$parmhash{$symbparm};
11554: 		untie(%parmhash);
11555: 	    }
11556: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11557: 	}
11558: # ------------------------------------------ fourth, look in resource metadata
11559:  
11560:         my $what = $spacequalifierrest;
11561: 	$what=~s/\./\_/;
11562: 	my $filename;
11563: 	if (!$symbparm) { $symbparm=&symbread(); }
11564: 	if ($symbparm) {
11565: 	    $filename=(&decode_symb($symbparm))[2];
11566: 	} else {
11567: 	    $filename=$env{'request.filename'};
11568: 	}
11569:         my $toolsymb;
11570:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
11571:             $toolsymb = $symbparm;
11572:         }
11573: 	my $metadata=&metadata($filename,$what,$toolsymb);
11574: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11575: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
11576: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11577: 
11578: # ----------------------------------------------- fifth, look in rest of course
11579: 	if ($symbparm && defined($courseid) && 
11580: 	    $courseid eq $env{'request.course.id'}) {
11581: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11582: 				     $env{'course.'.$courseid.'.domain'},
11583: 				     'course',$mapp,\$recursed,\@recurseup,
11584:                                      $courseid,'.',$spacequalifierrest,
11585: 				     ([$courselevelm,'map'   ],
11586:                                       [$courseleveli,'map'   ],
11587: 				      [$courselevel, 'course']));
11588: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11589: 	}
11590: # ------------------------------------------------------------------ Cascade up
11591: 	unless ($space eq '0') {
11592: 	    my @parts=split(/_/,$space);
11593: 	    my $id=pop(@parts);
11594: 	    my $part=join('_',@parts);
11595: 	    if ($part eq '') { $part='0'; }
11596: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11597: 				 $symbparm,$udom,$uname,$section,1);
11598: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11599: 	}
11600: 	if ($recurse) { return undef; }
11601: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
11602: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11603: # ---------------------------------------------------- Any other user namespace
11604:     } elsif ($realm eq 'environment') {
11605: # ----------------------------------------------------------------- environment
11606: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11607: 	    return $env{'environment.'.$spacequalifierrest};
11608: 	} else {
11609: 	    if ($uname eq 'anonymous' && $udom eq '') {
11610: 		return '';
11611: 	    }
11612: 	    my %returnhash=&userenvironment($udom,$uname,
11613: 					    $spacequalifierrest);
11614: 	    return $returnhash{$spacequalifierrest};
11615: 	}
11616:     } elsif ($realm eq 'system') {
11617: # ----------------------------------------------------------------- system.time
11618: 	if ($space eq 'time') {
11619: 	    return time;
11620:         }
11621:     } elsif ($realm eq 'server') {
11622: # ----------------------------------------------------------------- system.time
11623: 	if ($space eq 'name') {
11624: 	    return $ENV{'SERVER_NAME'};
11625:         }
11626:     }
11627:     return '';
11628: }
11629: 
11630: sub get_reply {
11631:     my ($reply_value) = @_;
11632:     if (ref($reply_value) eq 'ARRAY') {
11633:         if (wantarray) {
11634: 	    return @$reply_value;
11635:         }
11636:         return $reply_value->[0];
11637:     } else {
11638:         return $reply_value;
11639:     }
11640: }
11641: 
11642: sub check_group_parms {
11643:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11644:         $recursed,$recurseupref) = @_;
11645:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11646:                   [$what,'course']);
11647:     my $coursereply;
11648:     foreach my $group (@{$groups}) {
11649:         my @groupitems = ();
11650:         foreach my $level (@levels) {
11651:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11652:              push(@groupitems,[$item,$level->[1]]);
11653:         }
11654:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11655:                                    $env{'course.'.$courseid.'.domain'},
11656:                                    'course',$mapp,$recursed,$recurseupref,
11657:                                    $courseid,'.['.$group.'].',$what,
11658:                                    @groupitems);
11659:         last if (defined($coursereply));
11660:     }
11661:     return $coursereply;
11662: }
11663: 
11664: sub get_map_hierarchy {
11665:     my ($mapname,$courseid) = @_;
11666:     my @recurseup = ();
11667:     if ($mapname) {
11668:         if (($cachedmapkey eq $courseid) &&
11669:             (abs($cachedmaptime-time)<5)) {
11670:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11671:                 return @{$cachedmaps{$mapname}};
11672:             }
11673:         }
11674:         my $navmap = Apache::lonnavmaps::navmap->new();
11675:         if (ref($navmap)) {
11676:             @recurseup = $navmap->recurseup_maps($mapname);
11677:             undef($navmap);
11678:             $cachedmaps{$mapname} = \@recurseup;
11679:             $cachedmaptime=time;
11680:             $cachedmapkey=$courseid;
11681:         }
11682:     }
11683:     return @recurseup;
11684: }
11685: 
11686: }
11687: 
11688: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11689:     my ($courseid,@groups) = @_;
11690:     @groups = sort(@groups);
11691:     return @groups;
11692: }
11693: 
11694: sub packages_tab_default {
11695:     my ($uri,$varname,$toolsymb)=@_;
11696:     my (undef,$part,$name)=split(/\./,$varname);
11697: 
11698:     my (@extension,@specifics,$do_default);
11699:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
11700: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11701: 	if ($pack_type eq 'default') {
11702: 	    $do_default=1;
11703: 	} elsif ($pack_type eq 'extension') {
11704: 	    push(@extension,[$package,$pack_type,$pack_part]);
11705: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11706: 	    # only look at packages defaults for packages that this id is
11707: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11708: 	}
11709:     }
11710:     # first look for a package that matches the requested part id
11711:     foreach my $package (@specifics) {
11712: 	my (undef,$pack_type,$pack_part)=@{$package};
11713: 	next if ($pack_part ne $part);
11714: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11715: 	    return $packagetab{"$pack_type&$name&default"};
11716: 	}
11717:     }
11718:     # look for any possible matching non extension_ package
11719:     foreach my $package (@specifics) {
11720: 	my (undef,$pack_type,$pack_part)=@{$package};
11721: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11722: 	    return $packagetab{"$pack_type&$name&default"};
11723: 	}
11724: 	if ($pack_type eq 'part') { $pack_part='0'; }
11725: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11726: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11727: 	}
11728:     }
11729:     # look for any posible extension_ match
11730:     foreach my $package (@extension) {
11731: 	my ($package,$pack_type)=@{$package};
11732: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11733: 	    return $packagetab{"$pack_type&$name&default"};
11734: 	}
11735: 	if (defined($packagetab{$package."&$name&default"})) {
11736: 	    return $packagetab{$package."&$name&default"};
11737: 	}
11738:     }
11739:     # look for a global default setting
11740:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11741: 	return $packagetab{"default&$name&default"};
11742:     }
11743:     return undef;
11744: }
11745: 
11746: sub add_prefix_and_part {
11747:     my ($prefix,$part)=@_;
11748:     my $keyroot;
11749:     if (defined($prefix) && $prefix !~ /^__/) {
11750: 	# prefix that has a part already
11751: 	$keyroot=$prefix;
11752:     } elsif (defined($prefix)) {
11753: 	# prefix that is missing a part
11754: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11755:     } else {
11756: 	# no prefix at all
11757: 	if (defined($part)) { $keyroot='_'.$part; }
11758:     }
11759:     return $keyroot;
11760: }
11761: 
11762: # ---------------------------------------------------------------- Get metadata
11763: 
11764: my %metaentry;
11765: my %importedpartids;
11766: my %importedrespids;
11767: sub metadata {
11768:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
11769:     $uri=&declutter($uri);
11770:     # if it is a non metadata possible uri return quickly
11771:     if (($uri eq '') || 
11772: 	(($uri =~ m|^/*adm/|) && 
11773: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11774:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11775: 	return undef;
11776:     }
11777:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11778: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11779: 	return undef;
11780:     }
11781:     my $filename=$uri;
11782:     $uri=~s/\.meta$//;
11783: #
11784: # Is the metadata already cached?
11785: # Look at timestamp of caching
11786: # Everything is cached by the main uri, libraries are never directly cached
11787: #
11788:     if (!defined($liburi)) {
11789: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11790: 	if (defined($cached)) { return $result->{':'.$what}; }
11791:     }
11792: 
11793: #
11794: # If the uri is for an external tool the file from
11795: # which metadata should be retrieved depends on whether
11796: # the tool had been configured to be gradable (set in the Course
11797: # Editor or Resource Editor).
11798: #
11799: # If a valid symb has been included as the third arg in the call
11800: # to &metadata() that can be used to retrieve the value of
11801: # parameter_0_gradable set for the resource, and included in the
11802: # uploaded map containing the tool. The value is retrieved via
11803: # &EXT(), if a valid symb is available.  Otherwise the value of
11804: # gradable in the exttool_$marker.db file for the tool instance
11805: # is retrieved via &get().
11806: #
11807: # When lonuserstate::traceroute() calls lonnet::EXT() for 
11808: # hiddenresource and encrypturl (during course initialization)
11809: # the map-level parameter for resource.0.gradable included in the 
11810: # uploaded map containing the tool will not yet have been stored
11811: # in the user_course_parms.db file for the user's session, so in 
11812: # this case fall back to retrieving gradable status from the
11813: # exttool_$marker.db file.
11814: #
11815: # In order to avoid an infinite loop, &metadata() will return
11816: # before a call to &EXT(), if the uri is for an external tool
11817: # and the $what for which metadata is being requested is
11818: # parameter_0_gradable or 0_gradable.
11819: #
11820: 
11821:     if ($uri =~ /ext\.tool$/) {
11822:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
11823:             return;
11824:         } else {
11825:             my ($checked,$use_passback);
11826:             if ($toolsymb ne '') {
11827:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
11828:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
11829:                     $checked = 1;
11830:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
11831:                         $use_passback = 1;
11832:                     }
11833:                 }
11834:             }
11835:             unless ($checked) {
11836:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
11837:                 $marker=~s/\D//g;
11838:                 if ($marker) {
11839:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
11840:                     $use_passback = $toolsettings{'gradable'};
11841:                 }
11842:             }
11843:             if ($use_passback) {
11844:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
11845:             } else {
11846:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
11847:             }
11848:         }
11849:     }
11850: 
11851:     {
11852: # Imported parts would go here
11853:         my @origfiletagids=();
11854:         my $importedparts=0;
11855: 
11856: # Imported responseids would go here
11857:         my $importedresponses=0;
11858: #
11859: # Is this a recursive call for a library?
11860: #
11861: #	if (! exists($metacache{$uri})) {
11862: #	    $metacache{$uri}={};
11863: #	}
11864: 	my $cachetime = 60*60;
11865:         if ($liburi) {
11866: 	    $liburi=&declutter($liburi);
11867:             $filename=$liburi;
11868:         } else {
11869: 	    &devalidate_cache_new('meta',$uri);
11870: 	    undef(%metaentry);
11871: 	}
11872:         my %metathesekeys=();
11873:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11874: 	my $metastring;
11875: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11876: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11877: 	    $metastring = 
11878: 		&Apache::lonnet::ssi_body($which,
11879: 					  ('grade_target' => 'meta'));
11880: 	    $cachetime = 1; # only want this cached in the child not long term
11881: 	} elsif (($uri !~ m -^(editupload)/-) && 
11882:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11883: 	    my $file=&filelocation('',&clutter($filename));
11884: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11885: 	    $metastring=&getfile($file);
11886: 	}
11887:         my $parser=HTML::LCParser->new(\$metastring);
11888:         my $token;
11889:         undef %metathesekeys;
11890:         while ($token=$parser->get_token) {
11891: 	    if ($token->[0] eq 'S') {
11892: 		if (defined($token->[2]->{'package'})) {
11893: #
11894: # This is a package - get package info
11895: #
11896: 		    my $package=$token->[2]->{'package'};
11897: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11898: 		    if (defined($token->[2]->{'id'})) { 
11899: 			$keyroot.='_'.$token->[2]->{'id'}; 
11900: 		    }
11901: 		    if ($metaentry{':packages'}) {
11902: 			$metaentry{':packages'}.=','.$package.$keyroot;
11903: 		    } else {
11904: 			$metaentry{':packages'}=$package.$keyroot;
11905: 		    }
11906: 		    foreach my $pack_entry (keys(%packagetab)) {
11907: 			my $part=$keyroot;
11908: 			$part=~s/^\_//;
11909: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11910: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11911: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11912: 			    # ignore package.tab specified default values
11913:                             # here &package_tab_default() will fetch those
11914: 			    if ($subp eq 'default') { next; }
11915: 			    my $value=$packagetab{$pack_entry};
11916: 			    my $unikey;
11917: 			    if ($pack =~ /_0$/) {
11918: 				$unikey='parameter_0_'.$name;
11919: 				$part=0;
11920: 			    } else {
11921: 				$unikey='parameter'.$keyroot.'_'.$name;
11922: 			    }
11923: 			    if ($subp eq 'display') {
11924: 				$value.=' [Part: '.$part.']';
11925: 			    }
11926: 			    $metaentry{':'.$unikey.'.part'}=$part;
11927: 			    $metathesekeys{$unikey}=1;
11928: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11929: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11930: 			    }
11931: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11932: 				$metaentry{':'.$unikey}=
11933: 				    $metaentry{':'.$unikey.'.default'};
11934: 			    }
11935: 			}
11936: 		    }
11937: 		} else {
11938: #
11939: # This is not a package - some other kind of start tag
11940: #
11941: 		    my $entry=$token->[1];
11942: 		    my $unikey='';
11943: 
11944: 		    if ($entry eq 'import') {
11945: #
11946: # Importing a library here
11947: #
11948:                         my $location=$parser->get_text('/import');
11949:                         my $dir=$filename;
11950:                         $dir=~s|[^/]*$||;
11951:                         $location=&filelocation($dir,$location);
11952: 
11953:                         my $importid=$token->[2]->{'id'};
11954:                         my $importmode=$token->[2]->{'importmode'};
11955: #
11956: # Check metadata for imported file to
11957: # see if it contained response items
11958: #
11959:                         my ($origfile,@libfilekeys);
11960:                         my %currmetaentry = %metaentry;
11961:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
11962:                                                            $depthcount+1));
11963:                         if (grep(/^responseorder$/,@libfilekeys)) {
11964:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
11965:                                                              undef,$depthcount+1);
11966:                             if ($libresponseorder ne '') {
11967:                                 if ($#origfiletagids<0) {
11968:                                     undef(%importedrespids);
11969:                                     undef(%importedpartids);
11970:                                 }
11971:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
11972:                                 if (@respids) {
11973:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
11974:                                 }
11975:                                 if ($importedrespids{$importid} ne '') {
11976:                                     $importedresponses = 1;
11977: # We need to get the original file and the imported file to get the response order correct
11978: # Load and inspect original file
11979:                                     if ($#origfiletagids<0) {
11980:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11981:                                         $origfile=&getfile($origfilelocation);
11982:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11983:                                     }
11984:                                 }
11985:                             }
11986:                         }
11987: # Do not overwrite contents of %metaentry hash for resource itself with 
11988: # hash populated for imported library file
11989:                         %metaentry = %currmetaentry;
11990:                         undef(%currmetaentry);
11991:                         if ($importmode eq 'part') {
11992: # Import as part(s)
11993:                            $importedparts=1;
11994: # We need to get the original file and the imported file to get the part order correct
11995: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11996: # Load and inspect original file if we didn't do that already
11997:                            if ($#origfiletagids<0) {
11998:                                undef(%importedrespids);
11999:                                undef(%importedpartids);
12000:                                if ($origfile eq '') {
12001:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12002:                                    $origfile=&getfile($origfilelocation);
12003:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12004:                                }
12005:                            }
12006:                            my @impfilepartids;
12007: # If <partorder> tag is included in metadata for the imported file
12008: # get the parts in the imported file from that.
12009:                            if (grep(/^partorder$/,@libfilekeys)) {
12010:                                %currmetaentry = %metaentry;
12011:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12012:                                                             $depthcount+1);
12013:                                %metaentry = %currmetaentry;
12014:                                undef(%currmetaentry);
12015:                                if ($libpartorder ne '') {
12016:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12017:                                }
12018:                            } else {
12019: # If no <partorder> tag available, load and inspect imported file
12020:                                my $impfile=&getfile($location);
12021:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12022:                            }
12023:                            if ($#impfilepartids>=0) {
12024: # This problem had parts
12025:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12026:                            } else {
12027: # Importing by turning a single problem into a problem part
12028: # It gets the import-tags ID as part-ID
12029:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12030:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12031:                            }
12032:                         } else {
12033: # Import as problem or as normal import
12034:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12035:                             unless ($importmode eq 'problem') {
12036: # Normal import
12037:                                 if (defined($token->[2]->{'id'})) {
12038:                                     $unikey.='_'.$token->[2]->{'id'};
12039:                                 }
12040:                             }
12041: # Check metadata for imported file to
12042: # see if it contained parts
12043:                             if (grep(/^partorder$/,@libfilekeys)) {
12044:                                 %currmetaentry = %metaentry;
12045:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12046:                                                              $depthcount+1);
12047:                                 %metaentry = %currmetaentry;
12048:                                 undef(%currmetaentry);
12049:                                 if ($libpartorder ne '') {
12050:                                     $importedparts = 1;
12051:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12052:                                 }
12053:                             }
12054:                         }
12055: 			if ($depthcount<20) {
12056: 			    my $metadata = 
12057: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12058: 					  $depthcount+1);
12059: 			    foreach my $meta (split(',',$metadata)) {
12060: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12061: 				$metathesekeys{$meta}=1;
12062: 			    }
12063:                         }
12064: 		    } else {
12065: #
12066: # Not importing, some other kind of non-package, non-library start tag
12067: # 
12068:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12069:                         if (defined($token->[2]->{'id'})) {
12070:                             $unikey.='_'.$token->[2]->{'id'};
12071:                         }
12072: 			if (defined($token->[2]->{'name'})) { 
12073: 			    $unikey.='_'.$token->[2]->{'name'}; 
12074: 			}
12075: 			$metathesekeys{$unikey}=1;
12076: 			foreach my $param (@{$token->[3]}) {
12077: 			    $metaentry{':'.$unikey.'.'.$param} =
12078: 				$token->[2]->{$param};
12079: 			}
12080: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12081: 			my $default=$metaentry{':'.$unikey.'.default'};
12082: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12083: 		 # only ws inside the tag, and not in default, so use default
12084: 		 # as value
12085: 			    $metaentry{':'.$unikey}=$default;
12086: 			} elsif ( $internaltext =~ /\S/ ) {
12087: 		  # something interesting inside the tag
12088: 			    $metaentry{':'.$unikey}=$internaltext;
12089: 			} else {
12090: 		  # no interesting values, don't set a default
12091: 			}
12092: # end of not-a-package not-a-library import
12093: 		    }
12094: # end of not-a-package start tag
12095: 		}
12096: # the next is the end of "start tag"
12097: 	    }
12098: 	}
12099: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12100: 	$extension = lc($extension);
12101: 	if ($extension eq 'htm') { $extension='html'; }
12102: 
12103: 	foreach my $key (keys(%packagetab)) {
12104: 	    #no specific packages #how's our extension
12105: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12106: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12107: 					 \%metathesekeys);
12108: 	}
12109: 
12110: 	if (!exists($metaentry{':packages'})
12111: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12112: 	    foreach my $key (keys(%packagetab)) {
12113: 		#no specific packages well let's get default then
12114: 		if ($key!~/^default&/) { next; }
12115: 		&metadata_create_package_def($uri,$key,'default',
12116: 					     \%metathesekeys);
12117: 	    }
12118: 	}
12119: # are there custom rights to evaluate
12120: 	if ($metaentry{':copyright'} eq 'custom') {
12121: 
12122:     #
12123:     # Importing a rights file here
12124:     #
12125: 	    unless ($depthcount) {
12126: 		my $location=$metaentry{':customdistributionfile'};
12127: 		my $dir=$filename;
12128: 		$dir=~s|[^/]*$||;
12129: 		$location=&filelocation($dir,$location);
12130: 		my $rights_metadata =
12131: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12132: 			      $depthcount+1);
12133: 		foreach my $rights (split(',',$rights_metadata)) {
12134: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12135: 		    $metathesekeys{$rights}=1;
12136: 		}
12137: 	    }
12138: 	}
12139: 	# uniqifiy package listing
12140: 	my %seen;
12141: 	my @uniq_packages =
12142: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12143: 	$metaentry{':packages'} = join(',',@uniq_packages);
12144: 
12145:         if (($importedresponses) || ($importedparts)) {
12146:             if ($importedparts) {
12147: # We had imported parts and need to rebuild partorder
12148:                 $metaentry{':partorder'}='';
12149:                 $metathesekeys{'partorder'}=1;
12150:             }
12151:             if ($importedresponses) {
12152: # We had imported responses and need to rebuil responseorder
12153:                 $metaentry{':responseorder'}='';
12154:                 $metathesekeys{'responseorder'}=1;
12155:             }
12156:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12157:                 my $origid = $origfiletagids[$index+1];
12158:                 if ($origfiletagids[$index] eq 'part') {
12159: # Original part, part of the problem
12160:                     if ($importedparts) {
12161:                         $metaentry{':partorder'}.=','.$origid;
12162:                     }
12163:                 } elsif ($origfiletagids[$index] eq 'import') {
12164:                     if ($importedparts) {
12165: # We have imported parts at this position
12166:                         if ($importedpartids{$origid} ne '') {
12167:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12168:                         }
12169:                     }
12170:                     if ($importedresponses) {
12171: # We have imported responses at this position
12172:                         if ($importedrespids{$origid} ne '') {
12173:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12174:                         }
12175:                     }
12176:                 } else {
12177: # Original response item, part of the problem
12178:                     if ($importedresponses) {
12179:                         $metaentry{':responseorder'}.=','.$origid;
12180:                     }
12181:                 }
12182:             }
12183:             if ($importedparts) {
12184:                 $metaentry{':partorder'}=~s/^\,//;
12185:             }
12186:             if ($importedresponses) {
12187:                 $metaentry{':responseorder'}=~s/^\,//;
12188:             }
12189:         }
12190: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12191: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12192: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12193:         unless ($liburi) {
12194: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12195:         }
12196: # this is the end of "was not already recently cached
12197:     }
12198:     return $metaentry{':'.$what};
12199: }
12200: 
12201: sub metadata_create_package_def {
12202:     my ($uri,$key,$package,$metathesekeys)=@_;
12203:     my ($pack,$name,$subp)=split(/\&/,$key);
12204:     if ($subp eq 'default') { next; }
12205:     
12206:     if (defined($metaentry{':packages'})) {
12207: 	$metaentry{':packages'}.=','.$package;
12208:     } else {
12209: 	$metaentry{':packages'}=$package;
12210:     }
12211:     my $value=$packagetab{$key};
12212:     my $unikey;
12213:     $unikey='parameter_0_'.$name;
12214:     $metaentry{':'.$unikey.'.part'}=0;
12215:     $$metathesekeys{$unikey}=1;
12216:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12217: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12218:     }
12219:     if (defined($metaentry{':'.$unikey.'.default'})) {
12220: 	$metaentry{':'.$unikey}=
12221: 	    $metaentry{':'.$unikey.'.default'};
12222:     }
12223: }
12224: 
12225: sub metadata_generate_part0 {
12226:     my ($metadata,$metacache,$uri) = @_;
12227:     my %allnames;
12228:     foreach my $metakey (keys(%$metadata)) {
12229: 	if ($metakey=~/^parameter\_(.*)/) {
12230: 	  my $part=$$metacache{':'.$metakey.'.part'};
12231: 	  my $name=$$metacache{':'.$metakey.'.name'};
12232: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12233: 	    $allnames{$name}=$part;
12234: 	  }
12235: 	}
12236:     }
12237:     foreach my $name (keys(%allnames)) {
12238:       $$metadata{"parameter_0_$name"}=1;
12239:       my $key=":parameter_0_$name";
12240:       $$metacache{"$key.part"}='0';
12241:       $$metacache{"$key.name"}=$name;
12242:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12243: 					   $allnames{$name}.'_'.$name.
12244: 					   '.type'};
12245:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12246: 			     '.display'};
12247:       my $expr='[Part: '.$allnames{$name}.']';
12248:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12249:       $$metacache{"$key.display"}=$olddis;
12250:     }
12251: }
12252: 
12253: # ------------------------------------------------------ Devalidate title cache
12254: 
12255: sub devalidate_title_cache {
12256:     my ($url)=@_;
12257:     if (!$env{'request.course.id'}) { return; }
12258:     my $symb=&symbread($url);
12259:     if (!$symb) { return; }
12260:     my $key=$env{'request.course.id'}."\0".$symb;
12261:     &devalidate_cache_new('title',$key);
12262: }
12263: 
12264: # ------------------------------------------------- Get the title of a course
12265: 
12266: sub current_course_title {
12267:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12268: }
12269: # ------------------------------------------------- Get the title of a resource
12270: 
12271: sub gettitle {
12272:     my $urlsymb=shift;
12273:     my $symb=&symbread($urlsymb);
12274:     if ($symb) {
12275: 	my $key=$env{'request.course.id'}."\0".$symb;
12276: 	my ($result,$cached)=&is_cached_new('title',$key);
12277: 	if (defined($cached)) { 
12278: 	    return $result;
12279: 	}
12280: 	my ($map,$resid,$url)=&decode_symb($symb);
12281: 	my $title='';
12282: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12283: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12284: 	} else {
12285: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12286: 		    &GDBM_READER(),0640)) {
12287: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12288: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12289: 		untie(%bighash);
12290: 	    }
12291: 	}
12292: 	$title=~s/\&colon\;/\:/gs;
12293: 	if ($title) {
12294: # Remember both $symb and $title for dynamic metadata
12295:             $accesshash{$symb.'___crstitle'}=$title;
12296:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12297: # Cache this title and then return it
12298: 	    return &do_cache_new('title',$key,$title,600);
12299: 	}
12300: 	$urlsymb=$url;
12301:     }
12302:     my $title=&metadata($urlsymb,'title');
12303:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12304:     return $title;
12305: }
12306: 
12307: sub get_slot {
12308:     my ($which,$cnum,$cdom)=@_;
12309:     if (!$cnum || !$cdom) {
12310: 	(undef,my $courseid)=&whichuser();
12311: 	$cdom=$env{'course.'.$courseid.'.domain'};
12312: 	$cnum=$env{'course.'.$courseid.'.num'};
12313:     }
12314:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12315:     my %slotinfo;
12316:     if (exists($remembered{$key})) {
12317: 	$slotinfo{$which} = $remembered{$key};
12318:     } else {
12319: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12320: 	&Apache::lonhomework::showhash(%slotinfo);
12321: 	my ($tmp)=keys(%slotinfo);
12322: 	if ($tmp=~/^error:/) { return (); }
12323: 	$remembered{$key} = $slotinfo{$which};
12324:     }
12325:     if (ref($slotinfo{$which}) eq 'HASH') {
12326: 	return %{$slotinfo{$which}};
12327:     }
12328:     return $slotinfo{$which};
12329: }
12330: 
12331: sub get_reservable_slots {
12332:     my ($cnum,$cdom,$uname,$udom) = @_;
12333:     my $now = time;
12334:     my $reservable_info;
12335:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12336:     if (exists($remembered{$key})) {
12337:         $reservable_info = $remembered{$key};
12338:     } else {
12339:         my %resv;
12340:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12341:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12342:         $reservable_info = \%resv;
12343:         $remembered{$key} = $reservable_info;
12344:     }
12345:     return $reservable_info;
12346: }
12347: 
12348: sub get_course_slots {
12349:     my ($cnum,$cdom) = @_;
12350:     my $hashid=$cnum.':'.$cdom;
12351:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12352:     if (defined($cached)) {
12353:         if (ref($result) eq 'HASH') {
12354:             return %{$result};
12355:         }
12356:     } else {
12357:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12358:         my ($tmp) = keys(%slots);
12359:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12360:             &do_cache_new('allslots',$hashid,\%slots,600);
12361:             return %slots;
12362:         }
12363:     }
12364:     return;
12365: }
12366: 
12367: sub devalidate_slots_cache {
12368:     my ($cnum,$cdom)=@_;
12369:     my $hashid=$cnum.':'.$cdom;
12370:     &devalidate_cache_new('allslots',$hashid);
12371: }
12372: 
12373: sub get_coursechange {
12374:     my ($cdom,$cnum) = @_;
12375:     if ($cdom eq '' || $cnum eq '') {
12376:         return unless ($env{'request.course.id'});
12377:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12378:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12379:     }
12380:     my $hashid=$cdom.'_'.$cnum;
12381:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12382:     if ((defined($cached)) && ($change ne '')) {
12383:         return $change;
12384:     } else {
12385:         my %crshash;
12386:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12387:         if ($crshash{'internal.contentchange'} eq '') {
12388:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12389:             if ($change eq '') {
12390:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12391:                 $change = $crshash{'internal.created'};
12392:             }
12393:         } else {
12394:             $change = $crshash{'internal.contentchange'};
12395:         }
12396:         my $cachetime = 600;
12397:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12398:     }
12399:     return $change;
12400: }
12401: 
12402: sub devalidate_coursechange_cache {
12403:     my ($cnum,$cdom)=@_;
12404:     my $hashid=$cnum.':'.$cdom;
12405:     &devalidate_cache_new('crschange',$hashid);
12406: }
12407: 
12408: # ------------------------------------------------- Update symbolic store links
12409: 
12410: sub symblist {
12411:     my ($mapname,%newhash)=@_;
12412:     $mapname=&deversion(&declutter($mapname));
12413:     my %hash;
12414:     if (($env{'request.course.fn'}) && (%newhash)) {
12415:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12416:                       &GDBM_WRCREAT(),0640)) {
12417: 	    foreach my $url (keys(%newhash)) {
12418: 		next if ($url eq 'last_known'
12419: 			 && $env{'form.no_update_last_known'});
12420: 		$hash{declutter($url)}=&encode_symb($mapname,
12421: 						    $newhash{$url}->[1],
12422: 						    $newhash{$url}->[0]);
12423:             }
12424:             if (untie(%hash)) {
12425: 		return 'ok';
12426:             }
12427:         }
12428:     }
12429:     return 'error';
12430: }
12431: 
12432: # --------------------------------------------------------------- Verify a symb
12433: 
12434: sub symbverify {
12435:     my ($symb,$thisurl,$encstate)=@_;
12436:     my $thisfn=$thisurl;
12437:     $thisfn=&declutter($thisfn);
12438: # direct jump to resource in page or to a sequence - will construct own symbs
12439:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12440: # check URL part
12441:     my ($map,$resid,$url)=&decode_symb($symb);
12442: 
12443:     unless ($url eq $thisfn) { return 0; }
12444: 
12445:     $symb=&symbclean($symb);
12446:     $thisurl=&deversion($thisurl);
12447:     $thisfn=&deversion($thisfn);
12448: 
12449:     my %bighash;
12450:     my $okay=0;
12451: 
12452:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12453:                             &GDBM_READER(),0640)) {
12454:         my $noclutter;
12455:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12456:             $thisurl =~ s/\?.+$//;
12457:             if ($map =~ m{^uploaded/.+\.page$}) {
12458:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12459:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12460:                 $noclutter = 1;
12461:             }
12462:         }
12463:         my $ids;
12464:         if ($noclutter) {
12465:             $ids=$bighash{'ids_'.$thisurl};
12466:         } else {
12467:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12468:         }
12469:         unless ($ids) {
12470:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12471:             $ids=$bighash{$idkey};
12472:         }
12473:         if ($ids) {
12474: # ------------------------------------------------------------------- Has ID(s)
12475:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12476:                 $symb =~ s/\?.+$//;
12477:             }
12478: 	    foreach my $id (split(/\,/,$ids)) {
12479: 	       my ($mapid,$resid)=split(/\./,$id);
12480:                if (
12481:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12482:    eq $symb) {
12483:                    if (ref($encstate)) {
12484:                        $$encstate = $bighash{'encrypted_'.$id};
12485:                    }
12486: 		   if (($env{'request.role.adv'}) ||
12487: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12488:                        ($thisurl eq '/adm/navmaps')) {
12489: 		       $okay=1;
12490:                        last;
12491: 		   }
12492: 	       }
12493: 	   }
12494:         }
12495: 	untie(%bighash);
12496:     }
12497:     return $okay;
12498: }
12499: 
12500: # --------------------------------------------------------------- Clean-up symb
12501: 
12502: sub symbclean {
12503:     my $symb=shift;
12504:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12505: # remove version from map
12506:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12507: 
12508: # remove version from URL
12509:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12510: 
12511: # remove wrapper
12512: 
12513:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12514:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12515:     return $symb;
12516: }
12517: 
12518: # ---------------------------------------------- Split symb to find map and url
12519: 
12520: sub encode_symb {
12521:     my ($map,$resid,$url)=@_;
12522:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12523: }
12524: 
12525: sub decode_symb {
12526:     my $symb=shift;
12527:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12528:     my ($map,$resid,$url)=split(/___/,$symb);
12529:     return (&fixversion($map),$resid,&fixversion($url));
12530: }
12531: 
12532: sub fixversion {
12533:     my $fn=shift;
12534:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12535:     my %bighash;
12536:     my $uri=&clutter($fn);
12537:     my $key=$env{'request.course.id'}.'_'.$uri;
12538: # is this cached?
12539:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12540:     if (defined($cached)) { return $result; }
12541: # unfortunately not cached, or expired
12542:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12543: 	    &GDBM_READER(),0640)) {
12544:  	if ($bighash{'version_'.$uri}) {
12545:  	    my $version=$bighash{'version_'.$uri};
12546:  	    unless (($version eq 'mostrecent') || 
12547: 		    ($version==&getversion($uri))) {
12548:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12549:  	    }
12550:  	}
12551:  	untie %bighash;
12552:     }
12553:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12554: }
12555: 
12556: sub deversion {
12557:     my $url=shift;
12558:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12559:     return $url;
12560: }
12561: 
12562: # ------------------------------------------------------ Return symb list entry
12563: 
12564: sub symbread {
12565:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12566:     my $cache_str='request.symbread.cached.'.$thisfn;
12567:     if (defined($env{$cache_str})) {
12568:         if ($ignorecachednull) {
12569:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12570:         } else {
12571:             return $env{$cache_str};
12572:         }
12573:     }
12574: # no filename provided? try from environment
12575:     unless ($thisfn) {
12576:         if ($env{'request.symb'}) {
12577: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12578: 	}
12579: 	$thisfn=$env{'request.filename'};
12580:     }
12581:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12582: # is that filename actually a symb? Verify, clean, and return
12583:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12584: 	if (&symbverify($thisfn,$1)) {
12585: 	    return $env{$cache_str}=&symbclean($thisfn);
12586: 	}
12587:     }
12588:     $thisfn=declutter($thisfn);
12589:     my %hash;
12590:     my %bighash;
12591:     my $syval='';
12592:     if (($env{'request.course.fn'}) && ($thisfn)) {
12593:         my $targetfn = $thisfn;
12594:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12595:             $targetfn = 'adm/wrapper/'.$thisfn;
12596:         }
12597: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12598: 	    $targetfn=$1;
12599: 	}
12600:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12601:                       &GDBM_READER(),0640)) {
12602: 	    $syval=$hash{$targetfn};
12603:             untie(%hash);
12604:         }
12605: # ---------------------------------------------------------- There was an entry
12606:         if ($syval) {
12607: 	    #unless ($syval=~/\_\d+$/) {
12608: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12609: 		    #&appenv({'request.ambiguous' => $thisfn});
12610: 		    #return $env{$cache_str}='';
12611: 		#}    
12612: 		#$syval.=$1;
12613: 	    #}
12614:         } else {
12615: # ------------------------------------------------------- Was not in symb table
12616:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12617:                             &GDBM_READER(),0640)) {
12618: # ---------------------------------------------- Get ID(s) for current resource
12619:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12620:               unless ($ids) { 
12621:                  $ids=$bighash{'ids_/'.$thisfn};
12622:               }
12623:               unless ($ids) {
12624: # alias?
12625: 		  $ids=$bighash{'mapalias_'.$thisfn};
12626:               }
12627:               if ($ids) {
12628: # ------------------------------------------------------------------- Has ID(s)
12629:                  my @possibilities=split(/\,/,$ids);
12630:                  if ($#possibilities==0) {
12631: # ----------------------------------------------- There is only one possibility
12632: 		     my ($mapid,$resid)=split(/\./,$ids);
12633: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12634: 						    $resid,$thisfn);
12635:                      if (ref($possibles) eq 'HASH') {
12636:                          $possibles->{$syval} = 1;    
12637:                      }
12638:                      if ($checkforblock) {
12639:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12640:                          if (@blockers) {
12641:                              $syval = '';
12642:                              return;
12643:                          }
12644:                      }
12645:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12646: # ------------------------------------------ There is more than one possibility
12647:                      my $realpossible=0;
12648:                      foreach my $id (@possibilities) {
12649: 			 my $file=$bighash{'src_'.$id};
12650:                          my $canaccess;
12651:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12652:                              $canaccess = 1;
12653:                          } else { 
12654:                              $canaccess = &allowed('bre',$file);
12655:                          }
12656:                          if ($canaccess) {
12657:          		     my ($mapid,$resid)=split(/\./,$id);
12658:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12659:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12660: 						             $resid,$thisfn);
12661:                                  if (ref($possibles) eq 'HASH') {
12662:                                      $possibles->{$syval} = 1;
12663:                                  }
12664:                                  if ($checkforblock) {
12665:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12666:                                      unless (@blockers > 0) {
12667:                                          $syval = $poss_syval;
12668:                                          $realpossible++;
12669:                                      }
12670:                                  } else {
12671:                                      $syval = $poss_syval;
12672:                                      $realpossible++;
12673:                                  }
12674:                              }
12675: 			 }
12676:                      }
12677: 		     if ($realpossible!=1) { $syval=''; }
12678:                  } else {
12679:                      $syval='';
12680:                  }
12681: 	      }
12682:               untie(%bighash);
12683:            }
12684:         }
12685:         if ($syval) {
12686: 	    return $env{$cache_str}=$syval;
12687:         }
12688:     }
12689:     &appenv({'request.ambiguous' => $thisfn});
12690:     return $env{$cache_str}='';
12691: }
12692: 
12693: # ---------------------------------------------------------- Return random seed
12694: 
12695: sub numval {
12696:     my $txt=shift;
12697:     $txt=~tr/A-J/0-9/;
12698:     $txt=~tr/a-j/0-9/;
12699:     $txt=~tr/K-T/0-9/;
12700:     $txt=~tr/k-t/0-9/;
12701:     $txt=~tr/U-Z/0-5/;
12702:     $txt=~tr/u-z/0-5/;
12703:     $txt=~s/\D//g;
12704:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12705:     return int($txt);
12706: }
12707: 
12708: sub numval2 {
12709:     my $txt=shift;
12710:     $txt=~tr/A-J/0-9/;
12711:     $txt=~tr/a-j/0-9/;
12712:     $txt=~tr/K-T/0-9/;
12713:     $txt=~tr/k-t/0-9/;
12714:     $txt=~tr/U-Z/0-5/;
12715:     $txt=~tr/u-z/0-5/;
12716:     $txt=~s/\D//g;
12717:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12718:     my $total;
12719:     foreach my $val (@txts) { $total+=$val; }
12720:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12721:     return int($total);
12722: }
12723: 
12724: sub numval3 {
12725:     use integer;
12726:     my $txt=shift;
12727:     $txt=~tr/A-J/0-9/;
12728:     $txt=~tr/a-j/0-9/;
12729:     $txt=~tr/K-T/0-9/;
12730:     $txt=~tr/k-t/0-9/;
12731:     $txt=~tr/U-Z/0-5/;
12732:     $txt=~tr/u-z/0-5/;
12733:     $txt=~s/\D//g;
12734:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12735:     my $total;
12736:     foreach my $val (@txts) { $total+=$val; }
12737:     if ($_64bit) { $total=(($total<<32)>>32); }
12738:     return $total;
12739: }
12740: 
12741: sub digest {
12742:     my ($data)=@_;
12743:     my $digest=&Digest::MD5::md5($data);
12744:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12745:     my ($e,$f);
12746:     {
12747:         use integer;
12748:         $e=($a+$b);
12749:         $f=($c+$d);
12750:         if ($_64bit) {
12751:             $e=(($e<<32)>>32);
12752:             $f=(($f<<32)>>32);
12753:         }
12754:     }
12755:     if (wantarray) {
12756: 	return ($e,$f);
12757:     } else {
12758: 	my $g;
12759: 	{
12760: 	    use integer;
12761: 	    $g=($e+$f);
12762: 	    if ($_64bit) {
12763: 		$g=(($g<<32)>>32);
12764: 	    }
12765: 	}
12766: 	return $g;
12767:     }
12768: }
12769: 
12770: sub latest_rnd_algorithm_id {
12771:     return '64bit5';
12772: }
12773: 
12774: sub get_rand_alg {
12775:     my ($courseid)=@_;
12776:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12777:     if ($courseid) {
12778: 	return $env{"course.$courseid.rndseed"};
12779:     }
12780:     return &latest_rnd_algorithm_id();
12781: }
12782: 
12783: sub validCODE {
12784:     my ($CODE)=@_;
12785:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12786:     return 0;
12787: }
12788: 
12789: sub getCODE {
12790:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12791:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12792: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12793: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12794: 	return $Apache::lonhomework::history{'resource.CODE'};
12795:     }
12796:     return undef;
12797: }
12798: #
12799: #  Determines the random seed for a specific context:
12800: #
12801: # parameters:
12802: #   symb      - in course context the symb for the seed.
12803: #   course_id - The course id of the form domain_coursenum.
12804: #   domain    - Domain for the user.
12805: #   course    - Course for the user.
12806: #   cenv      - environment of the course.
12807: #
12808: # NOTE:
12809: #   All parameters are picked out of the environment if missing
12810: #   or not defined.
12811: #   If a symb cannot be determined the current time is used instead.
12812: #
12813: #  For a given well defined symb, courside, domain, username,
12814: #  and course environment, the seed is reproducible.
12815: #
12816: sub rndseed {
12817:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12818:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12819:     if (!defined($symb)) {
12820: 	unless ($symb=$wsymb) { return time; }
12821:     }
12822:     if (!defined $courseid) { 
12823: 	$courseid=$wcourseid; 
12824:     }
12825:     if (!defined $domain) { $domain=$wdomain; }
12826:     if (!defined $username) { $username=$wusername }
12827: 
12828:     my $which;
12829:     if (defined($cenv->{'rndseed'})) {
12830: 	$which = $cenv->{'rndseed'};
12831:     } else {
12832: 	$which =&get_rand_alg($courseid);
12833:     }
12834:     if (defined(&getCODE())) {
12835: 
12836: 	if ($which eq '64bit5') {
12837: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12838: 	} elsif ($which eq '64bit4') {
12839: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12840: 	} else {
12841: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12842: 	}
12843:     } elsif ($which eq '64bit5') {
12844: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12845:     } elsif ($which eq '64bit4') {
12846: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12847:     } elsif ($which eq '64bit3') {
12848: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12849:     } elsif ($which eq '64bit2') {
12850: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12851:     } elsif ($which eq '64bit') {
12852: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12853:     }
12854:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12855: }
12856: 
12857: sub rndseed_32bit {
12858:     my ($symb,$courseid,$domain,$username)=@_;
12859:     {
12860: 	use integer;
12861: 	my $symbchck=unpack("%32C*",$symb) << 27;
12862: 	my $symbseed=numval($symb) << 22;
12863: 	my $namechck=unpack("%32C*",$username) << 17;
12864: 	my $nameseed=numval($username) << 12;
12865: 	my $domainseed=unpack("%32C*",$domain) << 7;
12866: 	my $courseseed=unpack("%32C*",$courseid);
12867: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12868: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12869: 	#&logthis("rndseed :$num:$symb");
12870: 	if ($_64bit) { $num=(($num<<32)>>32); }
12871: 	return $num;
12872:     }
12873: }
12874: 
12875: sub rndseed_64bit {
12876:     my ($symb,$courseid,$domain,$username)=@_;
12877:     {
12878: 	use integer;
12879: 	my $symbchck=unpack("%32S*",$symb) << 21;
12880: 	my $symbseed=numval($symb) << 10;
12881: 	my $namechck=unpack("%32S*",$username);
12882: 	
12883: 	my $nameseed=numval($username) << 21;
12884: 	my $domainseed=unpack("%32S*",$domain) << 10;
12885: 	my $courseseed=unpack("%32S*",$courseid);
12886: 	
12887: 	my $num1=$symbchck+$symbseed+$namechck;
12888: 	my $num2=$nameseed+$domainseed+$courseseed;
12889: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12890: 	#&logthis("rndseed :$num:$symb");
12891: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12892: 	return "$num1,$num2";
12893:     }
12894: }
12895: 
12896: sub rndseed_64bit2 {
12897:     my ($symb,$courseid,$domain,$username)=@_;
12898:     {
12899: 	use integer;
12900: 	# strings need to be an even # of cahracters long, it it is odd the
12901:         # last characters gets thrown away
12902: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12903: 	my $symbseed=numval($symb) << 10;
12904: 	my $namechck=unpack("%32S*",$username.' ');
12905: 	
12906: 	my $nameseed=numval($username) << 21;
12907: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12908: 	my $courseseed=unpack("%32S*",$courseid.' ');
12909: 	
12910: 	my $num1=$symbchck+$symbseed+$namechck;
12911: 	my $num2=$nameseed+$domainseed+$courseseed;
12912: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12913: 	#&logthis("rndseed :$num:$symb");
12914: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12915: 	return "$num1,$num2";
12916:     }
12917: }
12918: 
12919: sub rndseed_64bit3 {
12920:     my ($symb,$courseid,$domain,$username)=@_;
12921:     {
12922: 	use integer;
12923: 	# strings need to be an even # of cahracters long, it it is odd the
12924:         # last characters gets thrown away
12925: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12926: 	my $symbseed=numval2($symb) << 10;
12927: 	my $namechck=unpack("%32S*",$username.' ');
12928: 	
12929: 	my $nameseed=numval2($username) << 21;
12930: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12931: 	my $courseseed=unpack("%32S*",$courseid.' ');
12932: 	
12933: 	my $num1=$symbchck+$symbseed+$namechck;
12934: 	my $num2=$nameseed+$domainseed+$courseseed;
12935: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12936: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12937: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12938: 	
12939: 	return "$num1:$num2";
12940:     }
12941: }
12942: 
12943: sub rndseed_64bit4 {
12944:     my ($symb,$courseid,$domain,$username)=@_;
12945:     {
12946: 	use integer;
12947: 	# strings need to be an even # of cahracters long, it it is odd the
12948:         # last characters gets thrown away
12949: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12950: 	my $symbseed=numval3($symb) << 10;
12951: 	my $namechck=unpack("%32S*",$username.' ');
12952: 	
12953: 	my $nameseed=numval3($username) << 21;
12954: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12955: 	my $courseseed=unpack("%32S*",$courseid.' ');
12956: 	
12957: 	my $num1=$symbchck+$symbseed+$namechck;
12958: 	my $num2=$nameseed+$domainseed+$courseseed;
12959: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12960: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12961: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12962: 	
12963: 	return "$num1:$num2";
12964:     }
12965: }
12966: 
12967: sub rndseed_64bit5 {
12968:     my ($symb,$courseid,$domain,$username)=@_;
12969:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12970:     return "$num1:$num2";
12971: }
12972: 
12973: sub rndseed_CODE_64bit {
12974:     my ($symb,$courseid,$domain,$username)=@_;
12975:     {
12976: 	use integer;
12977: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12978: 	my $symbseed=numval2($symb);
12979: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12980: 	my $CODEseed=numval(&getCODE());
12981: 	my $courseseed=unpack("%32S*",$courseid.' ');
12982: 	my $num1=$symbseed+$CODEchck;
12983: 	my $num2=$CODEseed+$courseseed+$symbchck;
12984: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12985: 	#&logthis("rndseed :$num1:$num2:$symb");
12986: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12987: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12988: 	return "$num1:$num2";
12989:     }
12990: }
12991: 
12992: sub rndseed_CODE_64bit4 {
12993:     my ($symb,$courseid,$domain,$username)=@_;
12994:     {
12995: 	use integer;
12996: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12997: 	my $symbseed=numval3($symb);
12998: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12999: 	my $CODEseed=numval3(&getCODE());
13000: 	my $courseseed=unpack("%32S*",$courseid.' ');
13001: 	my $num1=$symbseed+$CODEchck;
13002: 	my $num2=$CODEseed+$courseseed+$symbchck;
13003: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13004: 	#&logthis("rndseed :$num1:$num2:$symb");
13005: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13006: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13007: 	return "$num1:$num2";
13008:     }
13009: }
13010: 
13011: sub rndseed_CODE_64bit5 {
13012:     my ($symb,$courseid,$domain,$username)=@_;
13013:     my $code = &getCODE();
13014:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13015:     return "$num1:$num2";
13016: }
13017: 
13018: sub setup_random_from_rndseed {
13019:     my ($rndseed)=@_;
13020:     if ($rndseed =~/([,:])/) {
13021:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13022:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13023:             &Math::Random::random_set_seed_from_phrase($rndseed);
13024:         } else {
13025:             &Math::Random::random_set_seed($num1,$num2);
13026:         }
13027:     } else {
13028: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13029:     }
13030: }
13031: 
13032: sub latest_receipt_algorithm_id {
13033:     return 'receipt3';
13034: }
13035: 
13036: sub recunique {
13037:     my $fucourseid=shift;
13038:     my $unique;
13039:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13040: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13041: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13042:     } else {
13043: 	$unique=$perlvar{'lonReceipt'};
13044:     }
13045:     return unpack("%32C*",$unique);
13046: }
13047: 
13048: sub recprefix {
13049:     my $fucourseid=shift;
13050:     my $prefix;
13051:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13052: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13053: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13054:     } else {
13055: 	$prefix=$perlvar{'lonHostID'};
13056:     }
13057:     return unpack("%32C*",$prefix);
13058: }
13059: 
13060: sub ireceipt {
13061:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13062: 
13063:     my $return =&recprefix($fucourseid).'-';
13064: 
13065:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13066: 	$env{'request.state'} eq 'construct') {
13067: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13068: 	return $return;
13069:     }
13070: 
13071:     my $cuname=unpack("%32C*",$funame);
13072:     my $cudom=unpack("%32C*",$fudom);
13073:     my $cucourseid=unpack("%32C*",$fucourseid);
13074:     my $cusymb=unpack("%32C*",$fusymb);
13075:     my $cunique=&recunique($fucourseid);
13076:     my $cpart=unpack("%32S*",$part);
13077:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13078: 
13079: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13080: 			       
13081: 	$return.= ($cunique%$cuname+
13082: 		   $cunique%$cudom+
13083: 		   $cusymb%$cuname+
13084: 		   $cusymb%$cudom+
13085: 		   $cucourseid%$cuname+
13086: 		   $cucourseid%$cudom+
13087: 		   $cpart%$cuname+
13088: 		   $cpart%$cudom);
13089:     } else {
13090: 	$return.= ($cunique%$cuname+
13091: 		   $cunique%$cudom+
13092: 		   $cusymb%$cuname+
13093: 		   $cusymb%$cudom+
13094: 		   $cucourseid%$cuname+
13095: 		   $cucourseid%$cudom);
13096:     }
13097:     return $return;
13098: }
13099: 
13100: sub receipt {
13101:     my ($part)=@_;
13102:     my ($symb,$courseid,$domain,$name) = &whichuser();
13103:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13104: }
13105: 
13106: sub whichuser {
13107:     my ($passedsymb)=@_;
13108:     my ($symb,$courseid,$domain,$name,$publicuser);
13109:     if (defined($env{'form.grade_symb'})) {
13110: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13111: 	my $allowed=&allowed('vgr',$tmp_courseid);
13112: 	if (!$allowed &&
13113: 	    exists($env{'request.course.sec'}) &&
13114: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13115: 	    $allowed=&allowed('vgr',$tmp_courseid.
13116: 			      '/'.$env{'request.course.sec'});
13117: 	}
13118: 	if ($allowed) {
13119: 	    ($symb)=&get_env_multiple('form.grade_symb');
13120: 	    $courseid=$tmp_courseid;
13121: 	    ($domain)=&get_env_multiple('form.grade_domain');
13122: 	    ($name)=&get_env_multiple('form.grade_username');
13123: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13124: 	}
13125:     }
13126:     if (!$passedsymb) {
13127: 	$symb=&symbread();
13128:     } else {
13129: 	$symb=$passedsymb;
13130:     }
13131:     $courseid=$env{'request.course.id'};
13132:     $domain=$env{'user.domain'};
13133:     $name=$env{'user.name'};
13134:     if ($name eq 'public' && $domain eq 'public') {
13135: 	if (!defined($env{'form.username'})) {
13136: 	    $env{'form.username'}.=time.rand(10000000);
13137: 	}
13138: 	$name.=$env{'form.username'};
13139:     }
13140:     return ($symb,$courseid,$domain,$name,$publicuser);
13141: 
13142: }
13143: 
13144: # ------------------------------------------------------------ Serves up a file
13145: # returns either the contents of the file or 
13146: # -1 if the file doesn't exist
13147: #
13148: # if the target is a file that was uploaded via DOCS, 
13149: # a check will be made to see if a current copy exists on the local server,
13150: # if it does this will be served, otherwise a copy will be retrieved from
13151: # the home server for the course and stored in /home/httpd/html/userfiles on
13152: # the local server.   
13153: 
13154: sub getfile {
13155:     my ($file) = @_;
13156:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13157:     &repcopy($file);
13158:     return &readfile($file);
13159: }
13160: 
13161: sub repcopy_userfile {
13162:     my ($file)=@_;
13163:     my $londocroot = $perlvar{'lonDocRoot'};
13164:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13165:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13166:     my ($cdom,$cnum,$filename) = 
13167: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13168:     my $uri="/uploaded/$cdom/$cnum/$filename";
13169:     if (-e "$file") {
13170: # we already have a local copy, check it out
13171: 	my @fileinfo = stat($file);
13172: 	my $rtncode;
13173: 	my $info;
13174: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13175: 	if ($lwpresp ne 'ok') {
13176: # there is no such file anymore, even though we had a local copy
13177: 	    if ($rtncode eq '404') {
13178: 		unlink($file);
13179: 	    }
13180: 	    return -1;
13181: 	}
13182: 	if ($info < $fileinfo[9]) {
13183: # nice, the file we have is up-to-date, just say okay
13184: 	    return 'ok';
13185: 	} else {
13186: # the file is outdated, get rid of it
13187: 	    unlink($file);
13188: 	}
13189:     }
13190: # one way or the other, at this point, we don't have the file
13191: # construct the correct path for the file
13192:     my @parts = ($cdom,$cnum); 
13193:     if ($filename =~ m|^(.+)/[^/]+$|) {
13194: 	push @parts, split(/\//,$1);
13195:     }
13196:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13197:     foreach my $part (@parts) {
13198: 	$path .= '/'.$part;
13199: 	if (!-e $path) {
13200: 	    mkdir($path,0770);
13201: 	}
13202:     }
13203: # now the path exists for sure
13204: # get a user agent
13205:     my $transferfile=$file.'.in.transfer';
13206: # FIXME: this should flock
13207:     if (-e $transferfile) { return 'ok'; }
13208:     my $request;
13209:     $uri=~s/^\///;
13210:     my $homeserver = &homeserver($cnum,$cdom);
13211:     my $protocol = $protocol{$homeserver};
13212:     $protocol = 'http' if ($protocol ne 'https');
13213:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
13214:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13215: # did it work?
13216:     if ($response->is_error()) {
13217: 	unlink($transferfile);
13218: 	&logthis("Userfile repcopy failed for $uri");
13219: 	return -1;
13220:     }
13221: # worked, rename the transfer file
13222:     rename($transferfile,$file);
13223:     return 'ok';
13224: }
13225: 
13226: sub tokenwrapper {
13227:     my $uri=shift;
13228:     $uri=~s|^https?\://([^/]+)||;
13229:     $uri=~s|^/||;
13230:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13231:     my $token=$1;
13232:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13233:     if ($udom && $uname && $file) {
13234: 	$file=~s|(\?\.*)*$||;
13235:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13236:         my $homeserver = &homeserver($uname,$udom);
13237:         my $protocol = $protocol{$homeserver};
13238:         $protocol = 'http' if ($protocol ne 'https');
13239:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
13240:                (($uri=~/\?/)?'&':'?').'token='.$token.
13241:                                '&tokenissued='.$perlvar{'lonHostID'};
13242:     } else {
13243:         return '/adm/notfound.html';
13244:     }
13245: }
13246: 
13247: # call with reqtype HEAD: get last modification time
13248: # call with reqtype GET: get the file contents
13249: # Do not call this with reqtype GET for large files! It loads everything into memory
13250: #
13251: sub getuploaded {
13252:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13253:     $uri=~s/^\///;
13254:     my $homeserver = &homeserver($cnum,$cdom);
13255:     my $protocol = $protocol{$homeserver};
13256:     $protocol = 'http' if ($protocol ne 'https');
13257:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
13258:     my $request=new HTTP::Request($reqtype,$uri);
13259:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13260:     $$rtncode = $response->code;
13261:     if (! $response->is_success()) {
13262: 	return 'failed';
13263:     }      
13264:     if ($reqtype eq 'HEAD') {
13265: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13266:     } elsif ($reqtype eq 'GET') {
13267: 	$$info = $response->content;
13268:     }
13269:     return 'ok';
13270: }
13271: 
13272: sub readfile {
13273:     my $file = shift;
13274:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13275:     my $fh;
13276:     open($fh,"<",$file);
13277:     my $a='';
13278:     while (my $line = <$fh>) { $a .= $line; }
13279:     return $a;
13280: }
13281: 
13282: sub filelocation {
13283:     my ($dir,$file) = @_;
13284:     my $location;
13285:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13286: 
13287:     if ($file =~ m-^/adm/-) {
13288: 	$file=~s-^/adm/wrapper/-/-;
13289: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13290:     }
13291: 
13292:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13293:         $location = $file;
13294:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13295:         my ($udom,$uname,$filename)=
13296:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13297:         my $home=&homeserver($uname,$udom);
13298:         my $is_me=0;
13299:         my @ids=&current_machine_ids();
13300:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13301:         if ($is_me) {
13302:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13303:         } else {
13304:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13305:   	      $udom.'/'.$uname.'/'.$filename;
13306:         }
13307:     } elsif ($file =~ m-^/adm/-) {
13308: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13309:     } else {
13310:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13311:         $file=~s:^/(res|priv)/:/:;
13312:         my $space=$1;
13313:         if ( !( $file =~ m:^/:) ) {
13314:             $location = $dir. '/'.$file;
13315:         } else {
13316:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13317:         }
13318:     }
13319:     $location=~s://+:/:g; # remove duplicate /
13320:     while ($location=~m{/\.\./}) {
13321: 	if ($location =~ m{/[^/]+/\.\./}) {
13322: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13323: 	} else {
13324: 	    $location=~ s{/\.\./}{/}g;
13325: 	}
13326:     } #remove dir/..
13327:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13328:     return $location;
13329: }
13330: 
13331: sub hreflocation {
13332:     my ($dir,$file)=@_;
13333:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13334: 	$file=filelocation($dir,$file);
13335:     } elsif ($file=~m-^/adm/-) {
13336: 	$file=~s-^/adm/wrapper/-/-;
13337: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13338:     }
13339:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13340: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13341:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13342: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13343: 	        {/uploaded/$1/$2/}x;
13344:     }
13345:     if ($file=~ m{^/userfiles/}) {
13346: 	$file =~ s{^/userfiles/}{/uploaded/};
13347:     }
13348:     return $file;
13349: }
13350: 
13351: 
13352: 
13353: 
13354: 
13355: sub current_machine_domains {
13356:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13357: }
13358: 
13359: sub machine_domains {
13360:     my ($hostname) = @_;
13361:     my @domains;
13362:     my %hostname = &all_hostnames();
13363:     while( my($id, $name) = each(%hostname)) {
13364: #	&logthis("-$id-$name-$hostname-");
13365: 	if ($hostname eq $name) {
13366: 	    push(@domains,&host_domain($id));
13367: 	}
13368:     }
13369:     return @domains;
13370: }
13371: 
13372: sub current_machine_ids {
13373:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13374: }
13375: 
13376: sub machine_ids {
13377:     my ($hostname) = @_;
13378:     $hostname ||= &hostname($perlvar{'lonHostID'});
13379:     my @ids;
13380:     my %name_to_host = &all_names();
13381:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13382: 	return @{ $name_to_host{$hostname} };
13383:     }
13384:     return;
13385: }
13386: 
13387: sub additional_machine_domains {
13388:     my @domains;
13389:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13390:     while( my $line = <$fh>) {
13391:         $line =~ s/\s//g;
13392:         push(@domains,$line);
13393:     }
13394:     return @domains;
13395: }
13396: 
13397: sub default_login_domain {
13398:     my $domain = $perlvar{'lonDefDomain'};
13399:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13400:     foreach my $posdom (&current_machine_domains(),
13401:                         &additional_machine_domains()) {
13402:         if (lc($posdom) eq lc($testdomain)) {
13403:             $domain=$posdom;
13404:             last;
13405:         }
13406:     }
13407:     return $domain;
13408: }
13409: 
13410: # ------------------------------------------------------------- Declutters URLs
13411: 
13412: sub declutter {
13413:     my $thisfn=shift;
13414:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13415:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13416:         $thisfn=~s{^/home/httpd/html}{};
13417:     }
13418:     $thisfn=~s/^\///;
13419:     $thisfn=~s|^adm/wrapper/||;
13420:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13421:     $thisfn=~s/^res\///;
13422:     $thisfn=~s/^priv\///;
13423:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13424:         $thisfn=~s/\?.+$//;
13425:     }
13426:     return $thisfn;
13427: }
13428: 
13429: # ------------------------------------------------------------- Clutter up URLs
13430: 
13431: sub clutter {
13432:     my $thisfn='/'.&declutter(shift);
13433:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13434: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13435:        $thisfn='/res'.$thisfn; 
13436:     }
13437:     if ($thisfn !~m|^/adm|) {
13438: 	if ($thisfn =~ m|^/ext/|) {
13439: 	    $thisfn='/adm/wrapper'.$thisfn;
13440: 	} else {
13441: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13442: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13443: 	    if ($embstyle eq 'ssi'
13444: 		|| ($embstyle eq 'hdn')
13445: 		|| ($embstyle eq 'rat')
13446: 		|| ($embstyle eq 'prv')
13447: 		|| ($embstyle eq 'ign')) {
13448: 		#do nothing with these
13449: 	    } elsif (($embstyle eq 'img') 
13450: 		|| ($embstyle eq 'emb')
13451: 		|| ($embstyle eq 'wrp')) {
13452: 		$thisfn='/adm/wrapper'.$thisfn;
13453: 	    } elsif ($embstyle eq 'unk'
13454: 		     && $thisfn!~/\.(sequence|page)$/) {
13455: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13456: 	    } else {
13457: #		&logthis("Got a blank emb style");
13458: 	    }
13459: 	}
13460:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13461:         $thisfn='/adm/wrapper'.$thisfn;
13462:     }
13463:     return $thisfn;
13464: }
13465: 
13466: sub clutter_with_no_wrapper {
13467:     my $uri = &clutter(shift);
13468:     if ($uri =~ m-^/adm/-) {
13469: 	$uri =~ s-^/adm/wrapper/-/-;
13470: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13471:     }
13472:     return $uri;
13473: }
13474: 
13475: sub freeze_escape {
13476:     my ($value)=@_;
13477:     if (ref($value)) {
13478: 	$value=&nfreeze($value);
13479: 	return '__FROZEN__'.&escape($value);
13480:     }
13481:     return &escape($value);
13482: }
13483: 
13484: 
13485: sub thaw_unescape {
13486:     my ($value)=@_;
13487:     if ($value =~ /^__FROZEN__/) {
13488: 	substr($value,0,10,undef);
13489: 	$value=&unescape($value);
13490: 	return &thaw($value);
13491:     }
13492:     return &unescape($value);
13493: }
13494: 
13495: sub correct_line_ends {
13496:     my ($result)=@_;
13497:     $$result =~s/\r\n/\n/mg;
13498:     $$result =~s/\r/\n/mg;
13499: }
13500: # ================================================================ Main Program
13501: 
13502: sub goodbye {
13503:    &logthis("Starting Shut down");
13504: #not converted to using infrastruture and probably shouldn't be
13505:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13506: #converted
13507: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13508:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13509: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13510: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13511: #1.1 only
13512: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13513: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13514: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13515: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13516:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13517:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13518:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13519:    &flushcourselogs();
13520:    &logthis("Shutting down");
13521: }
13522: 
13523: sub get_dns {
13524:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13525:     if (!$ignore_cache) {
13526: 	my ($content,$cached)=
13527: 	    &Apache::lonnet::is_cached_new('dns',$url);
13528: 	if ($cached) {
13529: 	    &$func($content,$hashref);
13530: 	    return;
13531: 	}
13532:     }
13533: 
13534:     my %alldns;
13535:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13536:         foreach my $dns (<$config>) {
13537: 	    next if ($dns !~ /^\^(\S*)/x);
13538:             my $line = $1;
13539:             my ($host,$protocol) = split(/:/,$line);
13540:             if ($protocol ne 'https') {
13541:                 $protocol = 'http';
13542:             }
13543: 	    $alldns{$host} = $protocol;
13544:         }
13545:         close($config);
13546:     }
13547:     while (%alldns) {
13548: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13549: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13550:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13551:         delete($alldns{$dns});
13552: 	next if ($response->is_error());
13553:         if ($url eq '/adm/dns/loncapaCRL') {
13554:             return &$func($response);
13555:         } else {
13556: 	    my @content = split("\n",$response->content);
13557: 	    unless ($nocache) {
13558: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
13559: 	    }
13560: 	    &$func(\@content,$hashref);
13561:             return;
13562:         }
13563:     }
13564:     my $which = (split('/',$url,4))[3];
13565:     if ($which eq 'loncapaCRL') {
13566:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13567:         if (-e $diskfile) {
13568:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
13569:         } else {
13570:             &logthis("unable to contact DNS, no on disk file $diskfile available");
13571:         }
13572:     } else {
13573:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13574:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13575:             my @content = <$config>;
13576:             close($config);
13577:             &$func(\@content,$hashref);
13578:         }
13579:     }
13580:     return;
13581: }
13582: 
13583: # ------------------------------------------------------Get DNS checksums file
13584: sub parse_dns_checksums_tab {
13585:     my ($lines,$hashref) = @_;
13586:     my $lonhost = $perlvar{'lonHostID'};
13587:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13588:     my $loncaparev = &get_server_loncaparev($machine_dom);
13589:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13590:     my $webconfdir = '/etc/httpd/conf';
13591:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13592:         $webconfdir = '/etc/apache2';
13593:     } elsif ($distro =~ /^sles(\d+)$/) {
13594:         if ($1 >= 10) {
13595:             $webconfdir = '/etc/apache2';
13596:         }
13597:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13598:         if ($1 >= 10.0) {
13599:             $webconfdir = '/etc/apache2';
13600:         }
13601:     }
13602:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13603:     my (%chksum,%revnum);
13604:     if (ref($lines) eq 'ARRAY') {
13605:         chomp(@{$lines});
13606:         my $version = shift(@{$lines});
13607:         if ($version eq $release) {  
13608:             foreach my $line (@{$lines}) {
13609:                 my ($file,$version,$shasum) = split(/,/,$line);
13610:                 if ($file =~ m{^/etc/httpd/conf}) {
13611:                     if ($webconfdir eq '/etc/apache2') {
13612:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13613:                     }
13614:                 }
13615:                 $chksum{$file} = $shasum;
13616:                 $revnum{$file} = $version;
13617:             }
13618:             if (ref($hashref) eq 'HASH') {
13619:                 %{$hashref} = (
13620:                                 sums     => \%chksum,
13621:                                 versions => \%revnum,
13622:                               );
13623:             }
13624:         }
13625:     }
13626:     return;
13627: }
13628: 
13629: sub fetch_dns_checksums {
13630:     my %checksums;
13631:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13632:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13633:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13634:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13635:              \%checksums);
13636:     return \%checksums;
13637: }
13638: 
13639: sub fetch_crl_pemfile {
13640:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
13641: }
13642: 
13643: sub save_crl_pem {
13644:     my ($response) = @_;
13645:     my ($msg,$hadchanges);
13646:     if (ref($response)) {
13647:         my $now = time;
13648:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
13649:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
13650:         if (open(my $fh,'>',"$tmpcrl")) {
13651:             print $fh $response->content;
13652:             close($fh);
13653:             if (-e $lonca) {
13654:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
13655:                     my $check = <PIPE>;
13656:                     close(PIPE);
13657:                     chomp($check);
13658:                     if ($check eq 'verify OK') {
13659:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13660:                         my $backup;
13661:                         if (-e $dest) {
13662:                             if (&File::Copy::move($dest,"$dest.bak")) {
13663:                                 $backup = 'ok';
13664:                             }
13665:                         }
13666:                         if (&File::Copy::move($tmpcrl,$dest)) {
13667:                             $msg = 'ok';
13668:                             if ($backup) {
13669:                                 my (%oldnums,%newnums);
13670:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
13671:                                     while (<PIPE>) {
13672:                                         $oldnums{(split(/:/))[1]} = 1;
13673:                                     }
13674:                                     close(PIPE);
13675:                                 }
13676:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
13677:                                     while(<PIPE>) {
13678:                                         $newnums{(split(/:/))[1]} = 1;
13679:                                     }
13680:                                     close(PIPE);
13681:                                 }
13682:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
13683:                                     unless (exists($oldnums{$key})) {
13684:                                         $hadchanges = 1;
13685:                                         last;
13686:                                     }
13687:                                 }
13688:                                 unless ($hadchanges) {
13689:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
13690:                                         unless (exists($newnums{$key})) {
13691:                                             $hadchanges = 1;
13692:                                             last;
13693:                                         }
13694:                                     }
13695:                                 }
13696:                             }
13697:                         }
13698:                     } else {
13699:                         unlink($tmpcrl);
13700:                     }
13701:                 } else {
13702:                     unlink($tmpcrl);
13703:                 }
13704:             } else {
13705:                 unlink($tmpcrl);
13706:             }
13707:         }
13708:     }
13709:     return ($msg,$hadchanges);
13710: }
13711: 
13712: # ------------------------------------------------------------ Read domain file
13713: {
13714:     my $loaded;
13715:     my %domain;
13716: 
13717:     sub parse_domain_tab {
13718: 	my ($lines) = @_;
13719: 	foreach my $line (@$lines) {
13720: 	    next if ($line =~ /^(\#|\s*$ )/x);
13721: 
13722: 	    chomp($line);
13723: 	    my ($name,@elements) = split(/:/,$line,9);
13724: 	    my %this_domain;
13725: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13726: 			       'lang_def', 'city', 'longi', 'lati',
13727: 			       'primary') {
13728: 		$this_domain{$field} = shift(@elements);
13729: 	    }
13730: 	    $domain{$name} = \%this_domain;
13731: 	}
13732:     }
13733: 
13734:     sub reset_domain_info {
13735: 	undef($loaded);
13736: 	undef(%domain);
13737:     }
13738: 
13739:     sub load_domain_tab {
13740: 	my ($ignore_cache,$nocache) = @_;
13741: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13742: 	my $fh;
13743: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13744: 	    my @lines = <$fh>;
13745: 	    &parse_domain_tab(\@lines);
13746: 	}
13747: 	close($fh);
13748: 	$loaded = 1;
13749:     }
13750: 
13751:     sub domain {
13752: 	&load_domain_tab() if (!$loaded);
13753: 
13754: 	my ($name,$what) = @_;
13755: 	return if ( !exists($domain{$name}) );
13756: 
13757: 	if (!$what) {
13758: 	    return $domain{$name}{'description'};
13759: 	}
13760: 	return $domain{$name}{$what};
13761:     }
13762: 
13763:     sub domain_info {
13764:         &load_domain_tab() if (!$loaded);
13765:         return %domain;
13766:     }
13767: 
13768: }
13769: 
13770: 
13771: # ------------------------------------------------------------- Read hosts file
13772: {
13773:     my %hostname;
13774:     my %hostdom;
13775:     my %libserv;
13776:     my $loaded;
13777:     my %name_to_host;
13778:     my %internetdom;
13779:     my %LC_dns_serv;
13780: 
13781:     sub parse_hosts_tab {
13782: 	my ($file) = @_;
13783: 	foreach my $configline (@$file) {
13784: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13785:             chomp($configline);
13786: 	    if ($configline =~ /^\^/) {
13787:                 if ($configline =~ /^\^([\w.\-]+)/) {
13788:                     $LC_dns_serv{$1} = 1;
13789:                 }
13790:                 next;
13791:             }
13792: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13793: 	    $name=~s/\s//g;
13794: 	    if ($id && $domain && $role && $name) {
13795:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13796:                     my $curr = $hostname{$id};
13797:                     my $skip;
13798:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13799:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13800:                             $skip = 1;
13801:                         } else {
13802:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13803:                         }
13804:                     }
13805:                     unless ($skip) {
13806:                         push(@{$name_to_host{$name}},$id);
13807:                     }
13808:                 } else {
13809:                     push(@{$name_to_host{$name}},$id);
13810:                 }
13811: 		$hostname{$id}=$name;
13812: 		$hostdom{$id}=$domain;
13813: 		if ($role eq 'library') { $libserv{$id}=$name; }
13814:                 if (defined($protocol)) {
13815:                     if ($protocol eq 'https') {
13816:                         $protocol{$id} = $protocol;
13817:                     } else {
13818:                         $protocol{$id} = 'http'; 
13819:                     }
13820:                 } else {
13821:                     $protocol{$id} = 'http';
13822:                 }
13823:                 if (defined($intdom)) {
13824:                     $internetdom{$id} = $intdom;
13825:                 }
13826: 	    }
13827: 	}
13828:     }
13829:     
13830:     sub reset_hosts_info {
13831: 	&purge_remembered();
13832: 	&reset_domain_info();
13833: 	&reset_hosts_ip_info();
13834:         undef(%internetdom);
13835: 	undef(%name_to_host);
13836: 	undef(%hostname);
13837: 	undef(%hostdom);
13838: 	undef(%libserv);
13839: 	undef($loaded);
13840:     }
13841: 
13842:     sub load_hosts_tab {
13843: 	my ($ignore_cache,$nocache) = @_;
13844: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13845: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13846: 	my @config = <$config>;
13847: 	&parse_hosts_tab(\@config);
13848: 	close($config);
13849: 	$loaded=1;
13850:     }
13851: 
13852:     sub hostname {
13853: 	&load_hosts_tab() if (!$loaded);
13854: 
13855: 	my ($lonid) = @_;
13856: 	return $hostname{$lonid};
13857:     }
13858: 
13859:     sub all_hostnames {
13860: 	&load_hosts_tab() if (!$loaded);
13861: 
13862: 	return %hostname;
13863:     }
13864: 
13865:     sub all_names {
13866:         my ($ignore_cache,$nocache) = @_;
13867: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13868: 
13869: 	return %name_to_host;
13870:     }
13871: 
13872:     sub all_host_domain {
13873:         &load_hosts_tab() if (!$loaded);
13874:         return %hostdom;
13875:     }
13876: 
13877:     sub all_host_intdom {
13878:         &load_hosts_tab() if (!$loaded);
13879:         return %internetdom;
13880:     }
13881: 
13882:     sub is_library {
13883: 	&load_hosts_tab() if (!$loaded);
13884: 
13885: 	return exists($libserv{$_[0]});
13886:     }
13887: 
13888:     sub all_library {
13889: 	&load_hosts_tab() if (!$loaded);
13890: 
13891: 	return %libserv;
13892:     }
13893: 
13894:     sub unique_library {
13895: 	#2x reverse removes all hostnames that appear more than once
13896:         my %unique = reverse &all_library();
13897:         return reverse %unique;
13898:     }
13899: 
13900:     sub get_servers {
13901: 	&load_hosts_tab() if (!$loaded);
13902: 
13903: 	my ($domain,$type) = @_;
13904: 	my %possible_hosts = ($type eq 'library') ? %libserv
13905: 	                                          : %hostname;
13906: 	my %result;
13907: 	if (ref($domain) eq 'ARRAY') {
13908: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13909: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13910: 		    $result{$host} = $hostname;
13911: 		}
13912: 	    }
13913: 	} else {
13914: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13915: 		if ($hostdom{$host} eq $domain) {
13916: 		    $result{$host} = $hostname;
13917: 		}
13918: 	    }
13919: 	}
13920: 	return %result;
13921:     }
13922: 
13923:     sub get_unique_servers {
13924:         my %unique = reverse &get_servers(@_);
13925: 	return reverse %unique;
13926:     }
13927: 
13928:     sub host_domain {
13929: 	&load_hosts_tab() if (!$loaded);
13930: 
13931: 	my ($lonid) = @_;
13932: 	return $hostdom{$lonid};
13933:     }
13934: 
13935:     sub all_domains {
13936: 	&load_hosts_tab() if (!$loaded);
13937: 
13938: 	my %seen;
13939: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13940: 	return @uniq;
13941:     }
13942: 
13943:     sub internet_dom {
13944:         &load_hosts_tab() if (!$loaded);
13945: 
13946:         my ($lonid) = @_;
13947:         return $internetdom{$lonid};
13948:     }
13949: 
13950:     sub is_LC_dns {
13951:         &load_hosts_tab() if (!$loaded);
13952: 
13953:         my ($hostname) = @_;
13954:         return exists($LC_dns_serv{$hostname});
13955:     }
13956: 
13957: }
13958: 
13959: { 
13960:     my %iphost;
13961:     my %name_to_ip;
13962:     my %lonid_to_ip;
13963: 
13964:     sub get_hosts_from_ip {
13965: 	my ($ip) = @_;
13966: 	my %iphosts = &get_iphost();
13967: 	if (ref($iphosts{$ip})) {
13968: 	    return @{$iphosts{$ip}};
13969: 	}
13970: 	return;
13971:     }
13972:     
13973:     sub reset_hosts_ip_info {
13974: 	undef(%iphost);
13975: 	undef(%name_to_ip);
13976: 	undef(%lonid_to_ip);
13977:     }
13978: 
13979:     sub get_host_ip {
13980: 	my ($lonid) = @_;
13981: 	if (exists($lonid_to_ip{$lonid})) {
13982: 	    return $lonid_to_ip{$lonid};
13983: 	}
13984: 	my $name=&hostname($lonid);
13985:    	my $ip = gethostbyname($name);
13986: 	return if (!$ip || length($ip) ne 4);
13987: 	$ip=inet_ntoa($ip);
13988: 	$name_to_ip{$name}   = $ip;
13989: 	$lonid_to_ip{$lonid} = $ip;
13990: 	return $ip;
13991:     }
13992:     
13993:     sub get_iphost {
13994: 	my ($ignore_cache,$nocache) = @_;
13995: 
13996: 	if (!$ignore_cache) {
13997: 	    if (%iphost) {
13998: 		return %iphost;
13999: 	    }
14000: 	    my ($ip_info,$cached)=
14001: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14002: 	    if ($cached) {
14003: 		%iphost      = %{$ip_info->[0]};
14004: 		%name_to_ip  = %{$ip_info->[1]};
14005: 		%lonid_to_ip = %{$ip_info->[2]};
14006: 		return %iphost;
14007: 	    }
14008: 	}
14009: 
14010: 	# get yesterday's info for fallback
14011: 	my %old_name_to_ip;
14012: 	my ($ip_info,$cached)=
14013: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14014: 	if ($cached) {
14015: 	    %old_name_to_ip = %{$ip_info->[1]};
14016: 	}
14017: 
14018: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14019: 	foreach my $name (keys(%name_to_host)) {
14020: 	    my $ip;
14021: 	    if (!exists($name_to_ip{$name})) {
14022: 		$ip = gethostbyname($name);
14023: 		if (!$ip || length($ip) ne 4) {
14024: 		    if (defined($old_name_to_ip{$name})) {
14025: 			$ip = $old_name_to_ip{$name};
14026: 			&logthis("Can't find $name defaulting to old $ip");
14027: 		    } else {
14028: 			&logthis("Name $name no IP found");
14029: 			next;
14030: 		    }
14031: 		} else {
14032: 		    $ip=inet_ntoa($ip);
14033: 		}
14034: 		$name_to_ip{$name} = $ip;
14035: 	    } else {
14036: 		$ip = $name_to_ip{$name};
14037: 	    }
14038: 	    foreach my $id (@{ $name_to_host{$name} }) {
14039: 		$lonid_to_ip{$id} = $ip;
14040: 	    }
14041: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14042: 	}
14043:         unless ($nocache) {
14044: 	    &do_cache_new('iphost','iphost',
14045: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14046: 		          48*60*60);
14047:         }
14048: 
14049: 	return %iphost;
14050:     }
14051: 
14052:     #
14053:     #  Given a DNS returns the loncapa host name for that DNS 
14054:     # 
14055:     sub host_from_dns {
14056:         my ($dns) = @_;
14057:         my @hosts;
14058:         my $ip;
14059: 
14060:         if (exists($name_to_ip{$dns})) {
14061:             $ip = $name_to_ip{$dns};
14062:         }
14063:         if (!$ip) {
14064:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14065:             if (length($ip) == 4) { 
14066: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14067:             }
14068:         }
14069:         if ($ip) {
14070: 	    @hosts = get_hosts_from_ip($ip);
14071: 	    return $hosts[0];
14072:         }
14073:         return undef;
14074:     }
14075: 
14076:     sub get_internet_names {
14077:         my ($lonid) = @_;
14078:         return if ($lonid eq '');
14079:         my ($idnref,$cached)=
14080:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14081:         if ($cached) {
14082:             return $idnref;
14083:         }
14084:         my $ip = &get_host_ip($lonid);
14085:         my @hosts = &get_hosts_from_ip($ip);
14086:         my %iphost = &get_iphost();
14087:         my (@idns,%seen);
14088:         foreach my $id (@hosts) {
14089:             my $dom = &host_domain($id);
14090:             my $prim_id = &domain($dom,'primary');
14091:             my $prim_ip = &get_host_ip($prim_id);
14092:             next if ($seen{$prim_ip});
14093:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14094:                 foreach my $id (@{$iphost{$prim_ip}}) {
14095:                     my $intdom = &internet_dom($id);
14096:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14097:                         push(@idns,$intdom);
14098:                     }
14099:                 }
14100:             }
14101:             $seen{$prim_ip} = 1;
14102:         }
14103:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14104:     }
14105: 
14106: }
14107: 
14108: sub all_loncaparevs {
14109:     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);
14110: }
14111: 
14112: # ---------------------------------------------------------- Read loncaparev table
14113: {
14114:     sub load_loncaparevs { 
14115:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14116:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14117:                 while (my $configline=<$config>) {
14118:                     chomp($configline);
14119:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14120:                     $loncaparevs{$hostid}=$loncaparev;
14121:                 }
14122:                 close($config);
14123:             }
14124:         }
14125:     }
14126: }
14127: 
14128: # ---------------------------------------------------------- Read serverhostID table
14129: {
14130:     sub load_serverhomeIDs {
14131:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14132:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14133:                 while (my $configline=<$config>) {
14134:                     chomp($configline);
14135:                     my ($name,$id)=split(/:/,$configline);
14136:                     $serverhomeIDs{$name}=$id;
14137:                 }
14138:                 close($config);
14139:             }
14140:         }
14141:     }
14142: }
14143: 
14144: 
14145: BEGIN {
14146: 
14147: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14148:     unless ($readit) {
14149: {
14150:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14151:     %perlvar = (%perlvar,%{$configvars});
14152: }
14153: 
14154: 
14155: # ------------------------------------------------------ Read spare server file
14156: {
14157:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14158: 
14159:     while (my $configline=<$config>) {
14160:        chomp($configline);
14161:        if ($configline) {
14162: 	   my ($host,$type) = split(':',$configline,2);
14163: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14164: 	   push(@{ $spareid{$type} }, $host);
14165:        }
14166:     }
14167:     close($config);
14168: }
14169: # ------------------------------------------------------------ Read permissions
14170: {
14171:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14172: 
14173:     while (my $configline=<$config>) {
14174: 	chomp($configline);
14175: 	if ($configline) {
14176: 	    my ($role,$perm)=split(/ /,$configline);
14177: 	    if ($perm ne '') { $pr{$role}=$perm; }
14178: 	}
14179:     }
14180:     close($config);
14181: }
14182: 
14183: # -------------------------------------------- Read plain texts for permissions
14184: {
14185:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14186: 
14187:     while (my $configline=<$config>) {
14188: 	chomp($configline);
14189: 	if ($configline) {
14190: 	    my ($short,@plain)=split(/:/,$configline);
14191:             %{$prp{$short}} = ();
14192: 	    if (@plain > 0) {
14193:                 $prp{$short}{'std'} = $plain[0];
14194:                 for (my $i=1; $i<@plain; $i++) {
14195:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14196:                 }
14197:             }
14198: 	}
14199:     }
14200:     close($config);
14201: }
14202: 
14203: # ---------------------------------------------------------- Read package table
14204: {
14205:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14206: 
14207:     while (my $configline=<$config>) {
14208: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14209: 	chomp($configline);
14210: 	my ($short,$plain)=split(/:/,$configline);
14211: 	my ($pack,$name)=split(/\&/,$short);
14212: 	if ($plain ne '') {
14213: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14214: 	    $packagetab{$short}=$plain; 
14215: 	}
14216:     }
14217:     close($config);
14218: }
14219: 
14220: # ---------------------------------------------------------- Read loncaparev table
14221: 
14222: &load_loncaparevs();
14223: 
14224: # ---------------------------------------------------------- Read serverhostID table
14225: 
14226: &load_serverhomeIDs();
14227: 
14228: # ---------------------------------------------------------- Read releaseslist XML
14229: {
14230:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14231:     if (-e $file) {
14232:         my $parser = HTML::LCParser->new($file);
14233:         while (my $token = $parser->get_token()) {
14234:             if ($token->[0] eq 'S') {
14235:                 my $item = $token->[1];
14236:                 my $name = $token->[2]{'name'};
14237:                 my $value = $token->[2]{'value'};
14238:                 my $valuematch = $token->[2]{'valuematch'};
14239:                 my $namematch = $token->[2]{'namematch'};
14240:                 if ($item eq 'parameter') {
14241:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14242:                         my $release = $parser->get_text();
14243:                         $release =~ s/(^\s*|\s*$ )//gx;
14244:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14245:                     }
14246:                 } elsif ($item ne '' && $name ne '') {
14247:                     my $release = $parser->get_text();
14248:                     $release =~ s/(^\s*|\s*$ )//gx;
14249:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14250:                 }
14251:             }
14252:         }
14253:     }
14254: }
14255: 
14256: # ---------------------------------------------------------- Read managers table
14257: {
14258:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14259:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14260:             while (my $configline=<$config>) {
14261:                 chomp($configline);
14262:                 next if ($configline =~ /^\#/);
14263:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14264:                     $managerstab{$configline} = 1;
14265:                 }
14266:             }
14267:             close($config);
14268:         }
14269:     }
14270: }
14271: 
14272: # ------------- set up temporary directory
14273: {
14274:     $tmpdir = LONCAPA::tempdir();
14275: 
14276: }
14277: 
14278: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14279: 				'compress_threshold'=> 20_000,
14280:  			        });
14281: 
14282: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14283: $dumpcount=0;
14284: $locknum=0;
14285: 
14286: &logtouch();
14287: &logthis('<font color="yellow">INFO: Read configuration</font>');
14288: $readit=1;
14289:     {
14290: 	use integer;
14291: 	my $test=(2**32)+1;
14292: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14293: 	&logthis(" Detected 64bit platform ($_64bit)");
14294:     }
14295: }
14296: }
14297: 
14298: 1;
14299: __END__
14300: 
14301: =pod
14302: 
14303: =head1 NAME
14304: 
14305: Apache::lonnet - Subroutines to ask questions about things in the network.
14306: 
14307: =head1 SYNOPSIS
14308: 
14309: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14310: 
14311:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14312: 
14313: Common parameters:
14314: 
14315: =over 4
14316: 
14317: =item *
14318: 
14319: $uname : an internal username (if $cname expecting a course Id specifically)
14320: 
14321: =item *
14322: 
14323: $udom : a domain (if $cdom expecting a course's domain specifically)
14324: 
14325: =item *
14326: 
14327: $symb : a resource instance identifier
14328: 
14329: =item *
14330: 
14331: $namespace : the name of a .db file that contains the data needed or
14332: being set.
14333: 
14334: =back
14335: 
14336: =head1 OVERVIEW
14337: 
14338: lonnet provides subroutines which interact with the
14339: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14340: about classes, users, and resources.
14341: 
14342: For many of these objects you can also use this to store data about
14343: them or modify them in various ways.
14344: 
14345: =head2 Symbs
14346: 
14347: To identify a specific instance of a resource, LON-CAPA uses symbols
14348: or "symbs"X<symb>. These identifiers are built from the URL of the
14349: map, the resource number of the resource in the map, and the URL of
14350: the resource itself. The latter is somewhat redundant, but might help
14351: if maps change.
14352: 
14353: An example is
14354: 
14355:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14356: 
14357: The respective map entry is
14358: 
14359:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14360:   title="Problem 2">
14361:  </resource>
14362: 
14363: Symbs are used by the random number generator, as well as to store and
14364: restore data specific to a certain instance of for example a problem.
14365: 
14366: =head2 Storing And Retrieving Data
14367: 
14368: X<store()>X<cstore()>X<restore()>Three of the most important functions
14369: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14370: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14371: is is the non-critical message twin of cstore. These functions are for
14372: handlers to store a perl hash to a user's permanent data space in an
14373: easy manner, and to retrieve it again on another call. It is expected
14374: that a handler would use this once at the beginning to retrieve data,
14375: and then again once at the end to send only the new data back.
14376: 
14377: The data is stored in the user's data directory on the user's
14378: homeserver under the ID of the course.
14379: 
14380: The hash that is returned by restore will have all of the previous
14381: value for all of the elements of the hash.
14382: 
14383: Example:
14384: 
14385:  #creating a hash
14386:  my %hash;
14387:  $hash{'foo'}='bar';
14388: 
14389:  #storing it
14390:  &Apache::lonnet::cstore(\%hash);
14391: 
14392:  #changing a value
14393:  $hash{'foo'}='notbar';
14394: 
14395:  #adding a new value
14396:  $hash{'bar'}='foo';
14397:  &Apache::lonnet::cstore(\%hash);
14398: 
14399:  #retrieving the hash
14400:  my %history=&Apache::lonnet::restore();
14401: 
14402:  #print the hash
14403:  foreach my $key (sort(keys(%history))) {
14404:    print("\%history{$key} = $history{$key}");
14405:  }
14406: 
14407: Will print out:
14408: 
14409:  %history{1:foo} = bar
14410:  %history{1:keys} = foo:timestamp
14411:  %history{1:timestamp} = 990455579
14412:  %history{2:bar} = foo
14413:  %history{2:foo} = notbar
14414:  %history{2:keys} = foo:bar:timestamp
14415:  %history{2:timestamp} = 990455580
14416:  %history{bar} = foo
14417:  %history{foo} = notbar
14418:  %history{timestamp} = 990455580
14419:  %history{version} = 2
14420: 
14421: Note that the special hash entries C<keys>, C<version> and
14422: C<timestamp> were added to the hash. C<version> will be equal to the
14423: total number of versions of the data that have been stored. The
14424: C<timestamp> attribute will be the UNIX time the hash was
14425: stored. C<keys> is available in every historical section to list which
14426: keys were added or changed at a specific historical revision of a
14427: hash.
14428: 
14429: B<Warning>: do not store the hash that restore returns directly. This
14430: will cause a mess since it will restore the historical keys as if the
14431: were new keys. I.E. 1:foo will become 1:1:foo etc.
14432: 
14433: Calling convention:
14434: 
14435:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14436:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14437: 
14438: For more detailed information, see lonnet specific documentation.
14439: 
14440: =head1 RETURN MESSAGES
14441: 
14442: =over 4
14443: 
14444: =item * B<con_lost>: unable to contact remote host
14445: 
14446: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14447: when the connection is brought back up
14448: 
14449: =item * B<con_failed>: unable to contact remote host and unable to save message
14450: for later delivery
14451: 
14452: =item * B<error:>: an error a occurred, a description of the error follows the :
14453: 
14454: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14455: that was requested
14456: 
14457: =back
14458: 
14459: =head1 PUBLIC SUBROUTINES
14460: 
14461: =head2 Session Environment Functions
14462: 
14463: =over 4
14464: 
14465: =item * 
14466: X<appenv()>
14467: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14468: the user envirnoment file, and will be restored for each access this
14469: user makes during this session, also modifies the %env for the current
14470: process. Optional rolesarrayref - if defined contains a reference to an array
14471: of roles which are exempt from the restriction on modifying user.role entries 
14472: in the user's environment.db and in %env.    
14473: 
14474: =item *
14475: X<delenv()>
14476: B<delenv($delthis,$regexp)>: removes all items from the session
14477: environment file that begin with $delthis. If the 
14478: optional second arg - $regexp - is true, $delthis is treated as a 
14479: regular expression, otherwise \Q$delthis\E is used. 
14480: The values are also deleted from the current processes %env.
14481: 
14482: =item * get_env_multiple($name) 
14483: 
14484: gets $name from the %env hash, it seemlessly handles the cases where multiple
14485: values may be defined and end up as an array ref.
14486: 
14487: returns an array of values
14488: 
14489: =back
14490: 
14491: =head2 User Information
14492: 
14493: =over 4
14494: 
14495: =item *
14496: X<queryauthenticate()>
14497: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14498: authentication scheme
14499: 
14500: =item *
14501: X<authenticate()>
14502: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14503: authenticate user from domain's lib servers (first use the current
14504: one). C<$upass> should be the users password.
14505: $checkdefauth is optional (value is 1 if a check should be made to
14506:    authenticate user using default authentication method, and allow
14507:    account creation if username does not have account in the domain).
14508: $clientcancheckhost is optional (value is 1 if checking whether the
14509:    server can host will occur on the client side in lonauth.pm).   
14510: 
14511: =item *
14512: X<homeserver()>
14513: B<homeserver($uname,$udom)>: find the server which has
14514: the user's directory and files (there must be only one), this caches
14515: the answer, and also caches if there is a borken connection.
14516: 
14517: =item *
14518: X<idget()>
14519: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14520: a list of student/employee IDs or clicker IDs
14521: (student/employee IDs are a unique resource in a domain, there must be 
14522: only 1 ID per username, and only 1 username per ID in a specific domain).
14523: clickerIDs are not necessarily unique, as students might share clickers.
14524: (returns hash: id=>name,id=>name)
14525: 
14526: =item *
14527: X<idrget()>
14528: B<idrget($udom,@unames)>: find the IDs behind a list of
14529: usernames (returns hash: name=>id,name=>id)
14530: 
14531: =item *
14532: X<idput()>
14533: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14534: names and associated student/employee IDs or clicker IDs.
14535: 
14536: =item *
14537: X<iddel()>
14538: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14539: student/employee ID or clicker ID username look-ups from domain.
14540: The homeserver ($uhome) and namespace ($namespace) are optional.
14541: If no $uhome is provided, it will be determined usig &homeserver()
14542: for each user.  If no $namespace is provided, the default is ids.
14543: 
14544: =item *
14545: X<updateclickers()>
14546: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14547: clicker ID-to-username look-ups in clickers.db on library server.
14548: Permitted actions are add or del (i.e., add or delete). The 
14549: clickers.db contains clickerID as keys (escaped), and each corresponding
14550: value is an escaped comma-separated list of usernames (for whom the
14551: library server is the homeserver), who registered that particular ID.
14552: If $critical is true, the update will be sent via &critical, otherwise
14553: &reply() will be used.
14554: 
14555: =item *
14556: X<rolesinit()>
14557: B<rolesinit($udom,$username)>: get user privileges.
14558: returns user role, first access and timer interval hashes
14559: 
14560: =item *
14561: X<privileged()>
14562: B<privileged($username,$domain)>: returns a true if user has a
14563: privileged and active role (i.e. su or dc), false otherwise.
14564: 
14565: =item *
14566: X<getsection()>
14567: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14568: course $cname, return section name/number or '' for "not in course"
14569: and '-1' for "no section"
14570: 
14571: =item *
14572: X<userenvironment()>
14573: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14574: passed in @what from the requested user's environment, returns a hash
14575: 
14576: =item * 
14577: X<userlog_query()>
14578: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14579: activity.log file. %filters defines filters applied when parsing the
14580: log file. These can be start or end timestamps, or the type of action
14581: - log to look for Login or Logout events, check for Checkin or
14582: Checkout, role for role selection. The response is in the form
14583: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14584: escaped strings of the action recorded in the activity.log file.
14585: 
14586: =back
14587: 
14588: =head2 User Roles
14589: 
14590: =over 4
14591: 
14592: =item *
14593: 
14594: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14595: returns codes for allowed actions.
14596: 
14597: The first argument is required, all others are optional.
14598: 
14599: $priv is the privilege being checked.
14600: $uri contains additional information about what is being checked for access (e.g.,
14601: URL, course ID etc.). 
14602: $symb is the unique resource instance identifier in a course; if needed,
14603: but not provided, it will be retrieved via a call to &symbread(). 
14604: $role is the role for which a priv is being checked (only used if priv is evb). 
14605: $clientip is the user's IP address (only used when checking for access to portfolio 
14606: files).
14607: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14608: prevents recursive calls to &allowed.
14609: 
14610:  F: full access
14611:  U,I,K: authentication modes (cxx only)
14612:  '': forbidden
14613:  1: user needs to choose course
14614:  2: browse allowed
14615:  A: passphrase authentication needed
14616:  B: access temporarily blocked because of a blocking event in a course.
14617: 
14618: =item *
14619: 
14620: constructaccess($url,$setpriv) : check for access to construction space URL
14621: 
14622: See if the owner domain and name in the URL match those in the
14623: expected environment.  If so, return three element list
14624: ($ownername,$ownerdomain,$ownerhome).
14625: 
14626: Otherwise return the null string.
14627: 
14628: If second argument 'setpriv' is true, it assigns the privileges,
14629: and returns the same three element list, unless the owner has
14630: blocked "ad hoc" Domain Coordinator access to the Author Space,
14631: in which case the null string is returned.
14632: 
14633: =item *
14634: 
14635: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14636: define a custom role rolename set privileges in format of lonTabs/roles.tab
14637: for system, domain, and course level. $uname and $udom are optional (current
14638: user's username and domain will be used when either of $uname or $udom are absent.
14639: 
14640: =item *
14641: 
14642: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14643: (rolesplain.tab); plain text explanation of a user role term.
14644: $type is Course (default) or Community.
14645: If $forcedefault evaluates to true, text returned will be default 
14646: text for $type. Otherwise, if this is a course, the text returned 
14647: will be a custom name for the role (if defined in the course's 
14648: environment).  If no custom name is defined the default is returned.
14649:    
14650: =item *
14651: 
14652: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14653: All arguments are optional. Returns a hash of a roles, either for
14654: co-author/assistant author roles for a user's Construction Space
14655: (default), or if $context is 'userroles', roles for the user himself,
14656: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14657: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14658: For each key, value is set to colon-separated start and end times for
14659: the role.  If no username and domain are specified, will default to
14660: current user/domain. Types, roles, and roledoms are references to arrays
14661: of role statuses (active, future or previous), roles 
14662: (e.g., cc,in, st etc.) and domains of the roles which can be used
14663: to restrict the list of roles reported. If no array ref is 
14664: provided for types, will default to return only active roles.
14665: 
14666: =item *
14667: 
14668: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14669: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14670: 
14671: Additional optional arguments are: $type (if role checking is to be restricted 
14672: to certain user status types -- previous (expired roles), active (currently
14673: available roles) or future (roles available in the future), and
14674: $hideprivileged -- if true will not report course roles for users who
14675: have active Domain Coordinator role in course's domain or in additional
14676: domains (specified in 'Domains to check for privileged users' in course
14677: environment -- set via:  Course Settings -> Classlists and staff listing).
14678: 
14679: =item *
14680: 
14681: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14682: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14683: $possdomains and $possroles are optional array refs -- to domains to check and
14684: roles to check.  If $possdomains is not specified, a dump will be done of the
14685: users' roles.db to check for a dc or su role in any domain. This can be
14686: time consuming if &privileged is called repeatedly (e.g., when displaying a
14687: classlist), so in such cases, supplying a $possdomains array is preferred, as
14688: this then allows &privileged_by_domain() to be used, which caches the identity
14689: of privileged users, eliminating the need for repeated calls to &dump().
14690: 
14691: =item *
14692: 
14693: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14694: where the outer hash keys are domains specified in the $possdomains array ref,
14695: next inner hash keys are privileged roles specified in the $roles array ref,
14696: and the innermost hash contains key = value pairs for username:domain = end:start
14697: for active or future "privileged" users with that role in that domain. To avoid
14698: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14699: innerhash are cached using priv_$role and $dom as the identifiers.
14700: 
14701: =back
14702: 
14703: =head2 User Modification
14704: 
14705: =over 4
14706: 
14707: =item *
14708: 
14709: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14710: user for the level given by URL.  Optional start and end dates (leave empty
14711: string or zero for "no date")
14712: 
14713: =item *
14714: 
14715: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14716: change a users, password, possible return values are: ok,
14717: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14718: refused
14719: 
14720: =item *
14721: 
14722: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14723: 
14724: =item *
14725: 
14726: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14727:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14728: 
14729: will update user information (firstname,middlename,lastname,generation,
14730: permanentemail), and if forceid is true, student/employee ID also.
14731: A user's institutional affiliation(s) can also be updated.
14732: User information fields will not be overwritten with empty entries 
14733: unless the field is included in the $candelete array reference.
14734: This array is included when a single user is modified via "Manage Users",
14735: or when Autoupdate.pl is run by cron in a domain.
14736: 
14737: =item *
14738: 
14739: modifystudent
14740: 
14741: modify a student's enrollment and identification information.
14742: The course id is resolved based on the current user's environment.  
14743: This means the invoking user must be a course coordinator or otherwise
14744: associated with a course.
14745: 
14746: This call is essentially a wrapper for lonnet::modifyuser and
14747: lonnet::modify_student_enrollment
14748: 
14749: Inputs: 
14750: 
14751: =over 4
14752: 
14753: =item B<$udom> Student's loncapa domain
14754: 
14755: =item B<$uname> Student's loncapa login name
14756: 
14757: =item B<$uid> Student/Employee ID
14758: 
14759: =item B<$umode> Student's authentication mode
14760: 
14761: =item B<$upass> Student's password
14762: 
14763: =item B<$first> Student's first name
14764: 
14765: =item B<$middle> Student's middle name
14766: 
14767: =item B<$last> Student's last name
14768: 
14769: =item B<$gene> Student's generation
14770: 
14771: =item B<$usec> Student's section in course
14772: 
14773: =item B<$end> Unix time of the roles expiration
14774: 
14775: =item B<$start> Unix time of the roles start date
14776: 
14777: =item B<$forceid> If defined, allow $uid to be changed
14778: 
14779: =item B<$desiredhome> server to use as home server for student
14780: 
14781: =item B<$email> Student's permanent e-mail address
14782: 
14783: =item B<$type> Type of enrollment (auto or manual)
14784: 
14785: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14786: 
14787: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14788: 
14789: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14790: 
14791: =item B<$context> role change context (shown in User Management Logs display in a course)
14792: 
14793: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14794: 
14795: =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.
14796: 
14797: =back
14798: 
14799: =item *
14800: 
14801: modify_student_enrollment
14802: 
14803: Change a student's enrollment status in a class.  The environment variable
14804: 'role.request.course' must be defined for this function to proceed.
14805: 
14806: Inputs:
14807: 
14808: =over 4
14809: 
14810: =item $udom, student's domain
14811: 
14812: =item $uname, student's name
14813: 
14814: =item $uid, student's user id
14815: 
14816: =item $first, student's first name
14817: 
14818: =item $middle
14819: 
14820: =item $last
14821: 
14822: =item $gene
14823: 
14824: =item $usec
14825: 
14826: =item $end
14827: 
14828: =item $start
14829: 
14830: =item $type
14831: 
14832: =item $locktype
14833: 
14834: =item $cid
14835: 
14836: =item $selfenroll
14837: 
14838: =item $context
14839: 
14840: =item $credits, number of credits student will earn from this class
14841: 
14842: =item $instsec, institutional course section code for student
14843: 
14844: =back
14845: 
14846: 
14847: =item *
14848: 
14849: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14850: custom role; give a custom role to a user for the level given by URL.  Specify
14851: name and domain of role author, and role name
14852: 
14853: =item *
14854: 
14855: revokerole($udom,$uname,$url,$role) : revoke a role for url
14856: 
14857: =item *
14858: 
14859: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14860: 
14861: =back
14862: 
14863: =head2 Course Infomation
14864: 
14865: =over 4
14866: 
14867: =item *
14868: 
14869: coursedescription($courseid,$options) : returns a hash of information about the
14870: specified course id, including all environment settings for the
14871: course, the description of the course will be in the hash under the
14872: key 'description'
14873: 
14874: $options is an optional parameter that if supplied is a hash reference that controls
14875: what how this function works.  It has the following key/values:
14876: 
14877: =over 4
14878: 
14879: =item freshen_cache
14880: 
14881: If defined, and the environment cache for the course is valid, it is 
14882: returned in the returned hash.
14883: 
14884: =item one_time
14885: 
14886: If defined, the last cache time is set to _now_
14887: 
14888: =item user
14889: 
14890: If defined, the supplied username is used instead of the current user.
14891: 
14892: 
14893: =back
14894: 
14895: =item *
14896: 
14897: resdata($name,$domain,$type,@which) : request for current parameter
14898: setting for a specific $type, where $type is either 'course' or 'user',
14899: @what should be a list of parameters to ask about. This routine caches
14900: answers for 10 minutes.
14901: 
14902: =item *
14903: 
14904: get_courseresdata($courseid, $domain) : dump the entire course resource
14905: data base, returning a hash that is keyed by the resource name and has
14906: values that are the resource value.  I believe that the timestamps and
14907: versions are also returned.
14908: 
14909: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14910: supplemental content area. This routine caches the number of files for 
14911: 10 minutes.
14912: 
14913: =back
14914: 
14915: =head2 Course Modification
14916: 
14917: =over 4
14918: 
14919: =item *
14920: 
14921: writecoursepref($courseid,%prefs) : write preferences (environment
14922: database) for a course
14923: 
14924: =item *
14925: 
14926: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14927: 
14928: =item *
14929: 
14930: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14931: 
14932: =item *
14933: 
14934: is_course($courseid), is_course($cdom, $cnum)
14935: 
14936: Accepts either a combined $courseid (in the form of domain_courseid) or the
14937: two component version $cdom, $cnum. It checks if the specified course exists.
14938: 
14939: Returns:
14940:     undef if the course doesn't exist, otherwise
14941:     in scalar context the combined courseid.
14942:     in list context the two components of the course identifier, domain and 
14943:     courseid.    
14944: 
14945: =back
14946: 
14947: =head2 Resource Subroutines
14948: 
14949: =over 4
14950: 
14951: =item *
14952: 
14953: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14954: 
14955: =item *
14956: 
14957: repcopy($filename) : subscribes to the requested file, and attempts to
14958: replicate from the owning library server, Might return
14959: 'unavailable', 'not_found', 'forbidden', 'ok', or
14960: 'bad_request', also attempts to grab the metadata for the
14961: resource. Expects the local filesystem pathname
14962: (/home/httpd/html/res/....)
14963: 
14964: =back
14965: 
14966: =head2 Resource Information
14967: 
14968: =over 4
14969: 
14970: =item *
14971: 
14972: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14973: and returns the value of a variety of different possible values,
14974: $varname should be a request string, and the other parameters can be
14975: used to specify who and what one is asking about. Ordinarily, $cid 
14976: does not need to be specified, as it is retrived from 
14977: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14978: within lonuserstate::loadmap() when initializing a course, before
14979: $env{'request.course.id'} has been set, so it needs to be provided
14980: in that one case.
14981: 
14982: Possible values for $varname are environment.lastname (or other item
14983: from the envirnment hash), user.name (or someother aspect about the
14984: user), resource.0.maxtries (or some other part and parameter of a
14985: resource)
14986: 
14987: =item *
14988: 
14989: directcondval($number) : get current value of a condition; reads from a state
14990: string
14991: 
14992: =item *
14993: 
14994: condval($condidx) : value of condition index based on state
14995: 
14996: =item *
14997: 
14998: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
14999: resource's metadata, $what should be either a specific key, or either
15000: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15001: packages that this resource currently uses, the last 3 arguments are 
15002: only used internally for recursive metadata.
15003: 
15004: the toolsymb is only used where the uri is for an external tool (for which
15005: the uri as well as the symb are guaranteed to be unique).
15006: 
15007: this function automatically caches all requests except any made recursively
15008: to retrieve a list of metadata keys for an imported library file ($liburi is 
15009: defined).
15010: 
15011: =item *
15012: 
15013: metadata_query($query,$custom,$customshow) : make a metadata query against the
15014: network of library servers; returns file handle of where SQL and regex results
15015: will be stored for query
15016: 
15017: =item *
15018: 
15019: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15020: return symbolic list entry (all arguments optional). 
15021: 
15022: Args: filename is the filename (including path) for the file for which a symb 
15023: is required; donotrecurse, if true will prevent calls to allowed() being made 
15024: to check access status if more than one resource was found in the bighash 
15025: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15026: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15027: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15028: cause possible symbs to be checked to determine if they are subject to content
15029: blocking, if so they will not be included as possible symbs; possibles is a
15030: ref to a hash, which, as a side effect, will be populated with all possible 
15031: symbs (content blocking not tested).
15032:  
15033: returns the data handle
15034: 
15035: =item *
15036: 
15037: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15038: and is a possible symb for the URL in $thisfn, and if is an encrypted
15039: resource that the user accessed using /enc/ returns a 1 on success, 0
15040: on failure, user must be in a course, as it assumes the existence of
15041: the course initial hash, and uses $env('request.course.id'}.  The third
15042: arg is an optional reference to a scalar.  If this arg is passed in the 
15043: call to symbverify, it will be set to 1 if the symb has been set to be 
15044: encrypted; otherwise it will be null.  
15045: 
15046: =item *
15047: 
15048: symbclean($symb) : removes versions numbers from a symb, returns the
15049: cleaned symb
15050: 
15051: =item *
15052: 
15053: is_on_map($uri) : checks if the $uri is somewhere on the current
15054: course map, user must be in a course for it to work.
15055: 
15056: =item *
15057: 
15058: numval($salt) : return random seed value (addend for rndseed)
15059: 
15060: =item *
15061: 
15062: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15063: a random seed, all arguments are optional, if they aren't sent it uses the
15064: environment to derive them. Note: if symb isn't sent and it can't get one
15065: from &symbread it will use the current time as its return value
15066: 
15067: =item *
15068: 
15069: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15070: unfakeable, receipt
15071: 
15072: =item *
15073: 
15074: receipt() : API to ireceipt working off of env values; given out to users
15075: 
15076: =item *
15077: 
15078: countacc($url) : count the number of accesses to a given URL
15079: 
15080: =item *
15081: 
15082: 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
15083: 
15084: =item *
15085: 
15086: 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)
15087: 
15088: =item *
15089: 
15090: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15091: 
15092: =item *
15093: 
15094: devalidate($symb) : devalidate temporary spreadsheet calculations,
15095: forcing spreadsheet to reevaluate the resource scores next time.
15096: 
15097: =item * 
15098: 
15099: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15100: when viewing in course context.
15101: 
15102:  input: six args -- filename (decluttered), course number, course domain,
15103:                     url, symb (if registered) and group (if this is a 
15104:                     group item -- e.g., bulletin board, group page etc.).
15105: 
15106:  output: array of five scalars --
15107:          $cfile -- url for file editing if editable on current server
15108:          $home -- homeserver of resource (i.e., for author if published,
15109:                                           or course if uploaded.).
15110:          $switchserver --  1 if server switch will be needed.
15111:          $forceedit -- 1 if icon/link should be to go to edit mode 
15112:          $forceview -- 1 if icon/link should be to go to view mode
15113: 
15114: =item *
15115: 
15116: is_course_upload($file,$cnum,$cdom)
15117: 
15118: Used in course context to determine if current file was uploaded to 
15119: the course (i.e., would be found in /userfiles/docs on the course's 
15120: homeserver.
15121: 
15122:   input: 3 args -- filename (decluttered), course number and course domain.
15123:   output: boolean -- 1 if file was uploaded.
15124: 
15125: =back
15126: 
15127: =head2 Storing/Retreiving Data
15128: 
15129: =over 4
15130: 
15131: =item *
15132: 
15133: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15134: permanently for this url; hashref needs to be given and should be a \%hashname;
15135: the remaining args aren't required and if they aren't passed or are '' they will
15136: be derived from the env (with the exception of $laststore, which is an 
15137: optional arg used when a user's submission is stored in grading).
15138: $laststore is $version=$timestamp, where $version is the most recent version
15139: number retrieved for the corresponding $symb in the $namespace db file, and
15140: $timestamp is the timestamp for that transaction (UNIX time).
15141: $laststore is currently only passed when cstore() is called by 
15142: structuretags::finalize_storage().
15143: 
15144: =item *
15145: 
15146: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15147: but uses critical subroutine
15148: 
15149: =item *
15150: 
15151: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15152: all args are optional
15153: 
15154: =item *
15155: 
15156: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15157: dumps the complete (or key matching regexp) namespace into a hash
15158: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15159: normally &store()ed into
15160: 
15161: $range should be either an integer '100' (give me the first 100
15162:                                            matching records)
15163:               or be  two integers sperated by a - with no spaces
15164:                  '30-50' (give me the 30th through the 50th matching
15165:                           records)
15166: 
15167: 
15168: =item *
15169: 
15170: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15171: replaces a &store() version of data with a replacement set of data
15172: for a particular resource in a namespace passed in the $storehash hash 
15173: reference. If $tolog is true, the transaction is logged in the courselog
15174: with an action=PUTSTORE.
15175: 
15176: =item *
15177: 
15178: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15179: works very similar to store/cstore, but all data is stored in a
15180: temporary location and can be reset using tmpreset, $storehash should
15181: be a hash reference, returns nothing on success
15182: 
15183: =item *
15184: 
15185: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15186: similar to restore, but all data is stored in a temporary location and
15187: can be reset using tmpreset. Returns a hash of values on success,
15188: error string otherwise.
15189: 
15190: =item *
15191: 
15192: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15193: deltes all keys for $symb form the temporary storage hash.
15194: 
15195: =item *
15196: 
15197: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15198: reference filled in from namesp ($udom and $uname are optional)
15199: 
15200: =item *
15201: 
15202: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15203: namesp ($udom and $uname are optional)
15204: 
15205: =item *
15206: 
15207: dump($namespace,$udom,$uname,$regexp,$range) : 
15208: dumps the complete (or key matching regexp) namespace into a hash
15209: ($udom, $uname, $regexp, $range are optional)
15210: 
15211: $range should be either an integer '100' (give me the first 100
15212:                                            matching records)
15213:               or be  two integers sperated by a - with no spaces
15214:                  '30-50' (give me the 30th through the 50th matching
15215:                           records)
15216: =item *
15217: 
15218: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15219: $store can be a scalar, an array reference, or if the amount to be 
15220: incremented is > 1, a hash reference.
15221: 
15222: ($udom and $uname are optional)
15223: 
15224: =item *
15225: 
15226: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15227: ($udom and $uname are optional)
15228: 
15229: =item *
15230: 
15231: cput($namespace,$storehash,$udom,$uname) : critical put
15232: ($udom and $uname are optional)
15233: 
15234: =item *
15235: 
15236: newput($namespace,$storehash,$udom,$uname) :
15237: 
15238: Attempts to store the items in the $storehash, but only if they don't
15239: currently exist, if this succeeds you can be certain that you have 
15240: successfully created a new key value pair in the $namespace db.
15241: 
15242: 
15243: Args:
15244:  $namespace: name of database to store values to
15245:  $storehash: hashref to store to the db
15246:  $udom: (optional) domain of user containing the db
15247:  $uname: (optional) name of user caontaining the db
15248: 
15249: Returns:
15250:  'ok' -> succeeded in storing all keys of $storehash
15251:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15252:                         least <key> already existed in the db (other
15253:                         requested keys may also already exist)
15254:  'error: <msg>' -> unable to tie the DB or other error occurred
15255:  'con_lost' -> unable to contact request server
15256:  'refused' -> action was not allowed by remote machine
15257: 
15258: 
15259: =item *
15260: 
15261: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15262: reference filled in from namesp (encrypts the return communication)
15263: ($udom and $uname are optional)
15264: 
15265: =item *
15266: 
15267: log($udom,$name,$home,$message) : write to permanent log for user; use
15268: critical subroutine
15269: 
15270: =item *
15271: 
15272: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15273: array reference filled in from namespace found in domain level on either
15274: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15275: 
15276: =item *
15277: 
15278: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15279: domain level either on specified domain server ($uhome) or primary domain 
15280: server ($udom and $uhome are optional)
15281: 
15282: =item * 
15283: 
15284: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15285: for: authentication, language, quotas, timezone, date locale, and portal URL in
15286: the target domain.
15287: 
15288: May also include additional key => value pairs for the following groups:
15289: 
15290: =over
15291: 
15292: =item
15293: disk quotas (MB allocated by default to portfolios and authoring spaces).
15294: 
15295: =over
15296: 
15297: =item defaultquota, authorquota
15298: 
15299: =back
15300: 
15301: =item
15302: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15303: portfolio for users).
15304: 
15305: =over
15306: 
15307: =item
15308: aboutme, blog, webdav, portfolio
15309: 
15310: =back
15311: 
15312: =item
15313: requestcourses: ability to request courses, and how requests are processed.
15314: 
15315: =over
15316: 
15317: =item
15318: official, unofficial, community, textbook, placement
15319: 
15320: =back
15321: 
15322: =item
15323: inststatus: types of institutional affiliation, and order in which they are displayed.
15324: 
15325: =over
15326: 
15327: =item
15328: inststatustypes, inststatusorder, inststatusguest
15329: 
15330: =back
15331: 
15332: =item
15333: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15334: for course's uploaded content.
15335: 
15336: =over
15337: 
15338: =item
15339: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15340: communityquota, textbookquota, placementquota
15341: 
15342: =back
15343: 
15344: =item
15345: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15346: on your servers.
15347: 
15348: =over
15349: 
15350: =item 
15351: remotesessions, hostedsessions
15352: 
15353: =back
15354: 
15355: =back
15356: 
15357: In cases where a domain coordinator has never used the "Set Domain Configuration"
15358: utility to create a configuration.db file on a domain's primary library server 
15359: only the following domain defaults: auth_def, auth_arg_def, lang_def
15360: -- corresponding values are authentication type (internal, krb4, krb5,
15361: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15362: will be available. Values are retrieved from cache (if current), unless the
15363: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15364: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15365: 
15366: Typical usage:
15367: 
15368: %domdefaults = &get_domain_defaults($target_domain);
15369: 
15370: =back
15371: 
15372: =head2 Network Status Functions
15373: 
15374: =over 4
15375: 
15376: =item *
15377: 
15378: dirlist() : return directory list based on URI (first arg).
15379: 
15380: Inputs: 1 required, 5 optional.
15381: 
15382: =over
15383: 
15384: =item 
15385: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15386: 
15387: =item
15388: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15389: 
15390: =item
15391: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15392: 
15393: =item
15394: $getpropath - boolean: 1 if prepend path using &propath(). 
15395: 
15396: =item
15397: $getuserdir - boolean: 1 if prepend path for "userfiles".
15398: 
15399: =item 
15400: $alternateRoot - path to prepend in place of path from $uri.
15401: 
15402: =back
15403: 
15404: Returns: Array of up to two items.
15405: 
15406: =over
15407: 
15408: a reference to an array of files/subdirectories
15409: 
15410: =over
15411: 
15412: Each element in the array of files/subdirectories is a & separated list of
15413: item name and the result of running stat on the item.  If dirlist was requested
15414: for a file instead of a directory, the item name will be ''. For a directory 
15415: listing, if the item is a metadata file, the element will end &N&M 
15416: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15417: default copyright set (1).  
15418: 
15419: =back
15420: 
15421: a scalar containing error condition (if encountered).
15422: 
15423: =over
15424: 
15425: =item 
15426: no_host (no homeserver identified for $username:$domain).
15427: 
15428: =item 
15429: no_such_host (server contacted for listing not identified as valid host).
15430: 
15431: =item 
15432: con_lost (connection to remote server failed).
15433: 
15434: =item 
15435: refused (invalid $username:$domain received on lond side).
15436: 
15437: =item 
15438: no_such_dir (directory at specified path on lond side does not exist). 
15439: 
15440: =item 
15441: empty (directory at specified path on lond side is empty).
15442: 
15443: =over
15444: 
15445: This is currently not encountered because the &ls3, &ls2, 
15446: &ls (_handler) routines on the lond side do not filter out
15447: . and .. from a directory listing. 
15448: 
15449: =back
15450: 
15451: =back
15452: 
15453: =back
15454: 
15455: =item *
15456: 
15457: spareserver() : find server with least workload from spare.tab
15458: 
15459: 
15460: =item *
15461: 
15462: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15463: if there is no corresponding loncapa host.
15464: 
15465: =back
15466: 
15467: 
15468: =head2 Apache Request
15469: 
15470: =over 4
15471: 
15472: =item *
15473: 
15474: ssi($url,%hash) : server side include, does a complete request cycle on url to
15475: localhost, posts hash
15476: 
15477: =back
15478: 
15479: =head2 Data to String to Data
15480: 
15481: =over 4
15482: 
15483: =item *
15484: 
15485: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15486: and '&' separators, supports elements that are arrayrefs and hashrefs
15487: 
15488: =item *
15489: 
15490: hashref2str($hashref) : convert a hashref into a string complete with
15491: escaping and '=' and '&' separators, supports elements that are
15492: arrayrefs and hashrefs
15493: 
15494: =item *
15495: 
15496: arrayref2str($arrayref) : convert an arrayref into a string complete
15497: with escaping and '&' separators, supports elements that are arrayrefs
15498: and hashrefs
15499: 
15500: =item *
15501: 
15502: str2hash($string) : convert string to hash using unescaping and
15503: splitting on '=' and '&', supports elements that are arrayrefs and
15504: hashrefs
15505: 
15506: =item *
15507: 
15508: str2array($string) : convert string to hash using unescaping and
15509: splitting on '&', supports elements that are arrayrefs and hashrefs
15510: 
15511: =back
15512: 
15513: =head2 Logging Routines
15514: 
15515: 
15516: These routines allow one to make log messages in the lonnet.log and
15517: lonnet.perm logfiles.
15518: 
15519: =over 4
15520: 
15521: =item *
15522: 
15523: logtouch() : make sure the logfile, lonnet.log, exists
15524: 
15525: =item *
15526: 
15527: logthis() : append message to the normal lonnet.log file, it gets
15528: preiodically rolled over and deleted.
15529: 
15530: =item *
15531: 
15532: logperm() : append a permanent message to lonnet.perm.log, this log
15533: file never gets deleted by any automated portion of the system, only
15534: messages of critical importance should go in here.
15535: 
15536: 
15537: =back
15538: 
15539: =head2 General File Helper Routines
15540: 
15541: =over 4
15542: 
15543: =item *
15544: 
15545: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15546: (a) files in /uploaded
15547:   (i) If a local copy of the file exists - 
15548:       compares modification date of local copy with last-modified date for 
15549:       definitive version stored on home server for course. If local copy is 
15550:       stale, requests a new version from the home server and stores it. 
15551:       If the original has been removed from the home server, then local copy 
15552:       is unlinked.
15553:   (ii) If local copy does not exist -
15554:       requests the file from the home server and stores it. 
15555:   
15556:   If $caller is 'uploadrep':  
15557:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15558:     for request for files originally uploaded via DOCS. 
15559:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15560:   
15561:   Otherwise:
15562:      This indicates a call from the content generation phase of the request.
15563:      -  returns the entire contents of the file or -1.
15564:      
15565: (b) files in /res
15566:    - returns the entire contents of a file or -1; 
15567:    it properly subscribes to and replicates the file if neccessary.
15568: 
15569: 
15570: =item *
15571: 
15572: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15573:                   reference
15574: 
15575: returns either a stat() list of data about the file or an empty list
15576: if the file doesn't exist or couldn't find out about it (connection
15577: problems or user unknown)
15578: 
15579: =item *
15580: 
15581: filelocation($dir,$file) : returns file system location of a file
15582: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15583: directory that relative $file lookups are to looked in ($dir of /a/dir
15584: and a file of ../bob will become /a/bob)
15585: 
15586: =item *
15587: 
15588: hreflocation($dir,$file) : returns file system location or a URL; same as
15589: filelocation except for hrefs
15590: 
15591: =item *
15592: 
15593: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15594: also removes beginning /home/httpd/html unless /priv/ follows it.
15595: 
15596: =back
15597: 
15598: =head2 Usererfile file routines (/uploaded*)
15599: 
15600: =over 4
15601: 
15602: =item *
15603: 
15604: userfileupload(): main rotine for putting a file in a user or course's
15605:                   filespace, arguments are,
15606: 
15607:  formname - required - this is the name of the element in $env where the
15608:            filename, and the contents of the file to create/modifed exist
15609:            the filename is in $env{'form.'.$formname.'.filename'} and the
15610:            contents of the file is located in $env{'form.'.$formname}
15611:  context - if coursedoc, store the file in the course of the active role
15612:              of the current user; 
15613:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15614:            if 'canceloverwrite': delete file in tmp/overwrites directory
15615:  subdir - required - subdirectory to put the file in under ../userfiles/
15616:          if undefined, it will be placed in "unknown"
15617: 
15618:  (This routine calls clean_filename() to remove any dangerous
15619:  characters from the filename, and then calls finuserfileupload() to
15620:  complete the transaction)
15621: 
15622:  returns either the url of the uploaded file (/uploaded/....) if successful
15623:  and /adm/notfound.html if unsuccessful
15624: 
15625: =item *
15626: 
15627: clean_filename(): routine for cleaing a filename up for storage in
15628:                  userfile space, argument is:
15629: 
15630:  filename - proposed filename
15631: 
15632: returns: the new clean filename
15633: 
15634: =item *
15635: 
15636: finishuserfileupload(): routine that creates and sends the file to
15637: userspace, probably shouldn't be called directly
15638: 
15639:   docuname: username or courseid of destination for the file
15640:   docudom: domain of user/course of destination for the file
15641:   formname: same as for userfileupload()
15642:   fname: filename (including subdirectories) for the file
15643:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15644:   allfiles: reference to hash used to store objects found by parser
15645:   codebase: reference to hash used for codebases of java objects found by parser
15646:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15647:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15648:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15649:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15650:   context: if 'overwrite', will move the uploaded file from its temporary location to
15651:             userfiles to facilitate overwriting a previously uploaded file with same name.
15652:   mimetype: reference to scalar to accommodate mime type determined
15653:             from File::MMagic if $parser = parse.
15654: 
15655:  returns either the url of the uploaded file (/uploaded/....) if successful
15656:  and /adm/notfound.html if unsuccessful (or an error message if context 
15657:  was 'overwrite').
15658:  
15659: 
15660: =item *
15661: 
15662: renameuserfile(): renames an existing userfile to a new name
15663: 
15664:   Args:
15665:    docuname: username or courseid of destination for the file
15666:    docudom: domain of user/course of destination for the file
15667:    old: current file name (including any subdirs under userfiles)
15668:    new: desired file name (including any subdirs under userfiles)
15669: 
15670: =item *
15671: 
15672: mkdiruserfile(): creates a directory is a userfiles dir
15673: 
15674:   Args:
15675:    docuname: username or courseid of destination for the file
15676:    docudom: domain of user/course of destination for the file
15677:    dir: dir to create (including any subdirs under userfiles)
15678: 
15679: =item *
15680: 
15681: removeuserfile(): removes a file that exists in userfiles
15682: 
15683:   Args:
15684:    docuname: username or courseid of destination for the file
15685:    docudom: domain of user/course of destination for the file
15686:    fname: filname to delete (including any subdirs under userfiles)
15687: 
15688: =item *
15689: 
15690: removeuploadedurl(): convience function for removeuserfile()
15691: 
15692:   Args:
15693:    url:  a full /uploaded/... url to delete
15694: 
15695: =item * 
15696: 
15697: get_portfile_permissions():
15698:   Args:
15699:     domain: domain of user or course contain the portfolio files
15700:     user: name of user or num of course contain the portfolio files
15701:   Returns:
15702:     hashref of a dump of the proper file_permissions.db
15703:    
15704: 
15705: =item * 
15706: 
15707: get_access_controls():
15708: 
15709: Args:
15710:   current_permissions: the hash ref returned from get_portfile_permissions()
15711:   group: (optional) the group you want the files associated with
15712:   file: (optional) the file you want access info on
15713: 
15714: Returns:
15715:     a hash (keys are file names) of hashes containing
15716:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15717:         values are XML containing access control settings (see below) 
15718: 
15719: Internal notes:
15720: 
15721:  access controls are stored in file_permissions.db as key=value pairs.
15722:     key -> path to file/file_name\0uniqueID:scope_end_start
15723:         where scope -> public,guest,course,group,domains or users.
15724:               end -> UNIX time for end of access (0 -> no end date)
15725:               start -> UNIX time for start of access
15726: 
15727:     value -> XML description of access control
15728:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15729:             <start></start>
15730:             <end></end>
15731: 
15732:             <password></password>  for scope type = guest
15733: 
15734:             <domain></domain>     for scope type = course or group
15735:             <number></number>
15736:             <roles id="">
15737:              <role></role>
15738:              <access></access>
15739:              <section></section>
15740:              <group></group>
15741:             </roles>
15742: 
15743:             <dom></dom>         for scope type = domains
15744: 
15745:             <users>             for scope type = users
15746:              <user>
15747:               <uname></uname>
15748:               <udom></udom>
15749:              </user>
15750:             </users>
15751:            </scope> 
15752:               
15753:  Access data is also aggregated for each file in an additional key=value pair:
15754:  key -> path to file/file_name\0accesscontrol 
15755:  value -> reference to hash
15756:           hash contains key = value pairs
15757:           where key = uniqueID:scope_end_start
15758:                 value = UNIX time record was last updated
15759: 
15760:           Used to improve speed of look-ups of access controls for each file.  
15761:  
15762:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15763: 
15764: =item *
15765: 
15766: modify_access_controls():
15767: 
15768: Modifies access controls for a portfolio file
15769: Args
15770: 1. file name
15771: 2. reference to hash of required changes,
15772: 3. domain
15773: 4. username
15774:   where domain,username are the domain of the portfolio owner 
15775:   (either a user or a course) 
15776: 
15777: Returns:
15778: 1. result of additions or updates ('ok' or 'error', with error message). 
15779: 2. result of deletions ('ok' or 'error', with error message).
15780: 3. reference to hash of any new or updated access controls.
15781: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15782:    key = integer (inbound ID)
15783:    value = uniqueID
15784: 
15785: =item *
15786: 
15787: get_timebased_id():
15788: 
15789: Attempts to get a unique timestamp-based suffix for use with items added to a 
15790: course via the Course Editor (e.g., folders, composite pages, 
15791: group bulletin boards).
15792: 
15793: Args: (first three required; six others optional)
15794: 
15795: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15796:    docssequence, or name of group
15797: 
15798: 2. keyid (alphanumeric): name of temporary locking key in hash,
15799:    e.g., num, boardids
15800: 
15801: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15802:    file will be named nohist_namespace.db
15803: 
15804: 4. cdom: domain of course; default is current course domain from %env
15805: 
15806: 5. cnum: course number; default is current course number from %env
15807: 
15808: 6. idtype: set to concat if an additional digit is to be appended to the 
15809:    unix timestamp to form the suffix, if the plain timestamp is already
15810:    in use.  Default is to not do this, but simply increment the unix 
15811:    timestamp by 1 until a unique key is obtained.
15812: 
15813: 7. who: holder of locking key; defaults to user:domain for user.
15814: 
15815: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15816:    retrying); default is 3.
15817: 
15818: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15819: 
15820: Returns:
15821: 
15822: 1. suffix obtained (numeric)
15823: 
15824: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15825: 
15826: 3. error: contains (localized) error message if an error occurred.
15827: 
15828: 
15829: =back
15830: 
15831: =head2 HTTP Helper Routines
15832: 
15833: =over 4
15834: 
15835: =item *
15836: 
15837: escape() : unpack non-word characters into CGI-compatible hex codes
15838: 
15839: =item *
15840: 
15841: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15842: 
15843: =back
15844: 
15845: =head1 PRIVATE SUBROUTINES
15846: 
15847: =head2 Underlying communication routines (Shouldn't call)
15848: 
15849: =over 4
15850: 
15851: =item *
15852: 
15853: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15854: 
15855: =item *
15856: 
15857: reply() : uses subreply to send a message to remote machine, logs all failures
15858: 
15859: =item *
15860: 
15861: critical() : passes a critical message to another server; if cannot
15862: get through then place message in connection buffer directory and
15863: returns con_delayed, if incapable of saving message, returns
15864: con_failed
15865: 
15866: =item *
15867: 
15868: reconlonc() : tries to reconnect lonc client processes.
15869: 
15870: =back
15871: 
15872: =head2 Resource Access Logging
15873: 
15874: =over 4
15875: 
15876: =item *
15877: 
15878: flushcourselogs() : flush (save) buffer logs and access logs
15879: 
15880: =item *
15881: 
15882: courselog($what) : save message for course in hash
15883: 
15884: =item *
15885: 
15886: courseacclog($what) : save message for course using &courselog().  Perform
15887: special processing for specific resource types (problems, exams, quizzes, etc).
15888: 
15889: =item *
15890: 
15891: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15892: as a PerlChildExitHandler
15893: 
15894: =back
15895: 
15896: =head2 Other
15897: 
15898: =over 4
15899: 
15900: =item *
15901: 
15902: symblist($mapname,%newhash) : update symbolic storage links
15903: 
15904: =back
15905: 
15906: =cut
15907: 

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