File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1376: download - view: text, annotated - select for diffs
Tue May 1 14:28:41 2018 UTC (6 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Sanity checking

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1376 2018/05/01 14:28:41 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 ($linkname,$pubname);
  656:     if ($name eq '') {
  657:         $name = 'lonID';
  658:         $linkname = 'lonLinkID';
  659:         $pubname = 'lonPubID';
  660:     }
  661:     my $lonid=$cookies{$name};
  662:     if (!$lonid) {
  663:         if (($name eq 'lonID') && ($ENV{'SERVER_PORT'} != 443) && ($linkname)) {
  664:             $lonid=$cookies{$linkname};
  665:         }
  666:         if (!$lonid) {
  667:             if (($name eq 'lonID') && ($pubname)) {
  668:                 $lonid=$cookies{$pubname};
  669:             }
  670:         }
  671:     }
  672:     return undef if (!$lonid);
  673: 
  674:     my $handle=&LONCAPA::clean_handle($lonid->value);
  675:     my $lonidsdir;
  676:     if ($name eq 'lonDAV') {
  677:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  678:     } else {
  679:         $lonidsdir=$r->dir_config('lonIDsDir');
  680:     }
  681:     if (!-e "$lonidsdir/$handle.id") {
  682:         if ((ref($domref)) && ($name eq 'lonID') && 
  683:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  684:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  685:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  686:                 $$domref = $possudom;
  687:             }
  688:         }
  689:         return undef;
  690:     }
  691: 
  692:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  693:     return undef if (!$opened);
  694: 
  695:     flock($idf,LOCK_SH);
  696:     my %disk_env;
  697:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  698: 	    &GDBM_READER(),0640)) {
  699: 	return undef;	
  700:     }
  701: 
  702:     if (!defined($disk_env{'user.name'})
  703: 	|| !defined($disk_env{'user.domain'})) {
  704: 	return undef;
  705:     }
  706: 
  707:     if (ref($userhashref) eq 'HASH') {
  708:         $userhashref->{'name'} = $disk_env{'user.name'};
  709:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  710:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  711:         if ($userhashref->{'lti'}) {
  712:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  713:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  714:         }
  715:     }
  716: 
  717:     return $handle;
  718: }
  719: 
  720: sub timed_flock {
  721:     my ($file,$lock_type) = @_;
  722:     my $failed=0;
  723:     eval {
  724: 	local $SIG{__DIE__}='DEFAULT';
  725: 	local $SIG{ALRM}=sub {
  726: 	    $failed=1;
  727: 	    die("failed lock");
  728: 	};
  729: 	alarm(13);
  730: 	flock($file,$lock_type);
  731: 	alarm(0);
  732:     };
  733:     if ($failed) {
  734: 	return undef;
  735:     } else {
  736: 	return 1;
  737:     }
  738: }
  739: 
  740: # ---------------------------------------------------------- Append Environment
  741: 
  742: sub appenv {
  743:     my ($newenv,$roles) = @_;
  744:     if (ref($newenv) eq 'HASH') {
  745:         foreach my $key (keys(%{$newenv})) {
  746:             my $refused = 0;
  747: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  748:                 $refused = 1;
  749:                 if (ref($roles) eq 'ARRAY') {
  750:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  751:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  752:                         $refused = 0;
  753:                     }
  754:                 }
  755:             }
  756:             if ($refused) {
  757:                 &logthis("<font color=\"blue\">WARNING: ".
  758:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  759:                          .'</font>');
  760: 	        delete($newenv->{$key});
  761:             } else {
  762:                 $env{$key}=$newenv->{$key};
  763:             }
  764:         }
  765:         my $lonids = $perlvar{'lonIDsDir'};
  766:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  767:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  768:             if ($opened
  769: 	        && &timed_flock($env_file,LOCK_EX)
  770: 	        &&
  771: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  772: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  773: 	        while (my ($key,$value) = each(%{$newenv})) {
  774: 	            $disk_env{$key} = $value;
  775: 	        }
  776: 	        untie(%disk_env);
  777:             }
  778:         }
  779:     }
  780:     return 'ok';
  781: }
  782: # ----------------------------------------------------- Delete from Environment
  783: 
  784: sub delenv {
  785:     my ($delthis,$regexp,$roles) = @_;
  786:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  787:         my $refused = 1;
  788:         if (ref($roles) eq 'ARRAY') {
  789:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  790:             if (grep(/^\Q$role\E$/,@{$roles})) {
  791:                 $refused = 0;
  792:             }
  793:         }
  794:         if ($refused) {
  795:             &logthis("<font color=\"blue\">WARNING: ".
  796:                      "Attempt to delete from environment ".$delthis);
  797:             return 'error';
  798:         }
  799:     }
  800:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  801:     if ($opened
  802: 	&& &timed_flock($env_file,LOCK_EX)
  803: 	&&
  804: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  805: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  806: 	foreach my $key (keys(%disk_env)) {
  807: 	    if ($regexp) {
  808:                 if ($key=~/^$delthis/) {
  809:                     delete($env{$key});
  810:                     delete($disk_env{$key});
  811:                 } 
  812:             } else {
  813:                 if ($key=~/^\Q$delthis\E/) {
  814: 		    delete($env{$key});
  815: 		    delete($disk_env{$key});
  816: 	        }
  817:             }
  818: 	}
  819: 	untie(%disk_env);
  820:     }
  821:     return 'ok';
  822: }
  823: 
  824: sub get_env_multiple {
  825:     my ($name) = @_;
  826:     my @values;
  827:     if (defined($env{$name})) {
  828:         # exists is it an array
  829:         if (ref($env{$name})) {
  830:             @values=@{ $env{$name} };
  831:         } else {
  832:             $values[0]=$env{$name};
  833:         }
  834:     }
  835:     return(@values);
  836: }
  837: 
  838: # ------------------------------------------------------------------- Locking
  839: 
  840: sub set_lock {
  841:     my ($text)=@_;
  842:     $locknum++;
  843:     my $id=$$.'-'.$locknum;
  844:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  845:              'session.lock.'.$id => $text});
  846:     return $id;
  847: }
  848: 
  849: sub get_locks {
  850:     my $num=0;
  851:     my %texts=();
  852:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  853:        if ($lock=~/\w/) {
  854:           $num++;
  855:           $texts{$lock}=$env{'session.lock.'.$lock};
  856:        }
  857:    }
  858:    return ($num,%texts);
  859: }
  860: 
  861: sub remove_lock {
  862:     my ($id)=@_;
  863:     my $newlocks='';
  864:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  865:        if (($lock=~/\w/) && ($lock ne $id)) {
  866:           $newlocks.=','.$lock;
  867:        }
  868:     }
  869:     &appenv({'session.locks' => $newlocks});
  870:     &delenv('session.lock.'.$id);
  871: }
  872: 
  873: sub remove_all_locks {
  874:     my $activelocks=$env{'session.locks'};
  875:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  876:        if ($lock=~/\w/) {
  877:           &remove_lock($lock);
  878:        }
  879:     }
  880: }
  881: 
  882: 
  883: # ------------------------------------------ Find out current server userload
  884: sub userload {
  885:     my $numusers=0;
  886:     {
  887: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  888: 	my $filename;
  889: 	my $curtime=time;
  890: 	while ($filename=readdir(LONIDS)) {
  891: 	    next if ($filename eq '.' || $filename eq '..');
  892: 	    next if ($filename =~ /publicuser_\d+\.id/);
  893: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  894: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  895: 	}
  896: 	closedir(LONIDS);
  897:     }
  898:     my $userloadpercent=0;
  899:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  900:     if ($maxuserload) {
  901: 	$userloadpercent=100*$numusers/$maxuserload;
  902:     }
  903:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  904:     return $userloadpercent;
  905: }
  906: 
  907: # ------------------------------ Find server with least workload from spare.tab
  908: 
  909: sub spareserver {
  910:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  911:     my $spare_server;
  912:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  913:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  914:                                                      :  $userloadpercent;
  915:     my ($uint_dom,$remotesessions);
  916:     if (($udom ne '') && (&domain($udom) ne '')) {
  917:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  918:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  919:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  920:         $remotesessions = $udomdefaults{'remotesessions'};
  921:     }
  922:     my $spareshash = &this_host_spares($udom);
  923:     if (ref($spareshash) eq 'HASH') {
  924:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  925:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  926:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  927:                                              $try_server));
  928: 	        ($spare_server, $lowest_load) =
  929: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  930:             }
  931:         }
  932: 
  933:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  934: 
  935:         if (!$found_server) {
  936:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  937: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  938:                     next unless (&spare_can_host($udom,$uint_dom,
  939:                                                  $remotesessions,$try_server));
  940: 	            ($spare_server, $lowest_load) =
  941: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  942:                 }
  943: 	    }
  944:         }
  945:     }
  946: 
  947:     if (!$want_server_name) {
  948:         my $protocol = 'http';
  949:         if ($protocol{$spare_server} eq 'https') {
  950:             $protocol = $protocol{$spare_server};
  951:         }
  952:         if (defined($spare_server)) {
  953:             my $hostname = &hostname($spare_server);
  954:             if (defined($hostname)) {
  955: 	        $spare_server = $protocol.'://'.$hostname;
  956:             }
  957:         }
  958:     }
  959:     return $spare_server;
  960: }
  961: 
  962: sub compare_server_load {
  963:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  964: 
  965:     if ($required) {
  966:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  967:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  968:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  969:         if (($major eq '' && $minor eq '') ||
  970:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  971:             return ($spare_server,$lowest_load);
  972:         }
  973:     }
  974: 
  975:     my $loadans     = &reply('load',    $try_server);
  976:     my $userloadans = &reply('userload',$try_server);
  977: 
  978:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  979: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  980:     }
  981: 
  982:     my $load;
  983:     if ($loadans =~ /\d/) {
  984: 	if ($userloadans =~ /\d/) {
  985: 	    #both are numbers, pick the bigger one
  986: 	    $load = ($loadans > $userloadans) ? $loadans 
  987: 		                              : $userloadans;
  988: 	} else {
  989: 	    $load = $loadans;
  990: 	}
  991:     } else {
  992: 	$load = $userloadans;
  993:     }
  994: 
  995:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  996: 	$spare_server = $try_server;
  997: 	$lowest_load  = $load;
  998:     }
  999:     return ($spare_server,$lowest_load);
 1000: }
 1001: 
 1002: # --------------------------- ask offload servers if user already has a session
 1003: sub find_existing_session {
 1004:     my ($udom,$uname) = @_;
 1005:     my $spareshash = &this_host_spares($udom);
 1006:     if (ref($spareshash) eq 'HASH') {
 1007:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1008:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1009:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1010:             }
 1011:         }
 1012:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1013:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1014:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1015:             }
 1016:         }
 1017:     }
 1018:     return;
 1019: }
 1020: 
 1021: # -------------------------------- ask if server already has a session for user
 1022: sub has_user_session {
 1023:     my ($lonid,$udom,$uname) = @_;
 1024:     my $result = &reply(join(':','userhassession',
 1025: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1026:     return 1 if ($result eq 'ok');
 1027: 
 1028:     return 0;
 1029: }
 1030: 
 1031: # --------- determine least loaded server in a user's domain which allows login
 1032: 
 1033: sub choose_server {
 1034:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1035:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1036:     my %servers = &get_servers($udom);
 1037:     my $lowest_load = 30000;
 1038:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1039:     if ($skiploadbal) {
 1040:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1041:         unless (defined($cached)) {
 1042:             my $cachetime = 60*60*24;
 1043:             my %domconfig =
 1044:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1045:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1046:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1047:                                            $cachetime);
 1048:             }
 1049:         }
 1050:     }
 1051:     foreach my $lonhost (keys(%servers)) {
 1052:         if ($skiploadbal) {
 1053:             if (ref($balancers) eq 'HASH') {
 1054:                 next if (exists($balancers->{$lonhost}));
 1055:             }
 1056:         }   
 1057:         my $loginvia;
 1058:         if ($checkloginvia) {
 1059:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1060:             if ($loginvia) {
 1061:                 my ($server,$path) = split(/:/,$loginvia);
 1062:                 ($login_host, $lowest_load) =
 1063:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1064:                 if ($login_host eq $server) {
 1065:                     $portal_path = $path;
 1066:                     $isredirect = 1;
 1067:                 }
 1068:             } else {
 1069:                 ($login_host, $lowest_load) =
 1070:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1071:                 if ($login_host eq $lonhost) {
 1072:                     $portal_path = '';
 1073:                     $isredirect = ''; 
 1074:                 }
 1075:             }
 1076:         } else {
 1077:             ($login_host, $lowest_load) =
 1078:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1079:         }
 1080:     }
 1081:     if ($login_host ne '') {
 1082:         $hostname = &hostname($login_host);
 1083:     }
 1084:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1085: }
 1086: 
 1087: # --------------------------------------------- Try to change a user's password
 1088: 
 1089: sub changepass {
 1090:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1091:     $currentpass = &escape($currentpass);
 1092:     $newpass     = &escape($newpass);
 1093:     my $lonhost = $perlvar{'lonHostID'};
 1094:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1095: 		       $server);
 1096:     if (! $answer) {
 1097: 	&logthis("No reply on password change request to $server ".
 1098: 		 "by $uname in domain $udom.");
 1099:     } elsif ($answer =~ "^ok") {
 1100:         &logthis("$uname in $udom successfully changed their password ".
 1101: 		 "on $server.");
 1102:     } elsif ($answer =~ "^pwchange_failure") {
 1103: 	&logthis("$uname in $udom was unable to change their password ".
 1104: 		 "on $server.  The action was blocked by either lcpasswd ".
 1105: 		 "or pwchange");
 1106:     } elsif ($answer =~ "^non_authorized") {
 1107:         &logthis("$uname in $udom did not get their password correct when ".
 1108: 		 "attempting to change it on $server.");
 1109:     } elsif ($answer =~ "^auth_mode_error") {
 1110:         &logthis("$uname in $udom attempted to change their password despite ".
 1111: 		 "not being locally or internally authenticated on $server.");
 1112:     } elsif ($answer =~ "^unknown_user") {
 1113:         &logthis("$uname in $udom attempted to change their password ".
 1114: 		 "on $server but were unable to because $server is not ".
 1115: 		 "their home server.");
 1116:     } elsif ($answer =~ "^refused") {
 1117: 	&logthis("$server refused to change $uname in $udom password because ".
 1118: 		 "it was sent an unencrypted request to change the password.");
 1119:     } elsif ($answer =~ "invalid_client") {
 1120:         &logthis("$server refused to change $uname in $udom password because ".
 1121:                  "it was a reset by e-mail originating from an invalid server.");
 1122:     }
 1123:     return $answer;
 1124: }
 1125: 
 1126: # ----------------------- Try to determine user's current authentication scheme
 1127: 
 1128: sub queryauthenticate {
 1129:     my ($uname,$udom)=@_;
 1130:     my $uhome=&homeserver($uname,$udom);
 1131:     if (!$uhome) {
 1132: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1133: 	return 'no_host';
 1134:     }
 1135:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1136:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1137: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1138:     }
 1139:     return $answer;
 1140: }
 1141: 
 1142: # --------- Try to authenticate user from domain's lib servers (first this one)
 1143: 
 1144: sub authenticate {
 1145:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1146:     $upass=&escape($upass);
 1147:     $uname= &LONCAPA::clean_username($uname);
 1148:     my $uhome=&homeserver($uname,$udom,1);
 1149:     my $newhome;
 1150:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1151: # Maybe the machine was offline and only re-appeared again recently?
 1152:         &reconlonc();
 1153: # One more
 1154: 	$uhome=&homeserver($uname,$udom,1);
 1155:         if (($uhome eq 'no_host') && $checkdefauth) {
 1156:             if (defined(&domain($udom,'primary'))) {
 1157:                 $newhome=&domain($udom,'primary');
 1158:             }
 1159:             if ($newhome ne '') {
 1160:                 $uhome = $newhome;
 1161:             }
 1162:         }
 1163: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1164: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1165: 	    return 'no_host';
 1166:         }
 1167:     }
 1168:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1169:     if ($answer eq 'authorized') {
 1170:         if ($newhome) {
 1171:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1172:             return 'no_account_on_host'; 
 1173:         } else {
 1174:             &logthis("User $uname at $udom authorized by $uhome");
 1175:             return $uhome;
 1176:         }
 1177:     }
 1178:     if ($answer eq 'non_authorized') {
 1179: 	&logthis("User $uname at $udom rejected by $uhome");
 1180: 	return 'no_host'; 
 1181:     }
 1182:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1183:     return 'no_host';
 1184: }
 1185: 
 1186: sub can_host_session {
 1187:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1188:     my $canhost = 1;
 1189:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1190:     if (ref($remotesessions) eq 'HASH') {
 1191:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1192:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1193:                 $canhost = 0;
 1194:             } else {
 1195:                 $canhost = 1;
 1196:             }
 1197:         }
 1198:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1199:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1200:                 $canhost = 1;
 1201:             } else {
 1202:                 $canhost = 0;
 1203:             }
 1204:         }
 1205:         if ($canhost) {
 1206:             if ($remotesessions->{'version'} ne '') {
 1207:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1208:                 if ($reqmajor ne '' && $reqminor ne '') {
 1209:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1210:                         my $major = $1;
 1211:                         my $minor = $2;
 1212:                         if (($major < $reqmajor ) ||
 1213:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1214:                             $canhost = 0;
 1215:                         }
 1216:                     } else {
 1217:                         $canhost = 0;
 1218:                     }
 1219:                 }
 1220:             }
 1221:         }
 1222:     }
 1223:     if ($canhost) {
 1224:         if (ref($hostedsessions) eq 'HASH') {
 1225:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1226:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1227:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1228:                 if (($uint_dom ne '') && 
 1229:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1230:                     $canhost = 0;
 1231:                 } else {
 1232:                     $canhost = 1;
 1233:                 }
 1234:             }
 1235:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1236:                 if (($uint_dom ne '') && 
 1237:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1238:                     $canhost = 1;
 1239:                 } else {
 1240:                     $canhost = 0;
 1241:                 }
 1242:             }
 1243:         }
 1244:     }
 1245:     return $canhost;
 1246: }
 1247: 
 1248: sub spare_can_host {
 1249:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1250:     my $canhost=1;
 1251:     my $try_server_hostname = &hostname($try_server);
 1252:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1253:     my $serverhomedom = &host_domain($serverhomeID);
 1254:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1255:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1256:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1257:             $canhost = 0;
 1258:         }
 1259:     }
 1260:     if (($canhost) && ($uint_dom)) {
 1261:         my @intdoms;
 1262:         my $internet_names = &get_internet_names($try_server);
 1263:         if (ref($internet_names) eq 'ARRAY') {
 1264:             @intdoms = @{$internet_names};
 1265:         }
 1266:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1267:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1268:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1269:                                          $remotesessions,
 1270:                                          $defdomdefaults{'hostedsessions'});
 1271:         }
 1272:     }
 1273:     return $canhost;
 1274: }
 1275: 
 1276: sub this_host_spares {
 1277:     my ($dom) = @_;
 1278:     my ($dom_in_use,$lonhost_in_use,$result);
 1279:     my @hosts = &current_machine_ids();
 1280:     foreach my $lonhost (@hosts) {
 1281:         if (&host_domain($lonhost) eq $dom) {
 1282:             $dom_in_use = $dom;
 1283:             $lonhost_in_use = $lonhost;
 1284:             last;
 1285:         }
 1286:     }
 1287:     if ($dom_in_use ne '') {
 1288:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1289:     }
 1290:     if (ref($result) ne 'HASH') {
 1291:         $lonhost_in_use = $perlvar{'lonHostID'};
 1292:         $dom_in_use = &host_domain($lonhost_in_use);
 1293:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1294:         if (ref($result) ne 'HASH') {
 1295:             $result = \%spareid;
 1296:         }
 1297:     }
 1298:     return $result;
 1299: }
 1300: 
 1301: sub spares_for_offload  {
 1302:     my ($dom_in_use,$lonhost_in_use) = @_;
 1303:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1304:     if (defined($cached)) {
 1305:         return $result;
 1306:     } else {
 1307:         my $cachetime = 60*60*24;
 1308:         my %domconfig =
 1309:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1310:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1311:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1312:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1313:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1314:                 }
 1315:             }
 1316:         }
 1317:     }
 1318:     return;
 1319: }
 1320: 
 1321: sub get_lonbalancer_config {
 1322:     my ($servers) = @_;
 1323:     my ($currbalancer,$currtargets);
 1324:     if (ref($servers) eq 'HASH') {
 1325:         foreach my $server (keys(%{$servers})) {
 1326:             my %what = (
 1327:                          spareid => 1,
 1328:                          perlvar => 1,
 1329:                        );
 1330:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1331:             if ($result eq 'ok') {
 1332:                 if (ref($returnhash) eq 'HASH') {
 1333:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1334:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1335:                             $currbalancer = $server;
 1336:                             $currtargets = {};
 1337:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1338:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1339:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1340:                                 }
 1341:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1342:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1343:                                 }
 1344:                             }
 1345:                             last;
 1346:                         }
 1347:                     }
 1348:                 }
 1349:             }
 1350:         }
 1351:     }
 1352:     return ($currbalancer,$currtargets);
 1353: }
 1354: 
 1355: sub check_loadbalancing {
 1356:     my ($uname,$udom,$caller) = @_;
 1357:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1358:         $rule_in_effect,$offloadto,$otherserver);
 1359:     my $lonhost = $perlvar{'lonHostID'};
 1360:     my @hosts = &current_machine_ids();
 1361:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1362:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1363:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1364:     my $serverhomedom = &host_domain($lonhost);
 1365:     my $domneedscache;
 1366:     my $cachetime = 60*60*24;
 1367: 
 1368:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1369:         $dom_in_use = $udom;
 1370:         $homeintdom = 1;
 1371:     } else {
 1372:         $dom_in_use = $serverhomedom;
 1373:     }
 1374:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1375:     unless (defined($cached)) {
 1376:         my %domconfig =
 1377:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1378:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1379:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1380:         } else {
 1381:             $domneedscache = $dom_in_use;
 1382:         }
 1383:     }
 1384:     if (ref($result) eq 'HASH') {
 1385:         ($is_balancer,$currtargets,$currrules) = 
 1386:             &check_balancer_result($result,@hosts);
 1387:         if ($is_balancer) {
 1388:             if (ref($currrules) eq 'HASH') {
 1389:                 if ($homeintdom) {
 1390:                     if ($uname ne '') {
 1391:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1392:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1393:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1394:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1395:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1396:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1397:                             }
 1398:                         }
 1399:                         if ($rule_in_effect eq '') {
 1400:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1401:                             if ($userenv{'inststatus'} ne '') {
 1402:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1403:                                 my ($othertitle,$usertypes,$types) =
 1404:                                     &Apache::loncommon::sorted_inst_types($udom);
 1405:                                 if (ref($types) eq 'ARRAY') {
 1406:                                     foreach my $type (@{$types}) {
 1407:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1408:                                             if (exists($currrules->{$type})) {
 1409:                                                 $rule_in_effect = $currrules->{$type};
 1410:                                             }
 1411:                                         }
 1412:                                     }
 1413:                                 }
 1414:                             } else {
 1415:                                 if (exists($currrules->{'default'})) {
 1416:                                     $rule_in_effect = $currrules->{'default'};
 1417:                                 }
 1418:                             }
 1419:                         }
 1420:                     } else {
 1421:                         if (exists($currrules->{'default'})) {
 1422:                             $rule_in_effect = $currrules->{'default'};
 1423:                         }
 1424:                     }
 1425:                 } else {
 1426:                     if ($currrules->{'_LC_external'} ne '') {
 1427:                         $rule_in_effect = $currrules->{'_LC_external'};
 1428:                     }
 1429:                 }
 1430:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1431:                                                        $uname,$udom);
 1432:             }
 1433:         }
 1434:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1435:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1436:         unless (defined($cached)) {
 1437:             my %domconfig =
 1438:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1439:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1440:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1441:             } else {
 1442:                 $domneedscache = $serverhomedom;
 1443:             }
 1444:         }
 1445:         if (ref($result) eq 'HASH') {
 1446:             ($is_balancer,$currtargets,$currrules) = 
 1447:                 &check_balancer_result($result,@hosts);
 1448:             if ($is_balancer) {
 1449:                 if (ref($currrules) eq 'HASH') {
 1450:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1451:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1452:                     }
 1453:                 }
 1454:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1455:                                                        $uname,$udom);
 1456:             }
 1457:         } else {
 1458:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1459:                 $is_balancer = 1;
 1460:                 $offloadto = &this_host_spares($dom_in_use);
 1461:             }
 1462:             unless (defined($cached)) {
 1463:                 $domneedscache = $serverhomedom;
 1464:             }
 1465:         }
 1466:     } else {
 1467:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1468:             $is_balancer = 1;
 1469:             $offloadto = &this_host_spares($dom_in_use);
 1470:         }
 1471:         unless (defined($cached)) {
 1472:             $domneedscache = $serverhomedom;
 1473:         }
 1474:     }
 1475:     if ($domneedscache) {
 1476:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1477:     }
 1478:     if ($is_balancer) {
 1479:         my $lowest_load = 30000;
 1480:         if (ref($offloadto) eq 'HASH') {
 1481:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1482:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1483:                     ($otherserver,$lowest_load) =
 1484:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1485:                 }
 1486:             }
 1487:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1488: 
 1489:             if (!$found_server) {
 1490:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1491:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1492:                         ($otherserver,$lowest_load) =
 1493:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1494:                     }
 1495:                 }
 1496:             }
 1497:         } elsif (ref($offloadto) eq 'ARRAY') {
 1498:             if (@{$offloadto} == 1) {
 1499:                 $otherserver = $offloadto->[0];
 1500:             } elsif (@{$offloadto} > 1) {
 1501:                 foreach my $try_server (@{$offloadto}) {
 1502:                     ($otherserver,$lowest_load) =
 1503:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1504:                 }
 1505:             }
 1506:         }
 1507:         unless ($caller eq 'login') {
 1508:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1509:                 $is_balancer = 0;
 1510:                 if ($uname ne '' && $udom ne '') {
 1511:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1512:                     
 1513:                         &appenv({'user.loadbalexempt'     => $lonhost,  
 1514:                                  'user.loadbalcheck.time' => time});
 1515:                     }
 1516:                 }
 1517:             }
 1518:         }
 1519:     }
 1520:     return ($is_balancer,$otherserver);
 1521: }
 1522: 
 1523: sub check_balancer_result {
 1524:     my ($result,@hosts) = @_;
 1525:     my ($is_balancer,$currtargets,$currrules);
 1526:     if (ref($result) eq 'HASH') {
 1527:         if ($result->{'lonhost'} ne '') {
 1528:             my $currbalancer = $result->{'lonhost'};
 1529:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1530:                 $is_balancer = 1;
 1531:                 $currtargets = $result->{'targets'};
 1532:                 $currrules = $result->{'rules'};
 1533:             }
 1534:         } else {
 1535:             foreach my $key (keys(%{$result})) {
 1536:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1537:                     (ref($result->{$key}) eq 'HASH')) {
 1538:                     $is_balancer = 1;
 1539:                     $currrules = $result->{$key}{'rules'};
 1540:                     $currtargets = $result->{$key}{'targets'};
 1541:                     last;
 1542:                 }
 1543:             }
 1544:         }
 1545:     }
 1546:     return ($is_balancer,$currtargets,$currrules);
 1547: }
 1548: 
 1549: sub get_loadbalancer_targets {
 1550:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1551:     my $offloadto;
 1552:     if ($rule_in_effect eq 'none') {
 1553:         return [$perlvar{'lonHostID'}];
 1554:     } elsif ($rule_in_effect eq '') {
 1555:         $offloadto = $currtargets;
 1556:     } else {
 1557:         if ($rule_in_effect eq 'homeserver') {
 1558:             my $homeserver = &homeserver($uname,$udom);
 1559:             if ($homeserver ne 'no_host') {
 1560:                 $offloadto = [$homeserver];
 1561:             }
 1562:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1563:             my %domconfig =
 1564:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1565:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1566:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1567:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1568:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1569:                     }
 1570:                 }
 1571:             } else {
 1572:                 my %servers = &internet_dom_servers($udom);
 1573:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1574:                 if (&hostname($remotebalancer) ne '') {
 1575:                     $offloadto = [$remotebalancer];
 1576:                 }
 1577:             }
 1578:         } elsif (&hostname($rule_in_effect) ne '') {
 1579:             $offloadto = [$rule_in_effect];
 1580:         }
 1581:     }
 1582:     return $offloadto;
 1583: }
 1584: 
 1585: sub internet_dom_servers {
 1586:     my ($dom) = @_;
 1587:     my (%uniqservers,%servers);
 1588:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1589:     my @machinedoms = &machine_domains($primaryserver);
 1590:     foreach my $mdom (@machinedoms) {
 1591:         my %currservers = %servers;
 1592:         my %server = &get_servers($mdom);
 1593:         %servers = (%currservers,%server);
 1594:     }
 1595:     my %by_hostname;
 1596:     foreach my $id (keys(%servers)) {
 1597:         push(@{$by_hostname{$servers{$id}}},$id);
 1598:     }
 1599:     foreach my $hostname (sort(keys(%by_hostname))) {
 1600:         if (@{$by_hostname{$hostname}} > 1) {
 1601:             my $match = 0;
 1602:             foreach my $id (@{$by_hostname{$hostname}}) {
 1603:                 if (&host_domain($id) eq $dom) {
 1604:                     $uniqservers{$id} = $hostname;
 1605:                     $match = 1;
 1606:                 }
 1607:             }
 1608:             unless ($match) {
 1609:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1610:             }
 1611:         } else {
 1612:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1613:         }
 1614:     }
 1615:     return %uniqservers;
 1616: }
 1617: 
 1618: sub trusted_domains {
 1619:     my ($cmdtype,$calldom) = @_;
 1620:     my ($trusted,$untrusted);
 1621:     if (&domain($calldom) eq '') {
 1622:         return ($trusted,$untrusted);
 1623:     }
 1624:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1625:         return ($trusted,$untrusted);
 1626:     }
 1627:     my $callprimary = &domain($calldom,'primary');
 1628:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1629:     if ($intcalldom eq '') {
 1630:         return ($trusted,$untrusted);
 1631:     }
 1632: 
 1633:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1634:     unless (defined($cached)) {
 1635:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1636:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1637:         $trustconfig = $domconfig{'trust'};
 1638:     }
 1639:     if (ref($trustconfig)) {
 1640:         my (%possexc,%possinc,@allexc,@allinc); 
 1641:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1642:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1643:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1644:             }
 1645:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1646:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1647:             }
 1648:         }
 1649:         if (keys(%possexc)) {
 1650:             if (keys(%possinc)) {
 1651:                 foreach my $key (sort(keys(%possexc))) {
 1652:                     next if ($key eq $intcalldom);
 1653:                     unless ($possinc{$key}) {
 1654:                         push(@allexc,$key);
 1655:                     }
 1656:                 }
 1657:             } else {
 1658:                 @allexc = sort(keys(%possexc));
 1659:             }
 1660:         }
 1661:         if (keys(%possinc)) {
 1662:             $possinc{$intcalldom} = 1;
 1663:             @allinc = sort(keys(%possinc));
 1664:         }
 1665:         if ((@allexc > 0) || (@allinc > 0)) {
 1666:             my %doms_by_intdom;
 1667:             my %allintdoms = &all_host_intdom();
 1668:             my %alldoms = &all_host_domain();
 1669:             foreach my $key (%allintdoms) {
 1670:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1671:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1672:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1673:                     }
 1674:                 } else {
 1675:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1676:                 }
 1677:             }
 1678:             foreach my $exc (@allexc) {
 1679:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1680:                     $untrusted = $doms_by_intdom{$exc};
 1681:                 }
 1682:             }
 1683:             foreach my $inc (@allinc) {
 1684:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1685:                     $trusted = $doms_by_intdom{$inc};
 1686:                 }
 1687:             }
 1688:         }
 1689:     }
 1690:     return ($trusted,$untrusted);
 1691: }
 1692: 
 1693: sub will_trust {
 1694:     my ($cmdtype,$domain,$possdom) = @_;
 1695:     return 1 if ($domain eq $possdom);
 1696:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1697:     my $willtrust; 
 1698:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1699:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1700:             $willtrust = 1;
 1701:         }
 1702:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1703:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1704:             $willtrust = 1;
 1705:         }
 1706:     } else {
 1707:         $willtrust = 1;
 1708:     }
 1709:     return $willtrust;
 1710: }
 1711: 
 1712: # ---------------------- Find the homebase for a user from domain's lib servers
 1713: 
 1714: my %homecache;
 1715: sub homeserver {
 1716:     my ($uname,$udom,$ignoreBadCache)=@_;
 1717:     my $index="$uname:$udom";
 1718: 
 1719:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1720: 
 1721:     my %servers = &get_servers($udom,'library');
 1722:     foreach my $tryserver (keys(%servers)) {
 1723:         next if ($ignoreBadCache ne 'true' && 
 1724: 		 exists($badServerCache{$tryserver}));
 1725: 
 1726: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1727: 	if ($answer eq 'found') {
 1728: 	    delete($badServerCache{$tryserver}); 
 1729: 	    return $homecache{$index}=$tryserver;
 1730: 	} elsif ($answer eq 'no_host') {
 1731: 	    $badServerCache{$tryserver}=1;
 1732: 	}
 1733:     }    
 1734:     return 'no_host';
 1735: }
 1736: 
 1737: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1738: 
 1739: sub idget {
 1740:     my ($udom,$idsref,$namespace)=@_;
 1741:     my %returnhash=();
 1742:     my @ids=(); 
 1743:     if (ref($idsref) eq 'ARRAY') {
 1744:         @ids = @{$idsref};
 1745:     } else {
 1746:         return %returnhash; 
 1747:     }
 1748:     if ($namespace eq '') {
 1749:         $namespace = 'ids';
 1750:     }
 1751:     
 1752:     my %servers = &get_servers($udom,'library');
 1753:     foreach my $tryserver (keys(%servers)) {
 1754: 	my $idlist=join('&', map { &escape($_); } @ids);
 1755: 	if ($namespace eq 'ids') {
 1756: 	    $idlist=~tr/A-Z/a-z/;
 1757: 	}
 1758: 	my $reply;
 1759: 	if ($namespace eq 'ids') {
 1760: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1761: 	} else {
 1762: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1763: 	}
 1764: 	my @answer=();
 1765: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1766: 	    @answer=split(/\&/,$reply);
 1767: 	}                    ;
 1768: 	my $i;
 1769: 	for ($i=0;$i<=$#ids;$i++) {
 1770: 	    if ($answer[$i]) {
 1771: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1772: 	    }
 1773: 	}
 1774:     }
 1775:     return %returnhash;
 1776: }
 1777: 
 1778: # ------------------------------------- Find the IDs behind a list of usernames
 1779: 
 1780: sub idrget {
 1781:     my ($udom,@unames)=@_;
 1782:     my %returnhash=();
 1783:     foreach my $uname (@unames) {
 1784:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1785:     }
 1786:     return %returnhash;
 1787: }
 1788: 
 1789: # Store away a list of names and associated student/employee IDs or clicker IDs
 1790: 
 1791: sub idput {
 1792:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1793:     my %servers=();
 1794:     my %ids=();
 1795:     my %byid = ();
 1796:     if (ref($idsref) eq 'HASH') {
 1797:         %ids=%{$idsref};
 1798:     }
 1799:     if ($namespace eq '') {
 1800:         $namespace = 'ids'; 
 1801:     }
 1802:     foreach my $uname (keys(%ids)) {
 1803: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1804:         if ($uhom eq '') {
 1805:             $uhom=&homeserver($uname,$udom);
 1806:         }
 1807:         if ($uhom ne 'no_host') {
 1808:             my $esc_unam=&escape($uname);
 1809:             if ($namespace eq 'ids') {
 1810:                 my $id=&escape($ids{$uname});
 1811:                 $id=~tr/A-Z/a-z/;
 1812:                 my $esc_unam=&escape($uname);
 1813:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1814:             } else {
 1815:                 my @currids = split(/,/,$ids{$uname});
 1816:                 foreach my $id (@currids) {
 1817:                     $byid{$uhom}{$id} .= $uname.',';
 1818:                 }
 1819:             }
 1820:         }
 1821:     }
 1822:     if ($namespace eq 'clickers') {
 1823:         foreach my $server (keys(%byid)) {
 1824:             if (ref($byid{$server}) eq 'HASH') {
 1825:                 foreach my $id (keys(%{$byid{$server}})) {
 1826:                     $byid{$server} =~ s/,$//;
 1827:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1828:                 }
 1829:             }
 1830:         }
 1831:     }
 1832:     foreach my $server (keys(%servers)) {
 1833:         $servers{$server} =~ s/\&$//;
 1834:         if ($namespace eq 'ids') {     
 1835:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1836:         } else {
 1837:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1838:         }
 1839:     }
 1840: }
 1841: 
 1842: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1843: 
 1844: sub iddel {
 1845:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1846:     my %result=();
 1847:     my %ids=();
 1848:     my %byid = ();
 1849:     if (ref($idshashref) eq 'HASH') {
 1850:         %ids=%{$idshashref};
 1851:     } else {
 1852:         return %result;
 1853:     }
 1854:     if ($namespace eq '') {
 1855:         $namespace = 'ids';
 1856:     }
 1857:     my %servers=();
 1858:     while (my ($id,$unamestr) = each(%ids)) {
 1859:         if ($namespace eq 'ids') {
 1860:             my $uhom = $uhome;
 1861:             if ($uhom eq '') { 
 1862:                 $uhom=&homeserver($unamestr,$udom);
 1863:             }
 1864:             if ($uhom ne 'no_host') {
 1865:                 $servers{$uhom}.='&'.&escape($id);
 1866:             }
 1867:          } else {
 1868:             my @curritems = split(/,/,$ids{$id});
 1869:             foreach my $uname (@curritems) {
 1870:                 my $uhom = $uhome;
 1871:                 if ($uhom eq '') {
 1872:                     $uhom=&homeserver($uname,$udom);
 1873:                 }
 1874:                 if ($uhom ne 'no_host') { 
 1875:                     $byid{$uhom}{$id} .= $uname.',';
 1876:                 }
 1877:             }
 1878:         }
 1879:     }
 1880:     if ($namespace eq 'clickers') {
 1881:         foreach my $server (keys(%byid)) {
 1882:             if (ref($byid{$server}) eq 'HASH') {
 1883:                 foreach my $id (keys(%{$byid{$server}})) {
 1884:                     $byid{$server}{$id} =~ s/,$//;
 1885:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 1886:                 }
 1887:             }
 1888:         }
 1889:     }
 1890:     foreach my $server (keys(%servers)) {
 1891:         $servers{$server} =~ s/\&$//;
 1892:         if ($namespace eq 'ids') {
 1893:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1894:         } elsif ($namespace eq 'clickers') {
 1895:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 1896:         }
 1897:     }
 1898:     return %result;
 1899: }
 1900: 
 1901: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 1902: 
 1903: sub updateclickers {
 1904:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 1905:     my %clickers;
 1906:     if (ref($idshashref) eq 'HASH') {
 1907:         %clickers=%{$idshashref};
 1908:     } else {
 1909:         return;
 1910:     }
 1911:     my $items='';
 1912:     foreach my $item (keys(%clickers)) {
 1913:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 1914:     }
 1915:     $items=~s/\&$//;
 1916:     my $request = "updateclickers:$udom:$action:$items";
 1917:     if ($critical) {
 1918:         return &critical($request,$uhome);
 1919:     } else {
 1920:         return &reply($request,$uhome);
 1921:     }
 1922: }
 1923: 
 1924: # ------------------------------dump from db file owned by domainconfig user
 1925: sub dump_dom {
 1926:     my ($namespace, $udom, $regexp) = @_;
 1927: 
 1928:     $udom ||= $env{'user.domain'};
 1929: 
 1930:     return () unless $udom;
 1931: 
 1932:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1933: }
 1934: 
 1935: # ------------------------------------------ get items from domain db files   
 1936: 
 1937: sub get_dom {
 1938:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1939:     return if ($udom eq 'public');
 1940:     my $items='';
 1941:     foreach my $item (@$storearr) {
 1942:         $items.=&escape($item).'&';
 1943:     }
 1944:     $items=~s/\&$//;
 1945:     if (!$udom) {
 1946:         $udom=$env{'user.domain'};
 1947:         return if ($udom eq 'public');
 1948:         if (defined(&domain($udom,'primary'))) {
 1949:             $uhome=&domain($udom,'primary');
 1950:         } else {
 1951:             undef($uhome);
 1952:         }
 1953:     } else {
 1954:         if (!$uhome) {
 1955:             if (defined(&domain($udom,'primary'))) {
 1956:                 $uhome=&domain($udom,'primary');
 1957:             }
 1958:         }
 1959:     }
 1960:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1961:         my $rep;
 1962:         if ($namespace =~ /^enc/) {
 1963:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 1964:         } else {
 1965:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1966:         }
 1967:         my %returnhash;
 1968:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1969:             return %returnhash;
 1970:         }
 1971:         my @pairs=split(/\&/,$rep);
 1972:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1973:             return @pairs;
 1974:         }
 1975:         my $i=0;
 1976:         foreach my $item (@$storearr) {
 1977:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1978:             $i++;
 1979:         }
 1980:         return %returnhash;
 1981:     } else {
 1982:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1983:     }
 1984: }
 1985: 
 1986: # -------------------------------------------- put items in domain db files 
 1987: 
 1988: sub put_dom {
 1989:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1990:     if (!$udom) {
 1991:         $udom=$env{'user.domain'};
 1992:         if (defined(&domain($udom,'primary'))) {
 1993:             $uhome=&domain($udom,'primary');
 1994:         } else {
 1995:             undef($uhome);
 1996:         }
 1997:     } else {
 1998:         if (!$uhome) {
 1999:             if (defined(&domain($udom,'primary'))) {
 2000:                 $uhome=&domain($udom,'primary');
 2001:             }
 2002:         }
 2003:     } 
 2004:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2005:         my $items='';
 2006:         foreach my $item (keys(%$storehash)) {
 2007:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2008:         }
 2009:         $items=~s/\&$//;
 2010:         if ($namespace =~ /^enc/) {
 2011:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2012:         } else {
 2013:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2014:         }
 2015:     } else {
 2016:         &logthis("put_dom failed - no homeserver and/or domain");
 2017:     }
 2018: }
 2019: 
 2020: # --------------------- newput for items in db file owned by domainconfig user
 2021: sub newput_dom {
 2022:     my ($namespace,$storehash,$udom) = @_;
 2023:     my $result;
 2024:     if (!$udom) {
 2025:         $udom=$env{'user.domain'};
 2026:     }
 2027:     if ($udom) {
 2028:         my $uname = &get_domainconfiguser($udom);
 2029:         $result = &newput($namespace,$storehash,$udom,$uname);
 2030:     }
 2031:     return $result;
 2032: }
 2033: 
 2034: # --------------------- delete for items in db file owned by domainconfig user
 2035: sub del_dom {
 2036:     my ($namespace,$storearr,$udom)=@_;
 2037:     if (ref($storearr) eq 'ARRAY') {
 2038:         if (!$udom) {
 2039:             $udom=$env{'user.domain'};
 2040:         }
 2041:         if ($udom) {
 2042:             my $uname = &get_domainconfiguser($udom); 
 2043:             return &del($namespace,$storearr,$udom,$uname);
 2044:         }
 2045:     }
 2046: }
 2047: 
 2048: # ----------------------------------construct domainconfig user for a domain 
 2049: sub get_domainconfiguser {
 2050:     my ($udom) = @_;
 2051:     return $udom.'-domainconfig';
 2052: }
 2053: 
 2054: sub retrieve_inst_usertypes {
 2055:     my ($udom) = @_;
 2056:     my (%returnhash,@order);
 2057:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2058:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2059:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2060:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2061:     } else {
 2062:         if (defined(&domain($udom,'primary'))) {
 2063:             my $uhome=&domain($udom,'primary');
 2064:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2065:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2066:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2067:                 return (\%returnhash,\@order);
 2068:             }
 2069:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2070:             my @pairs=split(/\&/,$hashitems);
 2071:             foreach my $item (@pairs) {
 2072:                 my ($key,$value)=split(/=/,$item,2);
 2073:                 $key = &unescape($key);
 2074:                 next if ($key =~ /^error: 2 /);
 2075:                 $returnhash{$key}=&thaw_unescape($value);
 2076:             }
 2077:             my @esc_order = split(/\&/,$orderitems);
 2078:             foreach my $item (@esc_order) {
 2079:                 push(@order,&unescape($item));
 2080:             }
 2081:         } else {
 2082:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2083:         }
 2084:         return (\%returnhash,\@order);
 2085:     }
 2086: }
 2087: 
 2088: sub is_domainimage {
 2089:     my ($url) = @_;
 2090:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2091:         if (&domain($1) ne '') {
 2092:             return '1';
 2093:         }
 2094:     }
 2095:     return;
 2096: }
 2097: 
 2098: sub inst_directory_query {
 2099:     my ($srch) = @_;
 2100:     my $udom = $srch->{'srchdomain'};
 2101:     my %results;
 2102:     my $homeserver = &domain($udom,'primary');
 2103:     my $outcome;
 2104:     if ($homeserver ne '') {
 2105:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2106:             if ($srch->{'srchby'} eq 'email') {
 2107:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2108:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2109:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2110:                     (($major == 2) && ($minor < 12))) {
 2111:                     return;
 2112:                 }
 2113:             }
 2114:         }
 2115: 	my $queryid=&reply("querysend:instdirsearch:".
 2116: 			   &escape($srch->{'srchby'}).':'.
 2117: 			   &escape($srch->{'srchterm'}).':'.
 2118: 			   &escape($srch->{'srchtype'}),$homeserver);
 2119: 	my $host=&hostname($homeserver);
 2120: 	if ($queryid !~/^\Q$host\E\_/) {
 2121: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2122: 	    return;
 2123: 	}
 2124: 	my $response = &get_query_reply($queryid);
 2125: 	my $maxtries = 5;
 2126: 	my $tries = 1;
 2127: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2128: 	    $response = &get_query_reply($queryid);
 2129: 	    $tries ++;
 2130: 	}
 2131: 
 2132:         if (!&error($response) && $response ne 'refused') {
 2133:             if ($response eq 'unavailable') {
 2134:                 $outcome = $response;
 2135:             } else {
 2136:                 $outcome = 'ok';
 2137:                 my @matches = split(/\n/,$response);
 2138:                 foreach my $match (@matches) {
 2139:                     my ($key,$value) = split(/=/,$match);
 2140:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2141:                 }
 2142:             }
 2143:         }
 2144:     }
 2145:     return ($outcome,%results);
 2146: }
 2147: 
 2148: sub usersearch {
 2149:     my ($srch) = @_;
 2150:     my $dom = $srch->{'srchdomain'};
 2151:     my %results;
 2152:     my %libserv = &all_library();
 2153:     my $query = 'usersearch';
 2154:     foreach my $tryserver (keys(%libserv)) {
 2155:         if (&host_domain($tryserver) eq $dom) {
 2156:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2157:                 if ($srch->{'srchby'} eq 'email') {
 2158:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2159:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2160:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2161:                              (($major == 2) && ($minor < 12)));
 2162:                 }
 2163:             }
 2164:             my $host=&hostname($tryserver);
 2165:             my $queryid=
 2166:                 &reply("querysend:".&escape($query).':'.
 2167:                        &escape($srch->{'srchby'}).':'.
 2168:                        &escape($srch->{'srchtype'}).':'.
 2169:                        &escape($srch->{'srchterm'}),$tryserver);
 2170:             if ($queryid !~/^\Q$host\E\_/) {
 2171:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2172:                 next;
 2173:             }
 2174:             my $reply = &get_query_reply($queryid);
 2175:             my $maxtries = 1;
 2176:             my $tries = 1;
 2177:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2178:                 $reply = &get_query_reply($queryid);
 2179:                 $tries ++;
 2180:             }
 2181:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2182:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2183:             } else {
 2184:                 my @matches;
 2185:                 if ($reply =~ /\n/) {
 2186:                     @matches = split(/\n/,$reply);
 2187:                 } else {
 2188:                     @matches = split(/\&/,$reply);
 2189:                 }
 2190:                 foreach my $match (@matches) {
 2191:                     my ($uname,$udom,%userhash);
 2192:                     foreach my $entry (split(/:/,$match)) {
 2193:                         my ($key,$value) =
 2194:                             map {&unescape($_);} split(/=/,$entry);
 2195:                         $userhash{$key} = $value;
 2196:                         if ($key eq 'username') {
 2197:                             $uname = $value;
 2198:                         } elsif ($key eq 'domain') {
 2199:                             $udom = $value;
 2200:                         }
 2201:                     }
 2202:                     $results{$uname.':'.$udom} = \%userhash;
 2203:                 }
 2204:             }
 2205:         }
 2206:     }
 2207:     return %results;
 2208: }
 2209: 
 2210: sub get_instuser {
 2211:     my ($udom,$uname,$id) = @_;
 2212:     my $homeserver = &domain($udom,'primary');
 2213:     my ($outcome,%results);
 2214:     if ($homeserver ne '') {
 2215:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2216:                            &escape($id).':'.&escape($udom),$homeserver);
 2217:         my $host=&hostname($homeserver);
 2218:         if ($queryid !~/^\Q$host\E\_/) {
 2219:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2220:             return;
 2221:         }
 2222:         my $response = &get_query_reply($queryid);
 2223:         my $maxtries = 5;
 2224:         my $tries = 1;
 2225:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2226:             $response = &get_query_reply($queryid);
 2227:             $tries ++;
 2228:         }
 2229:         if (!&error($response) && $response ne 'refused') {
 2230:             if ($response eq 'unavailable') {
 2231:                 $outcome = $response;
 2232:             } else {
 2233:                 $outcome = 'ok';
 2234:                 my @matches = split(/\n/,$response);
 2235:                 foreach my $match (@matches) {
 2236:                     my ($key,$value) = split(/=/,$match);
 2237:                     $results{&unescape($key)} = &thaw_unescape($value);
 2238:                 }
 2239:             }
 2240:         }
 2241:     }
 2242:     my %userinfo;
 2243:     if (ref($results{$uname}) eq 'HASH') {
 2244:         %userinfo = %{$results{$uname}};
 2245:     } 
 2246:     return ($outcome,%userinfo);
 2247: }
 2248: 
 2249: sub get_multiple_instusers {
 2250:     my ($udom,$users,$caller) = @_;
 2251:     my ($outcome,$results);
 2252:     if (ref($users) eq 'HASH') {
 2253:         my $count = keys(%{$users}); 
 2254:         my $requested = &freeze_escape($users);
 2255:         my $homeserver = &domain($udom,'primary');
 2256:         if ($homeserver ne '') {
 2257:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2258:             my $host=&hostname($homeserver);
 2259:             if ($queryid !~/^\Q$host\E\_/) {
 2260:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2261:                          ' for host: '.$homeserver.'in domain '.$udom);
 2262:                 return ($outcome,$results);
 2263:             }
 2264:             my $response = &get_query_reply($queryid);
 2265:             my $maxtries = 5;
 2266:             if ($count > 100) {
 2267:                 $maxtries = 1+int($count/20);
 2268:             }
 2269:             my $tries = 1;
 2270:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2271:                 $response = &get_query_reply($queryid);
 2272:                 $tries ++;
 2273:             }
 2274:             if ($response eq '') {
 2275:                 $results = {};
 2276:                 foreach my $key (keys(%{$users})) {
 2277:                     my ($uname,$id);
 2278:                     if ($caller eq 'id') {
 2279:                         $id = $key;
 2280:                     } else {
 2281:                         $uname = $key;
 2282:                     }
 2283:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2284:                     $outcome = $resp;
 2285:                     if ($resp eq 'ok') {
 2286:                         %{$results} = (%{$results}, %info);
 2287:                     } else {
 2288:                         last;
 2289:                     }
 2290:                 }
 2291:             } elsif(!&error($response) && ($response ne 'refused')) {
 2292:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2293:                     $outcome = $response;
 2294:                 } else {
 2295:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2296:                     if ($outcome eq 'ok') {
 2297:                         $results = &thaw_unescape($userdata); 
 2298:                     }
 2299:                 }
 2300:             }
 2301:         }
 2302:     }
 2303:     return ($outcome,$results);
 2304: }
 2305: 
 2306: sub inst_rulecheck {
 2307:     my ($udom,$uname,$id,$item,$rules) = @_;
 2308:     my %returnhash;
 2309:     if ($udom ne '') {
 2310:         if (ref($rules) eq 'ARRAY') {
 2311:             @{$rules} = map {&escape($_);} (@{$rules});
 2312:             my $rulestr = join(':',@{$rules});
 2313:             my $homeserver=&domain($udom,'primary');
 2314:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2315:                 my $response;
 2316:                 if ($item eq 'username') {                
 2317:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2318:                                               ':'.&escape($uname).':'.$rulestr,
 2319:                                               $homeserver));
 2320:                 } elsif ($item eq 'id') {
 2321:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2322:                                               ':'.&escape($id).':'.$rulestr,
 2323:                                               $homeserver));
 2324:                 } elsif ($item eq 'selfcreate') {
 2325:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2326:                                                &escape($udom).':'.&escape($uname).
 2327:                                               ':'.$rulestr,$homeserver));
 2328:                 }
 2329:                 if ($response ne 'refused') {
 2330:                     my @pairs=split(/\&/,$response);
 2331:                     foreach my $item (@pairs) {
 2332:                         my ($key,$value)=split(/=/,$item,2);
 2333:                         $key = &unescape($key);
 2334:                         next if ($key =~ /^error: 2 /);
 2335:                         $returnhash{$key}=&thaw_unescape($value);
 2336:                     }
 2337:                 }
 2338:             }
 2339:         }
 2340:     }
 2341:     return %returnhash;
 2342: }
 2343: 
 2344: sub inst_userrules {
 2345:     my ($udom,$check) = @_;
 2346:     my (%ruleshash,@ruleorder);
 2347:     if ($udom ne '') {
 2348:         my $homeserver=&domain($udom,'primary');
 2349:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2350:             my $response;
 2351:             if ($check eq 'id') {
 2352:                 $response=&reply('instidrules:'.&escape($udom),
 2353:                                  $homeserver);
 2354:             } elsif ($check eq 'email') {
 2355:                 $response=&reply('instemailrules:'.&escape($udom),
 2356:                                  $homeserver);
 2357:             } else {
 2358:                 $response=&reply('instuserrules:'.&escape($udom),
 2359:                                  $homeserver);
 2360:             }
 2361:             if (($response ne 'refused') && ($response ne 'error') && 
 2362:                 ($response ne 'unknown_cmd') && 
 2363:                 ($response ne 'no_such_host')) {
 2364:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2365:                 my @pairs=split(/\&/,$hashitems);
 2366:                 foreach my $item (@pairs) {
 2367:                     my ($key,$value)=split(/=/,$item,2);
 2368:                     $key = &unescape($key);
 2369:                     next if ($key =~ /^error: 2 /);
 2370:                     $ruleshash{$key}=&thaw_unescape($value);
 2371:                 }
 2372:                 my @esc_order = split(/\&/,$orderitems);
 2373:                 foreach my $item (@esc_order) {
 2374:                     push(@ruleorder,&unescape($item));
 2375:                 }
 2376:             }
 2377:         }
 2378:     }
 2379:     return (\%ruleshash,\@ruleorder);
 2380: }
 2381: 
 2382: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2383: 
 2384: sub get_domain_defaults {
 2385:     my ($domain,$ignore_cache) = @_;
 2386:     return if (($domain eq '') || ($domain eq 'public'));
 2387:     my $cachetime = 60*60*24;
 2388:     unless ($ignore_cache) {
 2389:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2390:         if (defined($cached)) {
 2391:             if (ref($result) eq 'HASH') {
 2392:                 return %{$result};
 2393:             }
 2394:         }
 2395:     }
 2396:     my %domdefaults;
 2397:     my %domconfig =
 2398:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2399:                                   'requestcourses','inststatus',
 2400:                                   'coursedefaults','usersessions',
 2401:                                   'requestauthor','selfenrollment',
 2402:                                   'coursecategories','ssl','autoenroll',
 2403:                                   'trust','helpsettings'],$domain);
 2404:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2405:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2406:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2407:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2408:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2409:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2410:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2411:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2412:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2413:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2414:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2415:     } else {
 2416:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2417:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2418:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2419:     }
 2420:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2421:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2422:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2423:         } else {
 2424:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2425:         }
 2426:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2427:         foreach my $item (@usertools) {
 2428:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2429:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2430:             }
 2431:         }
 2432:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2433:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2434:         }
 2435:     }
 2436:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2437:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2438:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2439:         }
 2440:     }
 2441:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2442:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2443:     }
 2444:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2445:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2446:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2447:         }
 2448:     }
 2449:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2450:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2451:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2452:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2453:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2454:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2455:         }
 2456:         foreach my $type (@coursetypes) {
 2457:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2458:                 unless ($type eq 'community') {
 2459:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2460:                 }
 2461:             }
 2462:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2463:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2464:             }
 2465:             if ($domdefaults{'postsubmit'} eq 'on') {
 2466:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2467:                     $domdefaults{$type.'postsubtimeout'} = 
 2468:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2469:                 }
 2470:             }
 2471:         }
 2472:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2473:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2474:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2475:                 if (@clonecodes) {
 2476:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2477:                 }
 2478:             }
 2479:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2480:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2481:         }
 2482:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2483:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2484:         } 
 2485:     }
 2486:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2487:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2488:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2489:         }
 2490:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2491:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2492:         }
 2493:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2494:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2495:         }
 2496:     }
 2497:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2498:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2499:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2500:                             'approval','limit');
 2501:             foreach my $type (@coursetypes) {
 2502:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2503:                     my @mgrdc = ();
 2504:                     foreach my $item (@settings) {
 2505:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2506:                             push(@mgrdc,$item);
 2507:                         }
 2508:                     }
 2509:                     if (@mgrdc) {
 2510:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2511:                     }
 2512:                 }
 2513:             }
 2514:         }
 2515:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2516:             foreach my $type (@coursetypes) {
 2517:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2518:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2519:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2520:                     }
 2521:                 }
 2522:             }
 2523:         }
 2524:     }
 2525:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2526:         $domdefaults{'catauth'} = 'std';
 2527:         $domdefaults{'catunauth'} = 'std';
 2528:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2529:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2530:         }
 2531:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2532:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2533:         }
 2534:     }
 2535:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2536:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2537:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2538:         }
 2539:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2540:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2541:         }
 2542:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2543:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2544:         }
 2545:     }
 2546:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2547:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2548:         foreach my $prefix (@prefixes) {
 2549:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2550:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2551:             }
 2552:         }
 2553:     }
 2554:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2555:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2556:     }
 2557:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2558:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2559:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2560:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2561:         }
 2562:     }
 2563:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2564:     return %domdefaults;
 2565: }
 2566: 
 2567: sub course_portal_url {
 2568:     my ($cnum,$cdom) = @_;
 2569:     my $chome = &homeserver($cnum,$cdom);
 2570:     my $hostname = &hostname($chome);
 2571:     my $protocol = $protocol{$chome};
 2572:     $protocol = 'http' if ($protocol ne 'https');
 2573:     my %domdefaults = &get_domain_defaults($cdom);
 2574:     my $firsturl;
 2575:     if ($domdefaults{'portal_def'}) {
 2576:         $firsturl = $domdefaults{'portal_def'};
 2577:     } else {
 2578:         $firsturl = $protocol.'://'.$hostname;
 2579:     }
 2580:     return $firsturl;
 2581: }
 2582: 
 2583: # --------------------------------------------------- Assign a key to a student
 2584: 
 2585: sub assign_access_key {
 2586: #
 2587: # a valid key looks like uname:udom#comments
 2588: # comments are being appended
 2589: #
 2590:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2591:     $kdom=
 2592:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2593:     $knum=
 2594:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2595:     $cdom=
 2596:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2597:     $cnum=
 2598:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2599:     $udom=$env{'user.name'} unless (defined($udom));
 2600:     $uname=$env{'user.domain'} unless (defined($uname));
 2601:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2602:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2603:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2604:                                                   # assigned to this person
 2605:                                                   # - this should not happen,
 2606:                                                   # unless something went wrong
 2607:                                                   # the first time around
 2608: # ready to assign
 2609:         $logentry=$1.'; '.$logentry;
 2610:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2611:                                                  $kdom,$knum) eq 'ok') {
 2612: # key now belongs to user
 2613: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2614:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2615:                 &appenv({'environment.'.$envkey => $ckey});
 2616:                 return 'ok';
 2617:             } else {
 2618:                 return 
 2619:   'error: Count not permanently assign key, will need to be re-entered later.';
 2620: 	    }
 2621:         } else {
 2622:             return 'error: Could not assign key, try again later.';
 2623:         }
 2624:     } elsif (!$existing{$ckey}) {
 2625: # the key does not exist
 2626: 	return 'error: The key does not exist';
 2627:     } else {
 2628: # the key is somebody else's
 2629: 	return 'error: The key is already in use';
 2630:     }
 2631: }
 2632: 
 2633: # ------------------------------------------ put an additional comment on a key
 2634: 
 2635: sub comment_access_key {
 2636: #
 2637: # a valid key looks like uname:udom#comments
 2638: # comments are being appended
 2639: #
 2640:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2641:     $cdom=
 2642:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2643:     $cnum=
 2644:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2645:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2646:     if ($existing{$ckey}) {
 2647:         $existing{$ckey}.='; '.$logentry;
 2648: # ready to assign
 2649:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2650:                                                  $cdom,$cnum) eq 'ok') {
 2651: 	    return 'ok';
 2652:         } else {
 2653: 	    return 'error: Count not store comment.';
 2654:         }
 2655:     } else {
 2656: # the key does not exist
 2657: 	return 'error: The key does not exist';
 2658:     }
 2659: }
 2660: 
 2661: # ------------------------------------------------------ Generate a set of keys
 2662: 
 2663: sub generate_access_keys {
 2664:     my ($number,$cdom,$cnum,$logentry)=@_;
 2665:     $cdom=
 2666:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2667:     $cnum=
 2668:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2669:     unless (&allowed('mky',$cdom)) { return 0; }
 2670:     unless (($cdom) && ($cnum)) { return 0; }
 2671:     if ($number>10000) { return 0; }
 2672:     sleep(2); # make sure don't get same seed twice
 2673:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2674:     my $total=0;
 2675:     for (my $i=1;$i<=$number;$i++) {
 2676:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2677:                   sprintf("%lx",int(100000*rand)).'-'.
 2678:                   sprintf("%lx",int(100000*rand));
 2679:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2680:        $newkey=~s/0/h/g; # and also 0 and O
 2681:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2682:        if ($existing{$newkey}) {
 2683:            $i--;
 2684:        } else {
 2685: 	  if (&put('accesskeys',
 2686:               { $newkey => '# generated '.localtime().
 2687:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2688:                            '; '.$logentry },
 2689: 		   $cdom,$cnum) eq 'ok') {
 2690:               $total++;
 2691: 	  }
 2692:        }
 2693:     }
 2694:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2695:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2696:     return $total;
 2697: }
 2698: 
 2699: # ------------------------------------------------------- Validate an accesskey
 2700: 
 2701: sub validate_access_key {
 2702:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2703:     $cdom=
 2704:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2705:     $cnum=
 2706:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2707:     $udom=$env{'user.domain'} unless (defined($udom));
 2708:     $uname=$env{'user.name'} unless (defined($uname));
 2709:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2710:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2711: }
 2712: 
 2713: # ------------------------------------- Find the section of student in a course
 2714: sub devalidate_getsection_cache {
 2715:     my ($udom,$unam,$courseid)=@_;
 2716:     my $hashid="$udom:$unam:$courseid";
 2717:     &devalidate_cache_new('getsection',$hashid);
 2718: }
 2719: 
 2720: sub courseid_to_courseurl {
 2721:     my ($courseid) = @_;
 2722:     #already url style courseid
 2723:     return $courseid if ($courseid =~ m{^/});
 2724: 
 2725:     if (exists($env{'course.'.$courseid.'.num'})) {
 2726: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2727: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2728: 	return "/$cdom/$cnum";
 2729:     }
 2730: 
 2731:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2732:     if (exists($courseinfo{'num'})) {
 2733: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2734:     }
 2735: 
 2736:     return undef;
 2737: }
 2738: 
 2739: sub getsection {
 2740:     my ($udom,$unam,$courseid)=@_;
 2741:     my $cachetime=1800;
 2742: 
 2743:     my $hashid="$udom:$unam:$courseid";
 2744:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2745:     if (defined($cached)) { return $result; }
 2746: 
 2747:     my %Pending; 
 2748:     my %Expired;
 2749:     #
 2750:     # Each role can either have not started yet (pending), be active, 
 2751:     #    or have expired.
 2752:     #
 2753:     # If there is an active role, we are done.
 2754:     #
 2755:     # If there is more than one role which has not started yet, 
 2756:     #     choose the one which will start sooner
 2757:     # If there is one role which has not started yet, return it.
 2758:     #
 2759:     # If there is more than one expired role, choose the one which ended last.
 2760:     # If there is a role which has expired, return it.
 2761:     #
 2762:     $courseid = &courseid_to_courseurl($courseid);
 2763:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2764:     foreach my $key (keys(%roleshash)) {
 2765:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2766:         my $section=$1;
 2767:         if ($key eq $courseid.'_st') { $section=''; }
 2768:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2769:         my $now=time;
 2770:         if (defined($end) && $end && ($now > $end)) {
 2771:             $Expired{$end}=$section;
 2772:             next;
 2773:         }
 2774:         if (defined($start) && $start && ($now < $start)) {
 2775:             $Pending{$start}=$section;
 2776:             next;
 2777:         }
 2778:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2779:     }
 2780:     #
 2781:     # Presumedly there will be few matching roles from the above
 2782:     # loop and the sorting time will be negligible.
 2783:     if (scalar(keys(%Pending))) {
 2784:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2785:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2786:     } 
 2787:     if (scalar(keys(%Expired))) {
 2788:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2789:         my $time = pop(@sorted);
 2790:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2791:     }
 2792:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2793: }
 2794: 
 2795: sub save_cache {
 2796:     &purge_remembered();
 2797:     #&Apache::loncommon::validate_page();
 2798:     undef(%env);
 2799:     undef($env_loaded);
 2800: }
 2801: 
 2802: my $to_remember=-1;
 2803: my %remembered;
 2804: my %accessed;
 2805: my $kicks=0;
 2806: my $hits=0;
 2807: sub make_key {
 2808:     my ($name,$id) = @_;
 2809:     if (length($id) > 65 
 2810: 	&& length(&escape($id)) > 200) {
 2811: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2812:     }
 2813:     return &escape($name.':'.$id);
 2814: }
 2815: 
 2816: sub devalidate_cache_new {
 2817:     my ($name,$id,$debug) = @_;
 2818:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2819:     my $remembered_id=$name.':'.$id;
 2820:     $id=&make_key($name,$id);
 2821:     $memcache->delete($id);
 2822:     delete($remembered{$remembered_id});
 2823:     delete($accessed{$remembered_id});
 2824: }
 2825: 
 2826: sub is_cached_new {
 2827:     my ($name,$id,$debug) = @_;
 2828:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2829:     if (exists($remembered{$remembered_id})) {
 2830: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2831: 	$accessed{$remembered_id}=[&gettimeofday()];
 2832: 	$hits++;
 2833: 	return ($remembered{$remembered_id},1);
 2834:     }
 2835:     $id=&make_key($name,$id);
 2836:     my $value = $memcache->get($id);
 2837:     if (!(defined($value))) {
 2838: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2839: 	return (undef,undef);
 2840:     }
 2841:     if ($value eq '__undef__') {
 2842: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2843: 	$value=undef;
 2844:     }
 2845:     &make_room($remembered_id,$value,$debug);
 2846:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2847:     return ($value,1);
 2848: }
 2849: 
 2850: sub do_cache_new {
 2851:     my ($name,$id,$value,$time,$debug) = @_;
 2852:     my $remembered_id=$name.':'.$id;
 2853:     $id=&make_key($name,$id);
 2854:     my $setvalue=$value;
 2855:     if (!defined($setvalue)) {
 2856: 	$setvalue='__undef__';
 2857:     }
 2858:     if (!defined($time) ) {
 2859: 	$time=600;
 2860:     }
 2861:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2862:     my $result = $memcache->set($id,$setvalue,$time);
 2863:     if (! $result) {
 2864: 	&logthis("caching of id -> $id  failed");
 2865: 	$memcache->disconnect_all();
 2866:     }
 2867:     # need to make a copy of $value
 2868:     &make_room($remembered_id,$value,$debug);
 2869:     return $value;
 2870: }
 2871: 
 2872: sub make_room {
 2873:     my ($remembered_id,$value,$debug)=@_;
 2874: 
 2875:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2876:                                     : $value;
 2877:     if ($to_remember<0) { return; }
 2878:     $accessed{$remembered_id}=[&gettimeofday()];
 2879:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2880:     my $to_kick;
 2881:     my $max_time=0;
 2882:     foreach my $other (keys(%accessed)) {
 2883: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2884: 	    $to_kick=$other;
 2885: 	    $max_time=&tv_interval($accessed{$other});
 2886: 	}
 2887:     }
 2888:     delete($remembered{$to_kick});
 2889:     delete($accessed{$to_kick});
 2890:     $kicks++;
 2891:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2892:     return;
 2893: }
 2894: 
 2895: sub purge_remembered {
 2896:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2897:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2898:     undef(%remembered);
 2899:     undef(%accessed);
 2900: }
 2901: # ------------------------------------- Read an entry from a user's environment
 2902: 
 2903: sub userenvironment {
 2904:     my ($udom,$unam,@what)=@_;
 2905:     my $items;
 2906:     foreach my $item (@what) {
 2907:         $items.=&escape($item).'&';
 2908:     }
 2909:     $items=~s/\&$//;
 2910:     my %returnhash=();
 2911:     my $uhome = &homeserver($unam,$udom);
 2912:     unless ($uhome eq 'no_host') {
 2913:         my @answer=split(/\&/, 
 2914:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2915:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2916:             return %returnhash;
 2917:         }
 2918:         my $i;
 2919:         for ($i=0;$i<=$#what;$i++) {
 2920: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2921:         }
 2922:     }
 2923:     return %returnhash;
 2924: }
 2925: 
 2926: # ---------------------------------------------------------- Get a studentphoto
 2927: sub studentphoto {
 2928:     my ($udom,$unam,$ext) = @_;
 2929:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2930:     if (defined($env{'request.course.id'})) {
 2931:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2932:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2933:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2934:             } else {
 2935:                 my ($result,$perm_reqd)=
 2936: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2937:                 if ($result eq 'ok') {
 2938:                     if (!($perm_reqd eq 'yes')) {
 2939:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2940:                     }
 2941:                 }
 2942:             }
 2943:         }
 2944:     } else {
 2945:         my ($result,$perm_reqd) = 
 2946: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2947:         if ($result eq 'ok') {
 2948:             if (!($perm_reqd eq 'yes')) {
 2949:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2950:             }
 2951:         }
 2952:     }
 2953:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2954: }
 2955: 
 2956: sub retrievestudentphoto {
 2957:     my ($udom,$unam,$ext,$type) = @_;
 2958:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2959:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2960:     if ($ret eq 'ok') {
 2961:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2962:         if ($type eq 'thumbnail') {
 2963:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2964:         }
 2965:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2966:         return $tokenurl;
 2967:     } else {
 2968:         if ($type eq 'thumbnail') {
 2969:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2970:         } else { 
 2971:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2972:         }
 2973:     }
 2974: }
 2975: 
 2976: # -------------------------------------------------------------------- New chat
 2977: 
 2978: sub chatsend {
 2979:     my ($newentry,$anon,$group)=@_;
 2980:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2981:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2982:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2983:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2984: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2985: 		   &escape($newentry)).':'.$group,$chome);
 2986: }
 2987: 
 2988: # ------------------------------------------ Find current version of a resource
 2989: 
 2990: sub getversion {
 2991:     my $fname=&clutter(shift);
 2992:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2993:     return &currentversion(&filelocation('',$fname));
 2994: }
 2995: 
 2996: sub currentversion {
 2997:     my $fname=shift;
 2998:     my $author=$fname;
 2999:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3000:     my ($udom,$uname)=split(/\//,$author);
 3001:     my $home=&homeserver($uname,$udom);
 3002:     if ($home eq 'no_host') { 
 3003:         return -1; 
 3004:     }
 3005:     my $answer=&reply("currentversion:$fname",$home);
 3006:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3007: 	return -1;
 3008:     }
 3009:     return $answer;
 3010: }
 3011: 
 3012: #
 3013: # Return special version number of resource if set by override, empty otherwise
 3014: #
 3015: sub usedversion {
 3016:     my $fname=shift;
 3017:     unless ($fname) { $fname=$env{'request.uri'}; }
 3018:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3019:     if ($urlversion) { return $urlversion; }
 3020:     return '';
 3021: }
 3022: 
 3023: # ----------------------------- Subscribe to a resource, return URL if possible
 3024: 
 3025: sub subscribe {
 3026:     my $fname=shift;
 3027:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3028:     $fname=~s/[\n\r]//g;
 3029:     my $author=$fname;
 3030:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3031:     my ($udom,$uname)=split(/\//,$author);
 3032:     my $home=homeserver($uname,$udom);
 3033:     if ($home eq 'no_host') {
 3034:         return 'not_found';
 3035:     }
 3036:     my $answer=reply("sub:$fname",$home);
 3037:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3038: 	$answer.=' by '.$home;
 3039:     }
 3040:     return $answer;
 3041: }
 3042:     
 3043: # -------------------------------------------------------------- Replicate file
 3044: 
 3045: sub repcopy {
 3046:     my $filename=shift;
 3047:     $filename=~s/\/+/\//g;
 3048:     my $londocroot = $perlvar{'lonDocRoot'};
 3049:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3050:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3051:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3052: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3053: 	return &repcopy_userfile($filename);
 3054:     }
 3055:     $filename=~s/[\n\r]//g;
 3056:     my $transname="$filename.in.transfer";
 3057: # FIXME: this should flock
 3058:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3059:     my $remoteurl=subscribe($filename);
 3060:     if ($remoteurl =~ /^con_lost by/) {
 3061: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3062:            return 'unavailable';
 3063:     } elsif ($remoteurl eq 'not_found') {
 3064: 	   #&logthis("Subscribe returned not_found: $filename");
 3065: 	   return 'not_found';
 3066:     } elsif ($remoteurl =~ /^rejected by/) {
 3067: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3068:            return 'forbidden';
 3069:     } elsif ($remoteurl eq 'directory') {
 3070:            return 'ok';
 3071:     } else {
 3072:         my $author=$filename;
 3073:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3074:         my ($udom,$uname)=split(/\//,$author);
 3075:         my $home=homeserver($uname,$udom);
 3076:         unless ($home eq $perlvar{'lonHostID'}) {
 3077:            my @parts=split(/\//,$filename);
 3078:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3079:            if ($path ne "$londocroot/res") {
 3080:                &logthis("Malconfiguration for replication: $filename");
 3081: 	       return 'bad_request';
 3082:            }
 3083:            my $count;
 3084:            for ($count=5;$count<$#parts;$count++) {
 3085:                $path.="/$parts[$count]";
 3086:                if ((-e $path)!=1) {
 3087: 		   mkdir($path,0777);
 3088:                }
 3089:            }
 3090:            my $request=new HTTP::Request('GET',"$remoteurl");
 3091:            my $response;
 3092:            if ($remoteurl =~ m{/raw/}) {
 3093:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3094:            } else {
 3095:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3096:            }
 3097:            if ($response->is_error()) {
 3098: 	       unlink($transname);
 3099:                my $message=$response->status_line;
 3100:                &logthis("<font color=\"blue\">WARNING:"
 3101:                        ." LWP get: $message: $filename</font>");
 3102:                return 'unavailable';
 3103:            } else {
 3104: 	       if ($remoteurl!~/\.meta$/) {
 3105:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3106:                   my $mresponse;
 3107:                   if ($remoteurl =~ m{/raw/}) {
 3108:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3109:                   } else {
 3110:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3111:                   }
 3112:                   if ($mresponse->is_error()) {
 3113: 		      unlink($filename.'.meta');
 3114:                       &logthis(
 3115:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3116:                   }
 3117: 	       }
 3118:                rename($transname,$filename);
 3119:                return 'ok';
 3120:            }
 3121:        }
 3122:     }
 3123: }
 3124: 
 3125: # ------------------------------------------------ Get server side include body
 3126: sub ssi_body {
 3127:     my ($filelink,%form)=@_;
 3128:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3129:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3130:     }
 3131:     my $output='';
 3132:     my $response;
 3133:     if ($filelink=~/^https?\:/) {
 3134:        ($output,$response)=&externalssi($filelink);
 3135:     } else {
 3136:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3137:        $filelink .= 'inhibitmenu=yes';
 3138:        ($output,$response)=&ssi($filelink,%form);
 3139:     }
 3140:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3141:     $output=~s/^.*?\<body[^\>]*\>//si;
 3142:     $output=~s/\<\/body\s*\>.*?$//si;
 3143:     if (wantarray) {
 3144:         return ($output, $response);
 3145:     } else {
 3146:         return $output;
 3147:     }
 3148: }
 3149: 
 3150: # --------------------------------------------------------- Server Side Include
 3151: 
 3152: sub absolute_url {
 3153:     my ($host_name) = @_;
 3154:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3155:     if ($host_name eq '') {
 3156: 	$host_name = $ENV{'SERVER_NAME'};
 3157:     }
 3158:     return $protocol.$host_name;
 3159: }
 3160: 
 3161: #
 3162: #   Server side include.
 3163: # Parameters:
 3164: #  fn     Possibly encrypted resource name/id.
 3165: #  form   Hash that describes how the rendering should be done
 3166: #         and other things.
 3167: # Returns:
 3168: #   Scalar context: The content of the response.
 3169: #   Array context:  2 element list of the content and the full response object.
 3170: #     
 3171: sub ssi {
 3172: 
 3173:     my ($fn,%form)=@_;
 3174:     my $request;
 3175: 
 3176:     $form{'no_update_last_known'}=1;
 3177:     &Apache::lonenc::check_encrypt(\$fn);
 3178:     if (%form) {
 3179:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3180:       $request->content(join('&',map { 
 3181:             my $name = escape($_);
 3182:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3183:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3184:             : &escape($form{$_}) );    
 3185:         } keys(%form)));
 3186:     } else {
 3187:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3188:     }
 3189: 
 3190:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3191:     my $lonhost = $perlvar{'lonHostID'};
 3192:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
 3193: 
 3194:     if (wantarray) {
 3195: 	return ($response->content, $response);
 3196:     } else {
 3197: 	return $response->content;
 3198:     }
 3199: }
 3200: 
 3201: sub externalssi {
 3202:     my ($url)=@_;
 3203:     my $request=new HTTP::Request('GET',$url);
 3204:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3205:     if (wantarray) {
 3206:         return ($response->content, $response);
 3207:     } else {
 3208:         return $response->content;
 3209:     }
 3210: }
 3211: 
 3212: 
 3213: # If the local copy of a replicated resource is outdated, trigger a  
 3214: # connection from the homeserver to flush the delayed queue. If no update 
 3215: # happens, remove local copies of outdated resource (and corresponding
 3216: # metadata file).
 3217: 
 3218: sub remove_stale_resfile {
 3219:     my ($url) = @_;
 3220:     my $removed;
 3221:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3222:         my $audom = $1;
 3223:         my $auname = $2;
 3224:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3225:             my $homeserver = &homeserver($auname,$audom);
 3226:             unless (($homeserver eq 'no_host') ||
 3227:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3228:                 my $fname = &filelocation('',$url);
 3229:                 if (-e $fname) {
 3230:                     my $protocol = $protocol{$homeserver};
 3231:                     $protocol = 'http' if ($protocol ne 'https');
 3232:                     my $hostname = &hostname($homeserver);
 3233:                     if ($hostname) {
 3234:                         my $uri = &declutter($url);
 3235:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3236:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3237:                         if ($response->is_success()) {
 3238:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3239:                             my $locmodtime = (stat($fname))[9];
 3240:                             if ($locmodtime < $remmodtime) {
 3241:                                 my $stale;
 3242:                                 my $answer = &reply('pong',$homeserver);
 3243:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3244:                                     sleep(0.2);
 3245:                                     $locmodtime = (stat($fname))[9];
 3246:                                     if ($locmodtime < $remmodtime) {
 3247:                                         my $posstransfer = $fname.'.in.transfer';
 3248:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3249:                                             $removed = 1;
 3250:                                         } else {
 3251:                                             $stale = 1;
 3252:                                         }
 3253:                                     } else {
 3254:                                         $removed = 1;
 3255:                                     }
 3256:                                 } else {
 3257:                                     $stale = 1;
 3258:                                 }
 3259:                                 if ($stale) {
 3260:                                     unlink($fname);
 3261:                                     if ($uri!~/\.meta$/) {
 3262:                                         unlink($fname.'.meta');
 3263:                                     }
 3264:                                     &reply("unsub:$fname",$homeserver);
 3265:                                     $removed = 1;
 3266:                                 }
 3267:                             }
 3268:                         }
 3269:                     }
 3270:                 }
 3271:             }
 3272:         }
 3273:     }
 3274:     return $removed;
 3275: }
 3276: 
 3277: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3278: 
 3279: sub allowuploaded {
 3280:     my ($srcurl,$url)=@_;
 3281:     $url=&clutter(&declutter($url));
 3282:     my $dir=$url;
 3283:     $dir=~s/\/[^\/]+$//;
 3284:     my %httpref=();
 3285:     my $httpurl=&hreflocation('',$url);
 3286:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3287:     &Apache::lonnet::appenv(\%httpref);
 3288: }
 3289: 
 3290: #
 3291: # Determine if the current user should be able to edit a particular resource,
 3292: # when viewing in course context.
 3293: # (a) When viewing resource used to determine if "Edit" item is included in 
 3294: #     Functions.
 3295: # (b) When displaying folder contents in course editor, used to determine if
 3296: #     "Edit" link will be displayed alongside resource.
 3297: #
 3298: #  input: six args -- filename (decluttered), course number, course domain,
 3299: #                   url, symb (if registered) and group (if this is a group
 3300: #                   item -- e.g., bulletin board, group page etc.).
 3301: #  output: array of five scalars -- 
 3302: #          $cfile -- url for file editing if editable on current server
 3303: #          $home -- homeserver of resource (i.e., for author if published,
 3304: #                                           or course if uploaded.).
 3305: #          $switchserver --  1 if server switch will be needed.
 3306: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3307: #          $forceview -- 1 if icon/link should be to go to view mode
 3308: #
 3309: 
 3310: sub can_edit_resource {
 3311:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3312:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3313: #
 3314: # For aboutme pages user can only edit his/her own.
 3315: #
 3316:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3317:         my ($sdom,$sname) = ($1,$2);
 3318:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3319:             $home = $env{'user.home'};
 3320:             $cfile = $resurl;
 3321:             if ($env{'form.forceedit'}) {
 3322:                 $forceview = 1;
 3323:             } else {
 3324:                 $forceedit = 1;
 3325:             }
 3326:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3327:         } else {
 3328:             return;
 3329:         }
 3330:     }
 3331: 
 3332:     if ($env{'request.course.id'}) {
 3333:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3334:         if ($group ne '') {
 3335: # if this is a group homepage or group bulletin board, check group privs
 3336:             my $allowed = 0;
 3337:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3338:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3339:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3340:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3341:                     $allowed = 1;
 3342:                 }
 3343:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3344:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3345:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3346:                     $allowed = 1;
 3347:                 }
 3348:             }
 3349:             if ($allowed) {
 3350:                 $home=&homeserver($cnum,$cdom);
 3351:                 if ($env{'form.forceedit'}) {
 3352:                     $forceview = 1;
 3353:                 } else {
 3354:                     $forceedit = 1;
 3355:                 }
 3356:                 $cfile = $resurl;
 3357:             } else {
 3358:                 return;
 3359:             }
 3360:         } else {
 3361:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3362:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3363:                     return;
 3364:                 }
 3365:             } elsif (!$crsedit) {
 3366: #
 3367: # No edit allowed where CC has switched to student role.
 3368: #
 3369:                 return;
 3370:             }
 3371:         }
 3372:     }
 3373: 
 3374:     if ($file ne '') {
 3375:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3376:             if (&is_course_upload($file,$cnum,$cdom)) {
 3377:                 $uploaded = 1;
 3378:                 $incourse = 1;
 3379:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3380:                     $cfile = &hreflocation('',$file);
 3381:                     if ($env{'form.forceedit'}) {
 3382:                         $forceview = 1;
 3383:                     } else {
 3384:                         $forceedit = 1;
 3385:                     }
 3386:                 }
 3387:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3388:                 $incourse = 1;
 3389:                 if ($env{'form.forceedit'}) {
 3390:                     $forceview = 1;
 3391:                 } else {
 3392:                     $forceedit = 1;
 3393:                 }
 3394:                 $cfile = $resurl;
 3395:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3396:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3397:                     $incourse = 1;
 3398:                     if ($env{'form.forceedit'}) {
 3399:                         $forceview = 1;
 3400:                     } else {
 3401:                         $forceedit = 1;
 3402:                     }
 3403:                     $cfile = $resurl;
 3404:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3405:                     $incourse = 1;
 3406:                     $cfile = $resurl.'/smpedit';
 3407:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3408:                     $incourse = 1;
 3409:                     if ($env{'form.forceedit'}) {
 3410:                         $forceview = 1;
 3411:                     } else {
 3412:                         $forceedit = 1;
 3413:                     }
 3414:                     $cfile = $resurl;
 3415:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 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/viewclasslist$}) {
 3424:                     $incourse = 1;
 3425:                     if ($env{'form.forceedit'}) {
 3426:                         $forceview = 1;
 3427:                     } else {
 3428:                         $forceedit = 1;
 3429:                     }
 3430:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3431:                 }
 3432:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3433:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3434:                 if (&is_on_map($template)) { 
 3435:                     $incourse = 1;
 3436:                     $forceview = 1;
 3437:                     $cfile = $template;
 3438:                 }
 3439:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3440:                     $incourse = 1;
 3441:                     if ($env{'form.forceedit'}) {
 3442:                         $forceview = 1;
 3443:                     } else {
 3444:                         $forceedit = 1;
 3445:                     }
 3446:                     $cfile = $resurl;
 3447:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($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 eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3456:                 $incourse = 1;
 3457:                 $forceview = 1;
 3458:                 if ($symb) {
 3459:                     my ($map,$id,$res)=&decode_symb($symb);
 3460:                     $env{'request.symb'} = $symb;
 3461:                     $cfile = &clutter($res);
 3462:                 } else {
 3463:                     $cfile = $env{'form.suppurl'};
 3464:                     my $escfile = &unescape($cfile);
 3465:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3466:                         $cfile = '/adm/wrapper'.$escfile;
 3467:                     } else {
 3468:                         $escfile =~ s{^http://}{};
 3469:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3470:                     }
 3471:                 }
 3472:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3473:                 if ($env{'form.forceedit'}) {
 3474:                     $forceview = 1;
 3475:                 } else {
 3476:                     $forceedit = 1;
 3477:                 }
 3478:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3479:             }
 3480:         }
 3481:         if ($uploaded || $incourse) {
 3482:             $home=&homeserver($cnum,$cdom);
 3483:         } elsif ($file !~ m{/$}) {
 3484:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3485:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3486:             # Check that the user has permission to edit this resource
 3487:             my $setpriv = 1;
 3488:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3489:             if (defined($cfudom)) {
 3490:                 $home=&homeserver($cfuname,$cfudom);
 3491:                 $cfile=$file;
 3492:             }
 3493:         }
 3494:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3495:             (($home ne '') && ($home ne 'no_host'))) {
 3496:             my @ids=&current_machine_ids();
 3497:             unless (grep(/^\Q$home\E$/,@ids)) {
 3498:                 $switchserver=1;
 3499:             }
 3500:         }
 3501:     }
 3502:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3503: }
 3504: 
 3505: sub is_course_upload {
 3506:     my ($file,$cnum,$cdom) = @_;
 3507:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3508:     $uploadpath =~ s{^\/}{};
 3509:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3510:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3511:         return 1;
 3512:     }
 3513:     return;
 3514: }
 3515: 
 3516: sub in_course {
 3517:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3518:     if ($hideprivileged) {
 3519:         my $skipuser;
 3520:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3521:         my @possdoms = ($cdom);  
 3522:         if ($coursehash{'checkforpriv'}) { 
 3523:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3524:         }
 3525:         if (&privileged($uname,$udom,\@possdoms)) {
 3526:             $skipuser = 1;
 3527:             if ($coursehash{'nothideprivileged'}) {
 3528:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3529:                     my $user;
 3530:                     if ($item =~ /:/) {
 3531:                         $user = $item;
 3532:                     } else {
 3533:                         $user = join(':',split(/[\@]/,$item));
 3534:                     }
 3535:                     if ($user eq $uname.':'.$udom) {
 3536:                         undef($skipuser);
 3537:                         last;
 3538:                     }
 3539:                 }
 3540:             }
 3541:             if ($skipuser) {
 3542:                 return 0;
 3543:             }
 3544:         }
 3545:     }
 3546:     $type ||= 'any';
 3547:     if (!defined($cdom) || !defined($cnum)) {
 3548:         my $cid  = $env{'request.course.id'};
 3549:         $cdom = $env{'course.'.$cid.'.domain'};
 3550:         $cnum = $env{'course.'.$cid.'.num'};
 3551:     }
 3552:     my $typesref;
 3553:     if (($type eq 'any') || ($type eq 'all')) {
 3554:         $typesref = ['active','previous','future'];
 3555:     } elsif ($type eq 'previous' || $type eq 'future') {
 3556:         $typesref = [$type];
 3557:     }
 3558:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3559:                               $typesref,undef,[$cdom]);
 3560:     my ($tmp) = keys(%roles);
 3561:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3562:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3563:     if (@course_roles > 0) {
 3564:         return 1;
 3565:     }
 3566:     return 0;
 3567: }
 3568: 
 3569: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3570: # input: action, courseID, current domain, intended
 3571: #        path to file, source of file, instruction to parse file for objects,
 3572: #        ref to hash for embedded objects,
 3573: #        ref to hash for codebase of java objects.
 3574: #        reference to scalar to accommodate mime type determined
 3575: #          from File::MMagic if $parser = parse.
 3576: #
 3577: # output: url to file (if action was uploaddoc), 
 3578: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3579: #
 3580: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3581: # course.
 3582: #
 3583: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3584: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3585: #          course's home server.
 3586: #
 3587: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3588: #          be copied from $source (current location) to 
 3589: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3590: #         and will then be copied to
 3591: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3592: #         course's home server.
 3593: #
 3594: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3595: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3596: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3597: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3598: #         in course's home server.
 3599: #
 3600: 
 3601: sub process_coursefile {
 3602:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3603:         $mimetype)=@_;
 3604:     my $fetchresult;
 3605:     my $home=&homeserver($docuname,$docudom);
 3606:     if ($action eq 'propagate') {
 3607:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3608: 			     $home);
 3609:     } else {
 3610:         my $fpath = '';
 3611:         my $fname = $file;
 3612:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3613:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3614:         my $filepath = &build_filepath($fpath);
 3615:         if ($action eq 'copy') {
 3616:             if ($source eq '') {
 3617:                 $fetchresult = 'no source file';
 3618:                 return $fetchresult;
 3619:             } else {
 3620:                 my $destination = $filepath.'/'.$fname;
 3621:                 rename($source,$destination);
 3622:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3623:                                  $home);
 3624:             }
 3625:         } elsif ($action eq 'uploaddoc') {
 3626:             open(my $fh,'>',$filepath.'/'.$fname);
 3627:             print $fh $env{'form.'.$source};
 3628:             close($fh);
 3629:             if ($parser eq 'parse') {
 3630:                 my $mm = new File::MMagic;
 3631:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3632:                 if ($type eq 'text/html') {
 3633:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3634:                     unless ($parse_result eq 'ok') {
 3635:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3636:                     }
 3637:                 }
 3638:                 if (ref($mimetype)) {
 3639:                     $$mimetype = $type;
 3640:                 } 
 3641:             }
 3642:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3643:                                  $home);
 3644:             if ($fetchresult eq 'ok') {
 3645:                 return '/uploaded/'.$fpath.'/'.$fname;
 3646:             } else {
 3647:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3648:                         ' to host '.$home.': '.$fetchresult);
 3649:                 return '/adm/notfound.html';
 3650:             }
 3651:         }
 3652:     }
 3653:     unless ( $fetchresult eq 'ok') {
 3654:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3655:              ' to host '.$home.': '.$fetchresult);
 3656:     }
 3657:     return $fetchresult;
 3658: }
 3659: 
 3660: sub build_filepath {
 3661:     my ($fpath) = @_;
 3662:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3663:     unless ($fpath eq '') {
 3664:         my @parts=split('/',$fpath);
 3665:         foreach my $part (@parts) {
 3666:             $filepath.= '/'.$part;
 3667:             if ((-e $filepath)!=1) {
 3668:                 mkdir($filepath,0777);
 3669:             }
 3670:         }
 3671:     }
 3672:     return $filepath;
 3673: }
 3674: 
 3675: sub store_edited_file {
 3676:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3677:     my $file = $primary_url;
 3678:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3679:     my $fpath = '';
 3680:     my $fname = $file;
 3681:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3682:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3683:     my $filepath = &build_filepath($fpath);
 3684:     open(my $fh,'>',$filepath.'/'.$fname);
 3685:     print $fh $content;
 3686:     close($fh);
 3687:     my $home=&homeserver($docuname,$docudom);
 3688:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3689: 			  $home);
 3690:     if ($$fetchresult eq 'ok') {
 3691:         return '/uploaded/'.$fpath.'/'.$fname;
 3692:     } else {
 3693:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3694: 		 ' to host '.$home.': '.$$fetchresult);
 3695:         return '/adm/notfound.html';
 3696:     }
 3697: }
 3698: 
 3699: sub clean_filename {
 3700:     my ($fname,$args)=@_;
 3701: # Replace Windows backslashes by forward slashes
 3702:     $fname=~s/\\/\//g;
 3703:     if (!$args->{'keep_path'}) {
 3704:         # Get rid of everything but the actual filename
 3705: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3706:     }
 3707: # Replace spaces by underscores
 3708:     $fname=~s/\s+/\_/g;
 3709: # Replace all other weird characters by nothing
 3710:     $fname=~s{[^/\w\.\-]}{}g;
 3711: # Replace all .\d. sequences with _\d. so they no longer look like version
 3712: # numbers
 3713:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3714:     return $fname;
 3715: }
 3716: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3717: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3718: # image with the same aspect ratio as the original, but with dimensions which do 
 3719: # not exceed $resizewidth and $resizeheight.
 3720:  
 3721: sub resizeImage {
 3722:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3723:     my $ima = Image::Magick->new;
 3724:     my $resized;
 3725:     if (-e $img_path) {
 3726:         $ima->Read($img_path);
 3727:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3728:             my $width = $ima->Get('width');
 3729:             my $height = $ima->Get('height');
 3730:             if ($width > $resizewidth) {
 3731: 	        my $factor = $width/$resizewidth;
 3732:                 my $newheight = $height/$factor;
 3733:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3734:                 $resized = 1;
 3735:             }
 3736:         }
 3737:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3738:             my $width = $ima->Get('width');
 3739:             my $height = $ima->Get('height');
 3740:             if ($height > $resizeheight) {
 3741:                 my $factor = $height/$resizeheight;
 3742:                 my $newwidth = $width/$factor;
 3743:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3744:                 $resized = 1;
 3745:             }
 3746:         }
 3747:         if ($resized) {
 3748:             $ima->Write($img_path);
 3749:         }
 3750:     }
 3751:     return;
 3752: }
 3753: 
 3754: # --------------- Take an uploaded file and put it into the userfiles directory
 3755: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3756: #                    the desired filename is in $env{"form.$formname.filename"}
 3757: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3758: #                                    canceloverwrite, or ''. 
 3759: #                   if 'coursedoc': upload to the current course
 3760: #                   if 'existingfile': write file to tmp/overwrites directory 
 3761: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3762: #                   $context is passed as argument to &finishuserfileupload
 3763: #        $subdir - directory in userfile to store the file into
 3764: #        $parser - instruction to parse file for objects ($parser = parse)    
 3765: #        $allfiles - reference to hash for embedded objects
 3766: #        $codebase - reference to hash for codebase of java objects
 3767: #        $desuname - username for permanent storage of uploaded file
 3768: #        $dsetudom - domain for permanaent storage of uploaded file
 3769: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3770: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3771: #        $resizewidth - width (pixels) to which to resize uploaded image
 3772: #        $resizeheight - height (pixels) to which to resize uploaded image
 3773: #        $mimetype - reference to scalar to accommodate mime type determined
 3774: #                    from File::MMagic.
 3775: # 
 3776: # output: url of file in userspace, or error: <message> 
 3777: #             or /adm/notfound.html if failure to upload occurse
 3778: 
 3779: sub userfileupload {
 3780:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3781:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3782:     if (!defined($subdir)) { $subdir='unknown'; }
 3783:     my $fname=$env{'form.'.$formname.'.filename'};
 3784:     $fname=&clean_filename($fname);
 3785:     # See if there is anything left
 3786:     unless ($fname) { return 'error: no uploaded file'; }
 3787:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3788:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3789:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3790:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3791:         my $now = time;
 3792:         my $filepath;
 3793:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3794:              $filepath = 'tmp/helprequests/'.$now;
 3795:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3796:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3797:                          '_'.$env{'user.domain'}.'/pending';
 3798:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3799:             my ($docuname,$docudom);
 3800:             if ($destudom =~ /^$match_domain$/) {
 3801:                 $docudom = $destudom;
 3802:             } else {
 3803:                 $docudom = $env{'user.domain'};
 3804:             }
 3805:             if ($destuname =~ /^$match_username$/) {
 3806:                 $docuname = $destuname;
 3807:             } else {
 3808:                 $docuname = $env{'user.name'};
 3809:             }
 3810:             if (exists($env{'form.group'})) {
 3811:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3812:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3813:             }
 3814:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3815:             if ($context eq 'canceloverwrite') {
 3816:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3817:                 if (-e  $tempfile) {
 3818:                     my @info = stat($tempfile);
 3819:                     if ($info[9] eq $env{'form.timestamp'}) {
 3820:                         unlink($tempfile);
 3821:                     }
 3822:                 }
 3823:                 return;
 3824:             }
 3825:         }
 3826:         # Create the directory if not present
 3827:         my @parts=split(/\//,$filepath);
 3828:         my $fullpath = $perlvar{'lonDaemons'};
 3829:         for (my $i=0;$i<@parts;$i++) {
 3830:             $fullpath .= '/'.$parts[$i];
 3831:             if ((-e $fullpath)!=1) {
 3832:                 mkdir($fullpath,0777);
 3833:             }
 3834:         }
 3835:         open(my $fh,'>',$fullpath.'/'.$fname);
 3836:         print $fh $env{'form.'.$formname};
 3837:         close($fh);
 3838:         if ($context eq 'existingfile') {
 3839:             my @info = stat($fullpath.'/'.$fname);
 3840:             return ($fullpath.'/'.$fname,$info[9]);
 3841:         } else {
 3842:             return $fullpath.'/'.$fname;
 3843:         }
 3844:     }
 3845:     if ($subdir eq 'scantron') {
 3846:         $fname = 'scantron_orig_'.$fname;
 3847:     } else {
 3848:         $fname="$subdir/$fname";
 3849:     }
 3850:     if ($context eq 'coursedoc') {
 3851: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3852: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3853:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3854:             return &finishuserfileupload($docuname,$docudom,
 3855: 					 $formname,$fname,$parser,$allfiles,
 3856: 					 $codebase,$thumbwidth,$thumbheight,
 3857:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3858:         } else {
 3859:             if ($env{'form.folder'}) {
 3860:                 $fname=$env{'form.folder'}.'/'.$fname;
 3861:             }
 3862:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3863: 				       $fname,$formname,$parser,
 3864: 				       $allfiles,$codebase,$mimetype);
 3865:         }
 3866:     } elsif (defined($destuname)) {
 3867:         my $docuname=$destuname;
 3868:         my $docudom=$destudom;
 3869: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3870: 				     $parser,$allfiles,$codebase,
 3871:                                      $thumbwidth,$thumbheight,
 3872:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3873:     } else {
 3874:         my $docuname=$env{'user.name'};
 3875:         my $docudom=$env{'user.domain'};
 3876:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3877:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3878:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3879:         }
 3880: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3881: 				     $parser,$allfiles,$codebase,
 3882:                                      $thumbwidth,$thumbheight,
 3883:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3884:     }
 3885: }
 3886: 
 3887: sub finishuserfileupload {
 3888:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3889:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3890:     my $path=$docudom.'/'.$docuname.'/';
 3891:     my $filepath=$perlvar{'lonDocRoot'};
 3892:   
 3893:     my ($fnamepath,$file,$fetchthumb);
 3894:     $file=$fname;
 3895:     if ($fname=~m|/|) {
 3896:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3897: 	$path.=$fnamepath.'/';
 3898:     }
 3899:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3900:     my $count;
 3901:     for ($count=4;$count<=$#parts;$count++) {
 3902:         $filepath.="/$parts[$count]";
 3903:         if ((-e $filepath)!=1) {
 3904: 	    mkdir($filepath,0777);
 3905:         }
 3906:     }
 3907: 
 3908: # Save the file
 3909:     {
 3910: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 3911: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3912: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3913: 	    return '/adm/notfound.html';
 3914: 	}
 3915:         if ($context eq 'overwrite') {
 3916:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3917:             my $target = $filepath.'/'.$file;
 3918:             if (-e $source) {
 3919:                 my @info = stat($source);
 3920:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3921:                     unless (&File::Copy::move($source,$target)) {
 3922:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3923:                         return "Moving from $source failed";
 3924:                     }
 3925:                 } else {
 3926:                     return "Temporary file: $source had unexpected date/time for last modification";
 3927:                 }
 3928:             } else {
 3929:                 return "Temporary file: $source missing";
 3930:             }
 3931:         } elsif (!print FH ($env{'form.'.$formname})) {
 3932: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3933: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3934: 	    return '/adm/notfound.html';
 3935: 	}
 3936: 	close(FH);
 3937:         if ($resizewidth && $resizeheight) {
 3938:             my $mm = new File::MMagic;
 3939:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3940:             if ($mime_type =~ m{^image/}) {
 3941: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3942:             }  
 3943: 	}
 3944:     }
 3945:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3946:         if (ref($mimetype)) {
 3947:             if ($$mimetype eq '') {
 3948:                 my $mm = new File::MMagic;
 3949:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3950:                 $$mimetype = $type;
 3951:             }
 3952:         }
 3953:     }
 3954:     if ($parser eq 'parse') {
 3955:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3956:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3957:                                                        $allfiles,$codebase);
 3958:             unless ($parse_result eq 'ok') {
 3959:                 &logthis('Failed to parse '.$filepath.$file.
 3960: 	   	         ' for embedded media: '.$parse_result); 
 3961:             }
 3962:         }
 3963:     }
 3964:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3965:         my $input = $filepath.'/'.$file;
 3966:         my $output = $filepath.'/'.'tn-'.$file;
 3967:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3968:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 3969:         system({$args[0]} @args);
 3970:         if (-e $filepath.'/'.'tn-'.$file) {
 3971:             $fetchthumb  = 1; 
 3972:         }
 3973:     }
 3974:  
 3975: # Notify homeserver to grep it
 3976: #
 3977:     my $docuhome=&homeserver($docuname,$docudom);	
 3978:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3979:     if ($fetchresult eq 'ok') {
 3980:         if ($fetchthumb) {
 3981:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3982:             if ($thumbresult ne 'ok') {
 3983:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3984:                          $docuhome.': '.$thumbresult);
 3985:             }
 3986:         }
 3987: #
 3988: # Return the URL to it
 3989:         return '/uploaded/'.$path.$file;
 3990:     } else {
 3991:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3992: 		 ': '.$fetchresult);
 3993:         return '/adm/notfound.html';
 3994:     }
 3995: }
 3996: 
 3997: sub extract_embedded_items {
 3998:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3999:     my @state = ();
 4000:     my (%lastids,%related,%shockwave,%flashvars);
 4001:     my %javafiles = (
 4002:                       codebase => '',
 4003:                       code => '',
 4004:                       archive => ''
 4005:                     );
 4006:     my %mediafiles = (
 4007:                       src => '',
 4008:                       movie => '',
 4009:                      );
 4010:     my $p;
 4011:     if ($content) {
 4012:         $p = HTML::LCParser->new($content);
 4013:     } else {
 4014:         $p = HTML::LCParser->new($fullpath);
 4015:     }
 4016:     while (my $t=$p->get_token()) {
 4017: 	if ($t->[0] eq 'S') {
 4018: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4019: 	    push(@state, $tagname);
 4020:             if (lc($tagname) eq 'allow') {
 4021:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4022:             }
 4023: 	    if (lc($tagname) eq 'img') {
 4024: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4025: 	    }
 4026: 	    if (lc($tagname) eq 'a') {
 4027:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4028:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4029:                 }
 4030: 	    }
 4031:             if (lc($tagname) eq 'script') {
 4032:                 my $src;
 4033:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4034:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4035:                 } else {
 4036:                     if ($attr->{'src'} ne '') {
 4037:                         $src = $attr->{'src'};
 4038:                         &add_filetype($allfiles,$src,'src');
 4039:                     }
 4040:                 }
 4041:                 my $text = $p->get_trimmed_text();
 4042:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4043:                     my @swfargs = split(/,/,$1);
 4044:                     foreach my $item (@swfargs) {
 4045:                         $item =~ s/["']//g;
 4046:                         $item =~ s/^\s+//;
 4047:                         $item =~ s/\s+$//;
 4048:                     }
 4049:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4050:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4051:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4052:                         } else {
 4053:                             $related{$swfargs[0]} = [$swfargs[2]];
 4054:                         }
 4055:                     }
 4056:                 }
 4057:             }
 4058:             if (lc($tagname) eq 'link') {
 4059:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4060:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4061:                 }
 4062:             }
 4063: 	    if (lc($tagname) eq 'object' ||
 4064: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4065: 		foreach my $item (keys(%javafiles)) {
 4066: 		    $javafiles{$item} = '';
 4067: 		}
 4068:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4069:                     $lastids{lc($tagname)} = $attr->{'id'};
 4070:                 }
 4071: 	    }
 4072: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4073: 		my $name = lc($attr->{'name'});
 4074: 		foreach my $item (keys(%javafiles)) {
 4075: 		    if ($name eq $item) {
 4076: 			$javafiles{$item} = $attr->{'value'};
 4077: 			last;
 4078: 		    }
 4079: 		}
 4080:                 my $pathfrom;
 4081: 		foreach my $item (keys(%mediafiles)) {
 4082: 		    if ($name eq $item) {
 4083:                         $pathfrom = $attr->{'value'};
 4084:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4085: 			&add_filetype($allfiles,$pathfrom,$name);
 4086: 			last;
 4087: 		    }
 4088: 		}
 4089:                 if ($name eq 'flashvars') {
 4090:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4091:                 }
 4092:                 if ($pathfrom ne '') {
 4093:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4094:                                          $pathfrom);
 4095:                 }
 4096: 	    }
 4097: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4098: 		foreach my $item (keys(%javafiles)) {
 4099: 		    if ($attr->{$item}) {
 4100: 			$javafiles{$item} = $attr->{$item};
 4101: 			last;
 4102: 		    }
 4103: 		}
 4104: 		foreach my $item (keys(%mediafiles)) {
 4105: 		    if ($attr->{$item}) {
 4106: 			&add_filetype($allfiles,$attr->{$item},$item);
 4107: 			last;
 4108: 		    }
 4109: 		}
 4110:                 if (lc($tagname) eq 'embed') {
 4111:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4112:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4113:                                              $attr->{'src'});
 4114:                     }
 4115:                 }
 4116: 	    }
 4117:             if (lc($tagname) eq 'iframe') {
 4118:                 my $src = $attr->{'src'} ;
 4119:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4120:                     &add_filetype($allfiles,$src,'src');
 4121:                 } elsif ($src =~ m{^/}) {
 4122:                     if ($env{'request.course.id'}) {
 4123:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4124:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4125:                         my $url = &hreflocation('',$fullpath);
 4126:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4127:                             my $relpath = $1;
 4128:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4129:                                 &add_filetype($allfiles,$1,'src');
 4130:                             }
 4131:                         }
 4132:                     }
 4133:                 }
 4134:             }
 4135:             if ($t->[4] =~ m{/>$}) {
 4136:                 pop(@state);
 4137:             }
 4138: 	} elsif ($t->[0] eq 'E') {
 4139: 	    my ($tagname) = ($t->[1]);
 4140: 	    if ($javafiles{'codebase'} ne '') {
 4141: 		$javafiles{'codebase'} .= '/';
 4142: 	    }  
 4143: 	    if (lc($tagname) eq 'applet' ||
 4144: 		lc($tagname) eq 'object' ||
 4145: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4146: 		) {
 4147: 		foreach my $item (keys(%javafiles)) {
 4148: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4149: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4150: 			&add_filetype($allfiles,$file,$item);
 4151: 		    }
 4152: 		}
 4153: 	    } 
 4154: 	    pop @state;
 4155: 	}
 4156:     }
 4157:     foreach my $id (sort(keys(%flashvars))) {
 4158:         if ($shockwave{$id} ne '') {
 4159:             my @pairs = split(/\&/,$flashvars{$id});
 4160:             foreach my $pair (@pairs) {
 4161:                 my ($key,$value) = split(/\=/,$pair);
 4162:                 if ($key eq 'thumb') {
 4163:                     &add_filetype($allfiles,$value,$key);
 4164:                 } elsif ($key eq 'content') {
 4165:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4166:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4167:                     if ($ext ne '') {
 4168:                         &add_filetype($allfiles,$path.$value,$ext);
 4169:                     }
 4170:                 }
 4171:             }
 4172:         }
 4173:     }
 4174:     return 'ok';
 4175: }
 4176: 
 4177: sub add_filetype {
 4178:     my ($allfiles,$file,$type)=@_;
 4179:     if (exists($allfiles->{$file})) {
 4180: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4181: 	    push(@{$allfiles->{$file}}, &escape($type));
 4182: 	}
 4183:     } else {
 4184: 	@{$allfiles->{$file}} = (&escape($type));
 4185:     }
 4186: }
 4187: 
 4188: sub embedded_dependency {
 4189:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4190:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4191:         if (($identifier ne '') &&
 4192:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4193:             ($pathfrom ne '')) {
 4194:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4195:             foreach my $dep (@{$related->{$identifier}}) {
 4196:                 &add_filetype($allfiles,$path.$dep,'object');
 4197:             }
 4198:         }
 4199:     }
 4200:     return;
 4201: }
 4202: 
 4203: sub removeuploadedurl {
 4204:     my ($url)=@_;	
 4205:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4206:     return &removeuserfile($uname,$udom,$fname);
 4207: }
 4208: 
 4209: sub removeuserfile {
 4210:     my ($docuname,$docudom,$fname)=@_;
 4211:     my $home=&homeserver($docuname,$docudom);    
 4212:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4213:     if ($result eq 'ok') {	
 4214:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4215:             my $metafile = $fname.'.meta';
 4216:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4217: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4218:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4219:             my $sqlresult = 
 4220:                 &update_portfolio_table($docuname,$docudom,$file,
 4221:                                         'portfolio_metadata',$group,
 4222:                                         'delete');
 4223:         }
 4224:     }
 4225:     return $result;
 4226: }
 4227: 
 4228: sub mkdiruserfile {
 4229:     my ($docuname,$docudom,$dir)=@_;
 4230:     my $home=&homeserver($docuname,$docudom);
 4231:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4232: }
 4233: 
 4234: sub renameuserfile {
 4235:     my ($docuname,$docudom,$old,$new)=@_;
 4236:     my $home=&homeserver($docuname,$docudom);
 4237:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4238:                         &escape("$old").':'.&escape("$new"),$home);
 4239:     if ($result eq 'ok') {
 4240:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4241:             my $oldmeta = $old.'.meta';
 4242:             my $newmeta = $new.'.meta';
 4243:             my $metaresult = 
 4244:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4245: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4246:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4247:             my $sqlresult = 
 4248:                 &update_portfolio_table($docuname,$docudom,$file,
 4249:                                         'portfolio_metadata',$group,
 4250:                                         'delete');
 4251:         }
 4252:     }
 4253:     return $result;
 4254: }
 4255: 
 4256: # ------------------------------------------------------------------------- Log
 4257: 
 4258: sub log {
 4259:     my ($dom,$nam,$hom,$what)=@_;
 4260:     return critical("log:$dom:$nam:$what",$hom);
 4261: }
 4262: 
 4263: # ------------------------------------------------------------------ Course Log
 4264: #
 4265: # This routine flushes several buffers of non-mission-critical nature
 4266: #
 4267: 
 4268: sub flushcourselogs {
 4269:     &logthis('Flushing log buffers');
 4270: #
 4271: # course logs
 4272: # This is a log of all transactions in a course, which can be used
 4273: # for data mining purposes
 4274: #
 4275: # It also collects the courseid database, which lists last transaction
 4276: # times and course titles for all courseids
 4277: #
 4278:     my %courseidbuffer=();
 4279:     foreach my $crsid (keys(%courselogs)) {
 4280:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4281: 		          &escape($courselogs{$crsid}),
 4282: 		          $coursehombuf{$crsid}) eq 'ok') {
 4283: 	    delete $courselogs{$crsid};
 4284:         } else {
 4285:             &logthis('Failed to flush log buffer for '.$crsid);
 4286:             if (length($courselogs{$crsid})>40000) {
 4287:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4288:                         " exceeded maximum size, deleting.</font>");
 4289:                delete $courselogs{$crsid};
 4290:             }
 4291:         }
 4292:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4293:             'description' => $coursedescrbuf{$crsid},
 4294:             'inst_code'    => $courseinstcodebuf{$crsid},
 4295:             'type'        => $coursetypebuf{$crsid},
 4296:             'owner'       => $courseownerbuf{$crsid},
 4297:         };
 4298:     }
 4299: #
 4300: # Write course id database (reverse lookup) to homeserver of courses 
 4301: # Is used in pickcourse
 4302: #
 4303:     foreach my $crs_home (keys(%courseidbuffer)) {
 4304:         my $response = &courseidput(&host_domain($crs_home),
 4305:                                     $courseidbuffer{$crs_home},
 4306:                                     $crs_home,'timeonly');
 4307:     }
 4308: #
 4309: # File accesses
 4310: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4311: #
 4312:     foreach my $entry (keys(%accesshash)) {
 4313:         if ($entry =~ /___count$/) {
 4314:             my ($dom,$name);
 4315:             ($dom,$name,undef)=
 4316: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4317:             if (! defined($dom) || $dom eq '' || 
 4318:                 ! defined($name) || $name eq '') {
 4319:                 my $cid = $env{'request.course.id'};
 4320:                 $dom  = $env{'request.'.$cid.'.domain'};
 4321:                 $name = $env{'request.'.$cid.'.num'};
 4322:             }
 4323:             my $value = $accesshash{$entry};
 4324:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4325:             my %temphash=($url => $value);
 4326:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4327:             if ($result eq 'ok') {
 4328:                 delete $accesshash{$entry};
 4329:             }
 4330:         } else {
 4331:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4332:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4333:             my %temphash=($entry => $accesshash{$entry});
 4334:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4335:                 delete $accesshash{$entry};
 4336:             }
 4337:         }
 4338:     }
 4339: #
 4340: # Roles
 4341: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4342: #
 4343:     foreach my $entry (keys(%userrolehash)) {
 4344:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4345: 	    split(/\:/,$entry);
 4346:         if (&Apache::lonnet::put('nohist_userroles',
 4347:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4348:                 $rudom,$runame) eq 'ok') {
 4349: 	    delete $userrolehash{$entry};
 4350:         }
 4351:     }
 4352: #
 4353: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4354: #
 4355:     my %domrolebuffer = ();
 4356:     foreach my $entry (keys(%domainrolehash)) {
 4357:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4358:         if ($domrolebuffer{$rudom}) {
 4359:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4360:                       '='.&escape($domainrolehash{$entry});
 4361:         } else {
 4362:             $domrolebuffer{$rudom}.=&escape($entry).
 4363:                       '='.&escape($domainrolehash{$entry});
 4364:         }
 4365:         delete $domainrolehash{$entry};
 4366:     }
 4367:     foreach my $dom (keys(%domrolebuffer)) {
 4368: 	my %servers;
 4369: 	if (defined(&domain($dom,'primary'))) {
 4370: 	    my $primary=&domain($dom,'primary');
 4371: 	    my $hostname=&hostname($primary);
 4372: 	    $servers{$primary} = $hostname;
 4373: 	} else { 
 4374: 	    %servers = &get_servers($dom,'library');
 4375: 	}
 4376: 	foreach my $tryserver (keys(%servers)) {
 4377: 	    if (&reply('domroleput:'.$dom.':'.
 4378: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4379: 		last;
 4380: 	    } else {  
 4381: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4382: 	    }
 4383:         }
 4384:     }
 4385:     $dumpcount++;
 4386: }
 4387: 
 4388: sub courselog {
 4389:     my $what=shift;
 4390:     $what=time.':'.$what;
 4391:     unless ($env{'request.course.id'}) { return ''; }
 4392:     $coursedombuf{$env{'request.course.id'}}=
 4393:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4394:     $coursenumbuf{$env{'request.course.id'}}=
 4395:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4396:     $coursehombuf{$env{'request.course.id'}}=
 4397:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4398:     $coursedescrbuf{$env{'request.course.id'}}=
 4399:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4400:     $courseinstcodebuf{$env{'request.course.id'}}=
 4401:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4402:     $courseownerbuf{$env{'request.course.id'}}=
 4403:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4404:     $coursetypebuf{$env{'request.course.id'}}=
 4405:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4406:     if (defined $courselogs{$env{'request.course.id'}}) {
 4407: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4408:     } else {
 4409: 	$courselogs{$env{'request.course.id'}}.=$what;
 4410:     }
 4411:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4412: 	&flushcourselogs();
 4413:     }
 4414: }
 4415: 
 4416: sub courseacclog {
 4417:     my $fnsymb=shift;
 4418:     unless ($env{'request.course.id'}) { return ''; }
 4419:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4420:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4421:         $what.=':POST';
 4422:         # FIXME: Probably ought to escape things....
 4423: 	foreach my $key (keys(%env)) {
 4424:             if ($key=~/^form\.(.*)/) {
 4425:                 my $formitem = $1;
 4426:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4427:                     $what.=':'.$formitem.'='.$env{$key};
 4428:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4429:                     $what.=':'.$formitem.'='.$env{$key};
 4430:                 }
 4431:             }
 4432:         }
 4433:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4434:         # FIXME: We should not be depending on a form parameter that someone
 4435:         # editing lonsearchcat.pm might change in the future.
 4436:         if ($env{'form.phase'} eq 'course_search') {
 4437:             $what.= ':POST';
 4438:             # FIXME: Probably ought to escape things....
 4439:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4440:                                  'crsdiscuss') {
 4441:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4442:             }
 4443:         }
 4444:     }
 4445:     &courselog($what);
 4446: }
 4447: 
 4448: sub countacc {
 4449:     my $url=&declutter(shift);
 4450:     return if (! defined($url) || $url eq '');
 4451:     unless ($env{'request.course.id'}) { return ''; }
 4452: #
 4453: # Mark that this url was used in this course
 4454: #
 4455:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4456: #
 4457: # Increase the access count for this resource in this child process
 4458: #
 4459:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4460:     $accesshash{$key}++;
 4461: }
 4462: 
 4463: sub linklog {
 4464:     my ($from,$to)=@_;
 4465:     $from=&declutter($from);
 4466:     $to=&declutter($to);
 4467:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4468:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4469: }
 4470: 
 4471: sub statslog {
 4472:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4473:     if ($users<2) { return; }
 4474:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4475:             'course'       => $env{'request.course.id'},
 4476:             'sections'     => '"all"',
 4477:             'num_students' => $users,
 4478:             'part'         => $part,
 4479:             'symb'         => $symb,
 4480:             'mean_tries'   => $av_attempts,
 4481:             'deg_of_diff'  => $degdiff});
 4482:     foreach my $key (keys(%dynstore)) {
 4483:         $accesshash{$key}=$dynstore{$key};
 4484:     }
 4485: }
 4486:   
 4487: sub userrolelog {
 4488:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4489:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4490:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4491:        $userrolehash
 4492:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4493:                     =$tend.':'.$tstart;
 4494:     }
 4495:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4496:        $userrolehash
 4497:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4498:                     =$tend.':'.$tstart;
 4499:     }
 4500:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4501:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4502:        $domainrolehash
 4503:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4504:                     = $tend.':'.$tstart;
 4505:     }
 4506: }
 4507: 
 4508: sub courserolelog {
 4509:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4510:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4511:         my $cdom = $1;
 4512:         my $cnum = $2;
 4513:         my $sec = $3;
 4514:         my $namespace = 'rolelog';
 4515:         my %storehash = (
 4516:                            role    => $trole,
 4517:                            start   => $tstart,
 4518:                            end     => $tend,
 4519:                            selfenroll => $selfenroll,
 4520:                            context    => $context,
 4521:                         );
 4522:         if ($trole eq 'gr') {
 4523:             $namespace = 'groupslog';
 4524:             $storehash{'group'} = $sec;
 4525:         } else {
 4526:             $storehash{'section'} = $sec;
 4527:         }
 4528:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4529:                    $domain,$cnum,$cdom);
 4530:         if (($trole ne 'st') || ($sec ne '')) {
 4531:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4532:         }
 4533:     }
 4534:     return;
 4535: }
 4536: 
 4537: sub domainrolelog {
 4538:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4539:     if ($area =~ m{^/($match_domain)/$}) {
 4540:         my $cdom = $1;
 4541:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4542:         my $namespace = 'rolelog';
 4543:         my %storehash = (
 4544:                            role    => $trole,
 4545:                            start   => $tstart,
 4546:                            end     => $tend,
 4547:                            context => $context,
 4548:                         );
 4549:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4550:                    $domain,$domconfiguser,$cdom);
 4551:     }
 4552:     return;
 4553: 
 4554: }
 4555: 
 4556: sub coauthorrolelog {
 4557:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4558:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4559:         my $audom = $1;
 4560:         my $auname = $2;
 4561:         my $namespace = 'rolelog';
 4562:         my %storehash = (
 4563:                            role    => $trole,
 4564:                            start   => $tstart,
 4565:                            end     => $tend,
 4566:                            context => $context,
 4567:                         );
 4568:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4569:                    $domain,$auname,$audom);
 4570:     }
 4571:     return;
 4572: }
 4573: 
 4574: sub get_course_adv_roles {
 4575:     my ($cid,$codes) = @_;
 4576:     $cid=$env{'request.course.id'} unless (defined($cid));
 4577:     my %coursehash=&coursedescription($cid);
 4578:     my $crstype = &Apache::loncommon::course_type($cid);
 4579:     my %nothide=();
 4580:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4581:         if ($user !~ /:/) {
 4582: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4583:         } else {
 4584:             $nothide{$user}=1;
 4585:         }
 4586:     }
 4587:     my @possdoms = ($coursehash{'domain'});
 4588:     if ($coursehash{'checkforpriv'}) {
 4589:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4590:     }
 4591:     my %returnhash=();
 4592:     my %dumphash=
 4593:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4594:     my $now=time;
 4595:     my %privileged;
 4596:     foreach my $entry (keys(%dumphash)) {
 4597: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4598:         if (($tstart) && ($tstart<0)) { next; }
 4599:         if (($tend) && ($tend<$now)) { next; }
 4600:         if (($tstart) && ($now<$tstart)) { next; }
 4601:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4602: 	if ($username eq '' || $domain eq '') { next; }
 4603:         if ((&privileged($username,$domain,\@possdoms)) &&
 4604:             (!$nothide{$username.':'.$domain})) { next; }
 4605: 	if ($role eq 'cr') { next; }
 4606:         if ($codes) {
 4607:             if ($section) { $role .= ':'.$section; }
 4608:             if ($returnhash{$role}) {
 4609:                 $returnhash{$role}.=','.$username.':'.$domain;
 4610:             } else {
 4611:                 $returnhash{$role}=$username.':'.$domain;
 4612:             }
 4613:         } else {
 4614:             my $key=&plaintext($role,$crstype);
 4615:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4616:             if ($returnhash{$key}) {
 4617: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4618:             } else {
 4619:                 $returnhash{$key}=$username.':'.$domain;
 4620:             }
 4621:         }
 4622:     }
 4623:     return %returnhash;
 4624: }
 4625: 
 4626: sub get_my_roles {
 4627:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4628:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4629:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4630:     my (%dumphash,%nothide);
 4631:     if ($context eq 'userroles') {
 4632:         %dumphash = &dump('roles',$udom,$uname);
 4633:     } else {
 4634:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4635:         if ($hidepriv) {
 4636:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4637:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4638:                 if ($user !~ /:/) {
 4639:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4640:                 } else {
 4641:                     $nothide{$user} = 1;
 4642:                 }
 4643:             }
 4644:         }
 4645:     }
 4646:     my %returnhash=();
 4647:     my $now=time;
 4648:     my %privileged;
 4649:     foreach my $entry (keys(%dumphash)) {
 4650:         my ($role,$tend,$tstart);
 4651:         if ($context eq 'userroles') {
 4652:             next if ($entry =~ /^rolesdef/);
 4653: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4654:         } else {
 4655:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4656:         }
 4657:         if (($tstart) && ($tstart<0)) { next; }
 4658:         my $status = 'active';
 4659:         if (($tend) && ($tend<=$now)) {
 4660:             $status = 'previous';
 4661:         } 
 4662:         if (($tstart) && ($now<$tstart)) {
 4663:             $status = 'future';
 4664:         }
 4665:         if (ref($types) eq 'ARRAY') {
 4666:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4667:                 next;
 4668:             } 
 4669:         } else {
 4670:             if ($status ne 'active') {
 4671:                 next;
 4672:             }
 4673:         }
 4674:         my ($rolecode,$username,$domain,$section,$area);
 4675:         if ($context eq 'userroles') {
 4676:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4677:             (undef,$domain,$username,$section) = split(/\//,$area);
 4678:         } else {
 4679:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4680:         }
 4681:         if (ref($roledoms) eq 'ARRAY') {
 4682:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4683:                 next;
 4684:             }
 4685:         }
 4686:         if (ref($roles) eq 'ARRAY') {
 4687:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4688:                 if ($role =~ /^cr\//) {
 4689:                     if (!grep(/^cr$/,@{$roles})) {
 4690:                         next;
 4691:                     }
 4692:                 } elsif ($role =~ /^gr\//) {
 4693:                     if (!grep(/^gr$/,@{$roles})) {
 4694:                         next;
 4695:                     }
 4696:                 } else {
 4697:                     next;
 4698:                 }
 4699:             }
 4700:         }
 4701:         if ($hidepriv) {
 4702:             my @privroles = ('dc','su');
 4703:             if ($context eq 'userroles') {
 4704:                 next if (grep(/^\Q$role\E$/,@privroles));
 4705:             } else {
 4706:                 my $possdoms = [$domain];
 4707:                 if (ref($roledoms) eq 'ARRAY') {
 4708:                    push(@{$possdoms},@{$roledoms}); 
 4709:                 }
 4710:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4711:                     if (!$nothide{$username.':'.$domain}) {
 4712:                         next;
 4713:                     }
 4714:                 }
 4715:             }
 4716:         }
 4717:         if ($withsec) {
 4718:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4719:                 $tstart.':'.$tend;
 4720:         } else {
 4721:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4722:         }
 4723:     }
 4724:     return %returnhash;
 4725: }
 4726: 
 4727: sub get_all_adhocroles {
 4728:     my ($dom) = @_;
 4729:     my @roles_by_num = ();
 4730:     my %domdefaults = &get_domain_defaults($dom);
 4731:     my (%description,%access_in_dom,%access_info);
 4732:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4733:         my $count = 0;
 4734:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4735:         my %ordered;
 4736:         foreach my $role (sort(keys(%domcurrent))) {
 4737:             my ($order,$desc,$access_in_dom);
 4738:             if (ref($domcurrent{$role}) eq 'HASH') {
 4739:                 $order = $domcurrent{$role}{'order'};
 4740:                 $desc = $domcurrent{$role}{'desc'};
 4741:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4742:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4743:             }
 4744:             if ($order eq '') {
 4745:                 $order = $count;
 4746:             }
 4747:             $ordered{$order} = $role;
 4748:             if ($desc ne '') {
 4749:                 $description{$role} = $desc;
 4750:             } else {
 4751:                 $description{$role}= $role;
 4752:             }
 4753:             $count++;
 4754:         }
 4755:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4756:             push(@roles_by_num,$ordered{$item});
 4757:         }
 4758:     }
 4759:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4760: }
 4761: 
 4762: sub get_my_adhocroles {
 4763:     my ($cid,$checkreg) = @_;
 4764:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4765:     if ($env{'request.course.id'} eq $cid) {
 4766:         $cdom = $env{'course.'.$cid.'.domain'};
 4767:         $cnum = $env{'course.'.$cid.'.num'};
 4768:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4769:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4770:         $cdom = $1;
 4771:         $cnum = $2;
 4772:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4773:                                      $cdom,$cnum);
 4774:     }
 4775:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4776:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4777:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4778:         if ($rosterhash{$user} ne '') {
 4779:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4780:             return ([],{}) if ($type eq 'auto');
 4781:         }
 4782:     }
 4783:     if (($cdom ne '') && ($cnum ne ''))  {
 4784:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4785:             my $then=$env{'user.login.time'};
 4786:             my $update=$env{'user.update.time'};
 4787:             if (!$update) {
 4788:                 $update = $then;
 4789:             }
 4790:             my @liveroles;
 4791:             foreach my $role ('dh','da') {
 4792:                 if ($env{"user.role.$role./$cdom/"}) {
 4793:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4794:                     my $limit = $update;
 4795:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4796:                         $limit = $then;
 4797:                     }
 4798:                     my $activerole = 1;
 4799:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4800:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4801:                     if ($activerole) {
 4802:                         push(@liveroles,$role);
 4803:                     }
 4804:                 }
 4805:             }
 4806:             if (@liveroles) {
 4807:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4808:                     my ($accessref,$accessinfo,%access_in_dom);
 4809:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4810:                     if (ref($roles_by_num) eq 'ARRAY') {
 4811:                         if (@{$roles_by_num}) {
 4812:                             my %settings;
 4813:                             if ($env{'request.course.id'} eq $cid) {
 4814:                                 foreach my $envkey (keys(%env)) {
 4815:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4816:                                         $settings{$1} = $env{$envkey};
 4817:                                     }
 4818:                                 }
 4819:                             } else {
 4820:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4821:                             }
 4822:                             my %setincrs;
 4823:                             if ($settings{'internal.adhocaccess'}) {
 4824:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4825:                             }
 4826:                             my @statuses;
 4827:                             if ($env{'environment.inststatus'}) {
 4828:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4829:                             }
 4830:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4831:                             if (ref($accessref) eq 'HASH') {
 4832:                                 %access_in_dom = %{$accessref};
 4833:                             }
 4834:                             foreach my $role (@{$roles_by_num}) {
 4835:                                 my ($curraccess,@okstatus,@personnel);
 4836:                                 if ($setincrs{$role}) {
 4837:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4838:                                     if ($curraccess eq 'status') {
 4839:                                         @okstatus = split(/\&/,$rest);
 4840:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4841:                                         @personnel = split(/\&/,$rest);
 4842:                                     }
 4843:                                 } else {
 4844:                                     $curraccess = $access_in_dom{$role};
 4845:                                     if (ref($accessinfo) eq 'HASH') {
 4846:                                         if ($curraccess eq 'status') {
 4847:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4848:                                                 @okstatus = @{$accessinfo->{$role}};
 4849:                                             }
 4850:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4851:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4852:                                                 @personnel = @{$accessinfo->{$role}};
 4853:                                             }
 4854:                                         }
 4855:                                     }
 4856:                                 }
 4857:                                 if ($curraccess eq 'none') {
 4858:                                     next;
 4859:                                 } elsif ($curraccess eq 'all') {
 4860:                                     push(@possroles,$role);
 4861:                                 } elsif ($curraccess eq 'dh') {
 4862:                                     if (grep(/^dh$/,@liveroles)) {
 4863:                                         push(@possroles,$role);
 4864:                                     } else {
 4865:                                         next;
 4866:                                     }
 4867:                                 } elsif ($curraccess eq 'da') {
 4868:                                     if (grep(/^da$/,@liveroles)) {
 4869:                                         push(@possroles,$role);
 4870:                                     } else {
 4871:                                         next;
 4872:                                     }
 4873:                                 } elsif ($curraccess eq 'status') {
 4874:                                     if (@okstatus) {
 4875:                                         if (!@statuses) {
 4876:                                             if (grep(/^default$/,@okstatus)) {
 4877:                                                 push(@possroles,$role);
 4878:                                             }
 4879:                                         } else {
 4880:                                             foreach my $status (@okstatus) {
 4881:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 4882:                                                     push(@possroles,$role);
 4883:                                                     last;
 4884:                                                 }
 4885:                                             }
 4886:                                         }
 4887:                                     }
 4888:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4889:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 4890:                                         if ($curraccess eq 'exc') {
 4891:                                             push(@possroles,$role);
 4892:                                         }
 4893:                                     } elsif ($curraccess eq 'inc') {
 4894:                                         push(@possroles,$role);
 4895:                                     }
 4896:                                 }
 4897:                             }
 4898:                         }
 4899:                     }
 4900:                 }
 4901:             }
 4902:         }
 4903:     }
 4904:     unless (ref($description) eq 'HASH') {
 4905:         if (ref($roles_by_num) eq 'ARRAY') {
 4906:             my %desc;
 4907:             map { $desc{$_} = $_; } (@{$roles_by_num});
 4908:             $description = \%desc;
 4909:         } else {
 4910:             $description = {};
 4911:         }
 4912:     }
 4913:     return (\@possroles,$description);
 4914: }
 4915: 
 4916: # ----------------------------------------------------- Frontpage Announcements
 4917: #
 4918: #
 4919: 
 4920: sub postannounce {
 4921:     my ($server,$text)=@_;
 4922:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4923:     unless ($text=~/\w/) { $text=''; }
 4924:     return &reply('setannounce:'.&escape($text),$server);
 4925: }
 4926: 
 4927: sub getannounce {
 4928: 
 4929:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4930: 	my $announcement='';
 4931: 	while (my $line = <$fh>) { $announcement .= $line; }
 4932: 	close($fh);
 4933: 	if ($announcement=~/\w/) { 
 4934: 	    return 
 4935:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4936:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4937: 	} else {
 4938: 	    return '';
 4939: 	}
 4940:     } else {
 4941: 	return '';
 4942:     }
 4943: }
 4944: 
 4945: # ---------------------------------------------------------- Course ID routines
 4946: # Deal with domain's nohist_courseid.db files
 4947: #
 4948: 
 4949: sub courseidput {
 4950:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4951:     return unless (ref($storehash) eq 'HASH');
 4952:     my $outcome;
 4953:     if ($caller eq 'timeonly') {
 4954:         my $cids = '';
 4955:         foreach my $item (keys(%$storehash)) {
 4956:             $cids.=&escape($item).'&';
 4957:         }
 4958:         $cids=~s/\&$//;
 4959:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4960:                           $coursehome);       
 4961:     } else {
 4962:         my $items = '';
 4963:         foreach my $item (keys(%$storehash)) {
 4964:             $items.= &escape($item).'='.
 4965:                      &freeze_escape($$storehash{$item}).'&';
 4966:         }
 4967:         $items=~s/\&$//;
 4968:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4969:                           $coursehome);
 4970:     }
 4971:     if ($outcome eq 'unknown_cmd') {
 4972:         my $what;
 4973:         foreach my $cid (keys(%$storehash)) {
 4974:             $what .= &escape($cid).'=';
 4975:             foreach my $item ('description','inst_code','owner','type') {
 4976:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4977:             }
 4978:             $what =~ s/\:$/&/;
 4979:         }
 4980:         $what =~ s/\&$//;  
 4981:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4982:     } else {
 4983:         return $outcome;
 4984:     }
 4985: }
 4986: 
 4987: sub courseiddump {
 4988:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4989:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4990:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4991:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4992:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 4993:     my $as_hash = 1;
 4994:     my %returnhash;
 4995:     if (!$domfilter) { $domfilter=''; }
 4996:     my %libserv = &all_library();
 4997:     foreach my $tryserver (keys(%libserv)) {
 4998:         if ( (  $hostidflag == 1 
 4999: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5000: 	     || (!defined($hostidflag)) ) {
 5001: 
 5002: 	    if (($domfilter eq '') ||
 5003: 		(&host_domain($tryserver) eq $domfilter)) {
 5004:                 my $rep;
 5005:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5006:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5007:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5008:                                 &escape($descfilter), &escape($instcodefilter), 
 5009:                                 &escape($ownerfilter), &escape($coursefilter),
 5010:                                 &escape($typefilter), &escape($regexp_ok), 
 5011:                                 $as_hash, &escape($selfenrollonly), 
 5012:                                 &escape($catfilter), $showhidden, $caller, 
 5013:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5014:                                 &escape($createdbefore), &escape($createdafter), 
 5015:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5016:                                 $reqcrsdom,&escape($reqinstcode))));
 5017:                 } else {
 5018:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5019:                              $sincefilter.':'.&escape($descfilter).':'.
 5020:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5021:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5022:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5023:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5024:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5025:                              &escape($cc_clone).':'.$cloneonly.':'.
 5026:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5027:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5028:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5029:                 }
 5030:                      
 5031:                 my @pairs=split(/\&/,$rep);
 5032:                 foreach my $item (@pairs) {
 5033:                     my ($key,$value)=split(/\=/,$item,2);
 5034:                     $key = &unescape($key);
 5035:                     next if ($key =~ /^error: 2 /);
 5036:                     my $result = &thaw_unescape($value);
 5037:                     if (ref($result) eq 'HASH') {
 5038:                         $returnhash{$key}=$result;
 5039:                     } else {
 5040:                         my @responses = split(/:/,$value);
 5041:                         my @items = ('description','inst_code','owner','type');
 5042:                         for (my $i=0; $i<@responses; $i++) {
 5043:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5044:                         }
 5045:                     }
 5046:                 }
 5047:             }
 5048:         }
 5049:     }
 5050:     return %returnhash;
 5051: }
 5052: 
 5053: sub courselastaccess {
 5054:     my ($cdom,$cnum,$hostidref) = @_;
 5055:     my %returnhash;
 5056:     if ($cdom && $cnum) {
 5057:         my $chome = &homeserver($cnum,$cdom);
 5058:         if ($chome ne 'no_host') {
 5059:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5060:             &extract_lastaccess(\%returnhash,$rep);
 5061:         }
 5062:     } else {
 5063:         if (!$cdom) { $cdom=''; }
 5064:         my %libserv = &all_library();
 5065:         foreach my $tryserver (keys(%libserv)) {
 5066:             if (ref($hostidref) eq 'ARRAY') {
 5067:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5068:             } 
 5069:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5070:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5071:                 &extract_lastaccess(\%returnhash,$rep);
 5072:             }
 5073:         }
 5074:     }
 5075:     return %returnhash;
 5076: }
 5077: 
 5078: sub extract_lastaccess {
 5079:     my ($returnhash,$rep) = @_;
 5080:     if (ref($returnhash) eq 'HASH') {
 5081:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5082:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5083:                  $rep eq '') {
 5084:             my @pairs=split(/\&/,$rep);
 5085:             foreach my $item (@pairs) {
 5086:                 my ($key,$value)=split(/\=/,$item,2);
 5087:                 $key = &unescape($key);
 5088:                 next if ($key =~ /^error: 2 /);
 5089:                 $returnhash->{$key} = &thaw_unescape($value);
 5090:             }
 5091:         }
 5092:     }
 5093:     return;
 5094: }
 5095: 
 5096: # ---------------------------------------------------------- DC e-mail
 5097: 
 5098: sub dcmailput {
 5099:     my ($domain,$msgid,$message,$server)=@_;
 5100:     my $status = &Apache::lonnet::critical(
 5101:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5102:        &escape($message),$server);
 5103:     return $status;
 5104: }
 5105: 
 5106: sub dcmaildump {
 5107:     my ($dom,$startdate,$enddate,$senders) = @_;
 5108:     my %returnhash=();
 5109: 
 5110:     if (defined(&domain($dom,'primary'))) {
 5111:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5112:                                                          &escape($enddate).':';
 5113: 	my @esc_senders=map { &escape($_)} @$senders;
 5114: 	$cmd.=&escape(join('&',@esc_senders));
 5115: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5116:             my ($key,$value) = split(/\=/,$line,2);
 5117:             if (($key) && ($value)) {
 5118:                 $returnhash{&unescape($key)} = &unescape($value);
 5119:             }
 5120:         }
 5121:     }
 5122:     return %returnhash;
 5123: }
 5124: # ---------------------------------------------------------- Domain roles
 5125: 
 5126: sub get_domain_roles {
 5127:     my ($dom,$roles,$startdate,$enddate)=@_;
 5128:     if ((!defined($startdate)) || ($startdate eq '')) {
 5129:         $startdate = '.';
 5130:     }
 5131:     if ((!defined($enddate)) || ($enddate eq '')) {
 5132:         $enddate = '.';
 5133:     }
 5134:     my $rolelist;
 5135:     if (ref($roles) eq 'ARRAY') {
 5136:         $rolelist = join('&',@{$roles});
 5137:     }
 5138:     my %personnel = ();
 5139: 
 5140:     my %servers = &get_servers($dom,'library');
 5141:     foreach my $tryserver (keys(%servers)) {
 5142: 	%{$personnel{$tryserver}}=();
 5143: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5144: 					    &escape($startdate).':'.
 5145: 					    &escape($enddate).':'.
 5146: 					    &escape($rolelist), $tryserver))) {
 5147: 	    my ($key,$value) = split(/\=/,$line,2);
 5148: 	    if (($key) && ($value)) {
 5149: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5150: 	    }
 5151: 	}
 5152:     }
 5153:     return %personnel;
 5154: }
 5155: 
 5156: sub get_active_domroles {
 5157:     my ($dom,$roles) = @_;
 5158:     return () unless (ref($roles) eq 'ARRAY');
 5159:     my $now = time;
 5160:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5161:     my %domroles;
 5162:     foreach my $server (keys(%dompersonnel)) {
 5163:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5164:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5165:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5166:         }
 5167:     }
 5168:     return %domroles;
 5169: }
 5170: 
 5171: # ----------------------------------------------------------- Interval timing 
 5172: 
 5173: {
 5174: # Caches needed for speedup of navmaps
 5175: # We don't want to cache this for very long at all (5 seconds at most)
 5176: # 
 5177: # The user for whom we cache
 5178: my $cachedkey='';
 5179: # The cached times for this user
 5180: my %cachedtimes=();
 5181: # When this was last done
 5182: my $cachedtime='';
 5183: 
 5184: sub load_all_first_access {
 5185:     my ($uname,$udom,$ignorecache)=@_;
 5186:     if (($cachedkey eq $uname.':'.$udom) &&
 5187:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5188:         (!$ignorecache)) {
 5189:         return;
 5190:     }
 5191:     $cachedtime=time;
 5192:     $cachedkey=$uname.':'.$udom;
 5193:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5194: }
 5195: 
 5196: sub get_first_access {
 5197:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5198:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5199:     if ($argsymb) { $symb=$argsymb; }
 5200:     my ($map,$id,$res)=&decode_symb($symb);
 5201:     if ($argmap) { $map = $argmap; }
 5202:     if ($type eq 'course') {
 5203: 	$res='course';
 5204:     } elsif ($type eq 'map') {
 5205: 	$res=&symbread($map);
 5206:     } else {
 5207: 	$res=$symb;
 5208:     }
 5209:     &load_all_first_access($uname,$udom,$ignorecache);
 5210:     return $cachedtimes{"$courseid\0$res"};
 5211: }
 5212: 
 5213: sub set_first_access {
 5214:     my ($type,$interval)=@_;
 5215:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5216:     my ($map,$id,$res)=&decode_symb($symb);
 5217:     if ($type eq 'course') {
 5218: 	$res='course';
 5219:     } elsif ($type eq 'map') {
 5220: 	$res=&symbread($map);
 5221:     } else {
 5222: 	$res=$symb;
 5223:     }
 5224:     $cachedkey='';
 5225:     my $firstaccess=&get_first_access($type,$symb,$map);
 5226:     if (!$firstaccess) {
 5227:         my $start = time;
 5228: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5229:                           $udom,$uname);
 5230:         if ($putres eq 'ok') {
 5231:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5232:                  $udom,$uname); 
 5233:             &appenv(
 5234:                      {
 5235:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5236:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5237:                      }
 5238:                   );
 5239:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5240:                 $cachedtimes{"$courseid\0$res"} = $start;
 5241:             }
 5242:         }
 5243:         return $putres;
 5244:     }
 5245:     return 'already_set';
 5246: }
 5247: }
 5248: 
 5249: # --------------------------------------------- Set Expire Date for Spreadsheet
 5250: 
 5251: sub expirespread {
 5252:     my ($uname,$udom,$stype,$usymb)=@_;
 5253:     my $cid=$env{'request.course.id'}; 
 5254:     if ($cid) {
 5255:        my $now=time;
 5256:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5257:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5258:                             $env{'course.'.$cid.'.num'}.
 5259: 	        	    ':nohist_expirationdates:'.
 5260:                             &escape($key).'='.$now,
 5261:                             $env{'course.'.$cid.'.home'})
 5262:     }
 5263:     return 'ok';
 5264: }
 5265: 
 5266: # ----------------------------------------------------- Devalidate Spreadsheets
 5267: 
 5268: sub devalidate {
 5269:     my ($symb,$uname,$udom)=@_;
 5270:     my $cid=$env{'request.course.id'}; 
 5271:     if ($cid) {
 5272:         # delete the stored spreadsheets for
 5273:         # - the student level sheet of this user in course's homespace
 5274:         # - the assessment level sheet for this resource 
 5275:         #   for this user in user's homespace
 5276: 	# - current conditional state info
 5277: 	my $key=$uname.':'.$udom.':';
 5278:         my $status=
 5279: 	    &del('nohist_calculatedsheets',
 5280: 		 [$key.'studentcalc:'],
 5281: 		 $env{'course.'.$cid.'.domain'},
 5282: 		 $env{'course.'.$cid.'.num'})
 5283: 		.' '.
 5284: 	    &del('nohist_calculatedsheets_'.$cid,
 5285: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5286:         unless ($status eq 'ok ok') {
 5287:            &logthis('Could not devalidate spreadsheet '.
 5288:                     $uname.' at '.$udom.' for '.
 5289: 		    $symb.': '.$status);
 5290:         }
 5291: 	&delenv('user.state.'.$cid);
 5292:     }
 5293: }
 5294: 
 5295: sub get_scalar {
 5296:     my ($string,$end) = @_;
 5297:     my $value;
 5298:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5299: 	$value = $1;
 5300:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5301: 	$value = $1;
 5302:     }
 5303:     return &unescape($value);
 5304: }
 5305: 
 5306: sub array2str {
 5307:   my (@array) = @_;
 5308:   my $result=&arrayref2str(\@array);
 5309:   $result=~s/^__ARRAY_REF__//;
 5310:   $result=~s/__END_ARRAY_REF__$//;
 5311:   return $result;
 5312: }
 5313: 
 5314: sub arrayref2str {
 5315:   my ($arrayref) = @_;
 5316:   my $result='__ARRAY_REF__';
 5317:   foreach my $elem (@$arrayref) {
 5318:     if(ref($elem) eq 'ARRAY') {
 5319:       $result.=&arrayref2str($elem).'&';
 5320:     } elsif(ref($elem) eq 'HASH') {
 5321:       $result.=&hashref2str($elem).'&';
 5322:     } elsif(ref($elem)) {
 5323:       #print("Got a ref of ".(ref($elem))." skipping.");
 5324:     } else {
 5325:       $result.=&escape($elem).'&';
 5326:     }
 5327:   }
 5328:   $result=~s/\&$//;
 5329:   $result .= '__END_ARRAY_REF__';
 5330:   return $result;
 5331: }
 5332: 
 5333: sub hash2str {
 5334:   my (%hash) = @_;
 5335:   my $result=&hashref2str(\%hash);
 5336:   $result=~s/^__HASH_REF__//;
 5337:   $result=~s/__END_HASH_REF__$//;
 5338:   return $result;
 5339: }
 5340: 
 5341: sub hashref2str {
 5342:   my ($hashref)=@_;
 5343:   my $result='__HASH_REF__';
 5344:   foreach my $key (sort(keys(%$hashref))) {
 5345:     if (ref($key) eq 'ARRAY') {
 5346:       $result.=&arrayref2str($key).'=';
 5347:     } elsif (ref($key) eq 'HASH') {
 5348:       $result.=&hashref2str($key).'=';
 5349:     } elsif (ref($key)) {
 5350:       $result.='=';
 5351:       #print("Got a ref of ".(ref($key))." skipping.");
 5352:     } else {
 5353: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5354:     }
 5355: 
 5356:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5357:       $result.=&arrayref2str($hashref->{$key}).'&';
 5358:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5359:       $result.=&hashref2str($hashref->{$key}).'&';
 5360:     } elsif(ref($hashref->{$key})) {
 5361:        $result.='&';
 5362:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5363:     } else {
 5364:       $result.=&escape($hashref->{$key}).'&';
 5365:     }
 5366:   }
 5367:   $result=~s/\&$//;
 5368:   $result .= '__END_HASH_REF__';
 5369:   return $result;
 5370: }
 5371: 
 5372: sub str2hash {
 5373:     my ($string)=@_;
 5374:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5375:     return %$hash;
 5376: }
 5377: 
 5378: sub str2hashref {
 5379:   my ($string) = @_;
 5380: 
 5381:   my %hash;
 5382: 
 5383:   if($string !~ /^__HASH_REF__/) {
 5384:       if (! ($string eq '' || !defined($string))) {
 5385: 	  $hash{'error'}='Not hash reference';
 5386:       }
 5387:       return (\%hash, $string);
 5388:   }
 5389: 
 5390:   $string =~ s/^__HASH_REF__//;
 5391: 
 5392:   while($string !~ /^__END_HASH_REF__/) {
 5393:       #key
 5394:       my $key='';
 5395:       if($string =~ /^__HASH_REF__/) {
 5396:           ($key, $string)=&str2hashref($string);
 5397:           if(defined($key->{'error'})) {
 5398:               $hash{'error'}='Bad data';
 5399:               return (\%hash, $string);
 5400:           }
 5401:       } elsif($string =~ /^__ARRAY_REF__/) {
 5402:           ($key, $string)=&str2arrayref($string);
 5403:           if($key->[0] eq 'Array reference error') {
 5404:               $hash{'error'}='Bad data';
 5405:               return (\%hash, $string);
 5406:           }
 5407:       } else {
 5408:           $string =~ s/^(.*?)=//;
 5409: 	  $key=&unescape($1);
 5410:       }
 5411:       $string =~ s/^=//;
 5412: 
 5413:       #value
 5414:       my $value='';
 5415:       if($string =~ /^__HASH_REF__/) {
 5416:           ($value, $string)=&str2hashref($string);
 5417:           if(defined($value->{'error'})) {
 5418:               $hash{'error'}='Bad data';
 5419:               return (\%hash, $string);
 5420:           }
 5421:       } elsif($string =~ /^__ARRAY_REF__/) {
 5422:           ($value, $string)=&str2arrayref($string);
 5423:           if($value->[0] eq 'Array reference error') {
 5424:               $hash{'error'}='Bad data';
 5425:               return (\%hash, $string);
 5426:           }
 5427:       } else {
 5428: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5429:       }
 5430:       $string =~ s/^&//;
 5431: 
 5432:       $hash{$key}=$value;
 5433:   }
 5434: 
 5435:   $string =~ s/^__END_HASH_REF__//;
 5436: 
 5437:   return (\%hash, $string);
 5438: }
 5439: 
 5440: sub str2array {
 5441:     my ($string)=@_;
 5442:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5443:     return @$array;
 5444: }
 5445: 
 5446: sub str2arrayref {
 5447:   my ($string) = @_;
 5448:   my @array;
 5449: 
 5450:   if($string !~ /^__ARRAY_REF__/) {
 5451:       if (! ($string eq '' || !defined($string))) {
 5452: 	  $array[0]='Array reference error';
 5453:       }
 5454:       return (\@array, $string);
 5455:   }
 5456: 
 5457:   $string =~ s/^__ARRAY_REF__//;
 5458: 
 5459:   while($string !~ /^__END_ARRAY_REF__/) {
 5460:       my $value='';
 5461:       if($string =~ /^__HASH_REF__/) {
 5462:           ($value, $string)=&str2hashref($string);
 5463:           if(defined($value->{'error'})) {
 5464:               $array[0] ='Array reference error';
 5465:               return (\@array, $string);
 5466:           }
 5467:       } elsif($string =~ /^__ARRAY_REF__/) {
 5468:           ($value, $string)=&str2arrayref($string);
 5469:           if($value->[0] eq 'Array reference error') {
 5470:               $array[0] ='Array reference error';
 5471:               return (\@array, $string);
 5472:           }
 5473:       } else {
 5474: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5475:       }
 5476:       $string =~ s/^&//;
 5477: 
 5478:       push(@array, $value);
 5479:   }
 5480: 
 5481:   $string =~ s/^__END_ARRAY_REF__//;
 5482: 
 5483:   return (\@array, $string);
 5484: }
 5485: 
 5486: # -------------------------------------------------------------------Temp Store
 5487: 
 5488: sub tmpreset {
 5489:   my ($symb,$namespace,$domain,$stuname) = @_;
 5490:   if (!$symb) {
 5491:     $symb=&symbread();
 5492:     if (!$symb) { $symb= $env{'request.url'}; }
 5493:   }
 5494:   $symb=escape($symb);
 5495: 
 5496:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5497:   $namespace=~s/\//\_/g;
 5498:   $namespace=~s/\W//g;
 5499: 
 5500:   if (!$domain) { $domain=$env{'user.domain'}; }
 5501:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5502:   if ($domain eq 'public' && $stuname eq 'public') {
 5503:       $stuname=$ENV{'REMOTE_ADDR'};
 5504:   }
 5505:   my $path=LONCAPA::tempdir();
 5506:   my %hash;
 5507:   if (tie(%hash,'GDBM_File',
 5508: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5509: 	  &GDBM_WRCREAT(),0640)) {
 5510:     foreach my $key (keys(%hash)) {
 5511:       if ($key=~ /:$symb/) {
 5512: 	delete($hash{$key});
 5513:       }
 5514:     }
 5515:   }
 5516: }
 5517: 
 5518: sub tmpstore {
 5519:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5520: 
 5521:   if (!$symb) {
 5522:     $symb=&symbread();
 5523:     if (!$symb) { $symb= $env{'request.url'}; }
 5524:   }
 5525:   $symb=escape($symb);
 5526: 
 5527:   if (!$namespace) {
 5528:     # I don't think we would ever want to store this for a course.
 5529:     # it seems this will only be used if we don't have a course.
 5530:     #$namespace=$env{'request.course.id'};
 5531:     #if (!$namespace) {
 5532:       $namespace=$env{'request.state'};
 5533:     #}
 5534:   }
 5535:   $namespace=~s/\//\_/g;
 5536:   $namespace=~s/\W//g;
 5537:   if (!$domain) { $domain=$env{'user.domain'}; }
 5538:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5539:   if ($domain eq 'public' && $stuname eq 'public') {
 5540:       $stuname=$ENV{'REMOTE_ADDR'};
 5541:   }
 5542:   my $now=time;
 5543:   my %hash;
 5544:   my $path=LONCAPA::tempdir();
 5545:   if (tie(%hash,'GDBM_File',
 5546: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5547: 	  &GDBM_WRCREAT(),0640)) {
 5548:     $hash{"version:$symb"}++;
 5549:     my $version=$hash{"version:$symb"};
 5550:     my $allkeys=''; 
 5551:     foreach my $key (keys(%$storehash)) {
 5552:       $allkeys.=$key.':';
 5553:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5554:     }
 5555:     $hash{"$version:$symb:timestamp"}=$now;
 5556:     $allkeys.='timestamp';
 5557:     $hash{"$version:keys:$symb"}=$allkeys;
 5558:     if (untie(%hash)) {
 5559:       return 'ok';
 5560:     } else {
 5561:       return "error:$!";
 5562:     }
 5563:   } else {
 5564:     return "error:$!";
 5565:   }
 5566: }
 5567: 
 5568: # -----------------------------------------------------------------Temp Restore
 5569: 
 5570: sub tmprestore {
 5571:   my ($symb,$namespace,$domain,$stuname) = @_;
 5572: 
 5573:   if (!$symb) {
 5574:     $symb=&symbread();
 5575:     if (!$symb) { $symb= $env{'request.url'}; }
 5576:   }
 5577:   $symb=escape($symb);
 5578: 
 5579:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5580: 
 5581:   if (!$domain) { $domain=$env{'user.domain'}; }
 5582:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5583:   if ($domain eq 'public' && $stuname eq 'public') {
 5584:       $stuname=$ENV{'REMOTE_ADDR'};
 5585:   }
 5586:   my %returnhash;
 5587:   $namespace=~s/\//\_/g;
 5588:   $namespace=~s/\W//g;
 5589:   my %hash;
 5590:   my $path=LONCAPA::tempdir();
 5591:   if (tie(%hash,'GDBM_File',
 5592: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5593: 	  &GDBM_READER(),0640)) {
 5594:     my $version=$hash{"version:$symb"};
 5595:     $returnhash{'version'}=$version;
 5596:     my $scope;
 5597:     for ($scope=1;$scope<=$version;$scope++) {
 5598:       my $vkeys=$hash{"$scope:keys:$symb"};
 5599:       my @keys=split(/:/,$vkeys);
 5600:       my $key;
 5601:       $returnhash{"$scope:keys"}=$vkeys;
 5602:       foreach $key (@keys) {
 5603: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5604: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5605:       }
 5606:     }
 5607:     if (!(untie(%hash))) {
 5608:       return "error:$!";
 5609:     }
 5610:   } else {
 5611:     return "error:$!";
 5612:   }
 5613:   return %returnhash;
 5614: }
 5615: 
 5616: # ----------------------------------------------------------------------- Store
 5617: 
 5618: sub store {
 5619:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5620:     my $home='';
 5621: 
 5622:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5623: 
 5624:     $symb=&symbclean($symb);
 5625:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5626: 
 5627:     if (!$domain) { $domain=$env{'user.domain'}; }
 5628:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5629: 
 5630:     &devalidate($symb,$stuname,$domain);
 5631: 
 5632:     $symb=escape($symb);
 5633:     if (!$namespace) { 
 5634:        unless ($namespace=$env{'request.course.id'}) { 
 5635:           return ''; 
 5636:        } 
 5637:     }
 5638:     if (!$home) { $home=$env{'user.home'}; }
 5639: 
 5640:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5641:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5642: 
 5643:     my $namevalue='';
 5644:     foreach my $key (keys(%$storehash)) {
 5645:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5646:     }
 5647:     $namevalue=~s/\&$//;
 5648:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5649:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5650: }
 5651: 
 5652: # -------------------------------------------------------------- Critical Store
 5653: 
 5654: sub cstore {
 5655:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5656:     my $home='';
 5657: 
 5658:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5659: 
 5660:     $symb=&symbclean($symb);
 5661:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5662: 
 5663:     if (!$domain) { $domain=$env{'user.domain'}; }
 5664:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5665: 
 5666:     &devalidate($symb,$stuname,$domain);
 5667: 
 5668:     $symb=escape($symb);
 5669:     if (!$namespace) { 
 5670:        unless ($namespace=$env{'request.course.id'}) { 
 5671:           return ''; 
 5672:        } 
 5673:     }
 5674:     if (!$home) { $home=$env{'user.home'}; }
 5675: 
 5676:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5677:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5678: 
 5679:     my $namevalue='';
 5680:     foreach my $key (keys(%$storehash)) {
 5681:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5682:     }
 5683:     $namevalue=~s/\&$//;
 5684:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5685:     return critical
 5686:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5687: }
 5688: 
 5689: # --------------------------------------------------------------------- Restore
 5690: 
 5691: sub restore {
 5692:     my ($symb,$namespace,$domain,$stuname) = @_;
 5693:     my $home='';
 5694: 
 5695:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5696: 
 5697:     if (!$symb) {
 5698:         return if ($namespace eq 'courserequests');
 5699:         unless ($symb=escape(&symbread())) { return ''; }
 5700:     } else {
 5701:         unless ($namespace eq 'courserequests') {
 5702:             $symb=&escape(&symbclean($symb));
 5703:         }
 5704:     }
 5705:     if (!$namespace) { 
 5706:        unless ($namespace=$env{'request.course.id'}) { 
 5707:           return ''; 
 5708:        } 
 5709:     }
 5710:     if (!$domain) { $domain=$env{'user.domain'}; }
 5711:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5712:     if (!$home) { $home=$env{'user.home'}; }
 5713:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5714: 
 5715:     my %returnhash=();
 5716:     foreach my $line (split(/\&/,$answer)) {
 5717: 	my ($name,$value)=split(/\=/,$line);
 5718:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5719:     }
 5720:     my $version;
 5721:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5722:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5723:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5724:        }
 5725:     }
 5726:     return %returnhash;
 5727: }
 5728: 
 5729: # ---------------------------------------------------------- Course Description
 5730: #
 5731: #  
 5732: 
 5733: sub coursedescription {
 5734:     my ($courseid,$args)=@_;
 5735:     $courseid=~s/^\///;
 5736:     $courseid=~s/\_/\//g;
 5737:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5738:     my $chome=&homeserver($cnum,$cdomain);
 5739:     my $normalid=$cdomain.'_'.$cnum;
 5740:     # need to always cache even if we get errors otherwise we keep 
 5741:     # trying and trying and trying to get the course description.
 5742:     my %envhash=();
 5743:     my %returnhash=();
 5744:     
 5745:     my $expiretime=600;
 5746:     if ($env{'request.course.id'} eq $normalid) {
 5747: 	$expiretime=120;
 5748:     }
 5749: 
 5750:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5751:     if (!$args->{'freshen_cache'}
 5752: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5753: 	foreach my $key (keys(%env)) {
 5754: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5755: 	    my ($setting) = $1;
 5756: 	    $returnhash{$setting} = $env{$key};
 5757: 	}
 5758: 	return %returnhash;
 5759:     }
 5760: 
 5761:     # get the data again
 5762: 
 5763:     if (!$args->{'one_time'}) {
 5764: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5765:     }
 5766: 
 5767:     if ($chome ne 'no_host') {
 5768:        %returnhash=&dump('environment',$cdomain,$cnum);
 5769:        if (!exists($returnhash{'con_lost'})) {
 5770: 	   my $username = $env{'user.name'}; # Defult username
 5771: 	   if(defined $args->{'user'}) {
 5772: 	       $username = $args->{'user'};
 5773: 	   }
 5774:            $returnhash{'home'}= $chome;
 5775: 	   $returnhash{'domain'} = $cdomain;
 5776: 	   $returnhash{'num'} = $cnum;
 5777:            if (!defined($returnhash{'type'})) {
 5778:                $returnhash{'type'} = 'Course';
 5779:            }
 5780:            while (my ($name,$value) = each %returnhash) {
 5781:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5782:            }
 5783:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5784:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5785: 	       $username.'_'.$cdomain.'_'.$cnum;
 5786:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5787:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5788:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5789:        }
 5790:     }
 5791:     if (!$args->{'one_time'}) {
 5792: 	&appenv(\%envhash);
 5793:     }
 5794:     return %returnhash;
 5795: }
 5796: 
 5797: sub update_released_required {
 5798:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5799:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5800:         $cid = $env{'request.course.id'};
 5801:         $cdom = $env{'course.'.$cid.'.domain'};
 5802:         $cnum = $env{'course.'.$cid.'.num'};
 5803:         $chome = $env{'course.'.$cid.'.home'};
 5804:     }
 5805:     if ($needsrelease) {
 5806:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5807:         my $needsupdate;
 5808:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5809:             $needsupdate = 1;
 5810:         } else {
 5811:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5812:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5813:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5814:                 $needsupdate = 1;
 5815:             }
 5816:         }
 5817:         if ($needsupdate) {
 5818:             my %needshash = (
 5819:                              'internal.releaserequired' => $needsrelease,
 5820:                             );
 5821:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5822:             if ($putresult eq 'ok') {
 5823:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5824:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5825:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5826:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5827:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5828:                 }
 5829:             }
 5830:         }
 5831:     }
 5832:     return;
 5833: }
 5834: 
 5835: # -------------------------------------------------See if a user is privileged
 5836: 
 5837: sub privileged {
 5838:     my ($username,$domain,$possdomains,$possroles)=@_;
 5839:     my $now = time;
 5840:     my $roles;
 5841:     if (ref($possroles) eq 'ARRAY') {
 5842:         $roles = $possroles; 
 5843:     } else {
 5844:         $roles = ['dc','su'];
 5845:     }
 5846:     if (ref($possdomains) eq 'ARRAY') {
 5847:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5848:         foreach my $dom (@{$possdomains}) {
 5849:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5850:                 (ref($privileged{$dom}) eq 'HASH')) {
 5851:                 foreach my $role (@{$roles}) {
 5852:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5853:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5854:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5855:                             return 1 unless (($end && $end < $now) ||
 5856:                                              ($start && $start > $now));
 5857:                         }
 5858:                     }
 5859:                 }
 5860:             }
 5861:         }
 5862:     } else {
 5863:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5864:         my $now = time;
 5865: 
 5866:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5867:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5868:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5869:                 return 1 unless ($tend && $tend < $now) 
 5870:                         or ($tstart && $tstart > $now);
 5871:             }
 5872:         }
 5873:     }
 5874:     return 0;
 5875: }
 5876: 
 5877: sub privileged_by_domain {
 5878:     my ($domains,$roles) = @_;
 5879:     my %privileged = ();
 5880:     my $cachetime = 60*60*24;
 5881:     my $now = time;
 5882:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5883:         return %privileged;
 5884:     }
 5885:     foreach my $dom (@{$domains}) {
 5886:         next if (ref($privileged{$dom}) eq 'HASH');
 5887:         my $needroles;
 5888:         foreach my $role (@{$roles}) {
 5889:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5890:             if (defined($cached)) {
 5891:                 if (ref($result) eq 'HASH') {
 5892:                     $privileged{$dom}{$role} = $result;
 5893:                 }
 5894:             } else {
 5895:                 $needroles = 1;
 5896:             }
 5897:         }
 5898:         if ($needroles) {
 5899:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5900:             $privileged{$dom} = {};
 5901:             foreach my $server (keys(%dompersonnel)) {
 5902:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5903:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5904:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5905:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5906:                         next if ($end && $end < $now);
 5907:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5908:                             $dompersonnel{$server}{$item};
 5909:                     }
 5910:                 }
 5911:             }
 5912:             if (ref($privileged{$dom}) eq 'HASH') {
 5913:                 foreach my $role (@{$roles}) {
 5914:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5915:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5916:                     } else {
 5917:                         my %hash = ();
 5918:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5919:                     }
 5920:                 }
 5921:             }
 5922:         }
 5923:     }
 5924:     return %privileged;
 5925: }
 5926: 
 5927: # -------------------------------------------------------- Get user privileges
 5928: 
 5929: sub rolesinit {
 5930:     my ($domain, $username) = @_;
 5931:     my %userroles = ('user.login.time' => time);
 5932:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5933: 
 5934:     # firstaccess and timerinterval are related to timed maps/resources. 
 5935:     # also, blocking can be triggered by an activating timer
 5936:     # it's saved in the user's %env.
 5937:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5938:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5939:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5940:         %timerintchk, %timerintenv);
 5941: 
 5942:     foreach my $key (keys(%firstaccess)) {
 5943:         my ($cid, $rest) = split(/\0/, $key);
 5944:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5945:     }
 5946: 
 5947:     foreach my $key (keys(%timerinterval)) {
 5948:         my ($cid,$rest) = split(/\0/,$key);
 5949:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5950:     }
 5951: 
 5952:     my %allroles=();
 5953:     my %allgroups=();
 5954: 
 5955:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5956:         my $role = $rolesdump{$area};
 5957:         $area =~ s/\_\w\w$//;
 5958: 
 5959:         my ($trole, $tend, $tstart, $group_privs);
 5960: 
 5961:         if ($role =~ /^cr/) {
 5962:         # Custom role, defined by a user 
 5963:         # e.g., user.role.cr/msu/smith/mynewrole
 5964:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5965:                 $trole = $1;
 5966:                 ($tend, $tstart) = split('_', $2);
 5967:             } else {
 5968:                 $trole = $role;
 5969:             }
 5970:         } elsif ($role =~ m|^gr/|) {
 5971:         # Role of member in a group, defined within a course/community
 5972:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5973:             ($trole, $tend, $tstart) = split(/_/, $role);
 5974:             next if $tstart eq '-1';
 5975:             ($trole, $group_privs) = split(/\//, $trole);
 5976:             $group_privs = &unescape($group_privs);
 5977:         } else {
 5978:         # Just a normal role, defined in roles.tab
 5979:             ($trole, $tend, $tstart) = split(/_/,$role);
 5980:         }
 5981: 
 5982:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5983:                  $username);
 5984:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5985: 
 5986:         # role expired or not available yet?
 5987:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5988:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5989: 
 5990:         next if $area eq '' or $trole eq '';
 5991: 
 5992:         my $spec = "$trole.$area";
 5993:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5994: 
 5995:         if ($trole =~ /^cr\//) {
 5996:         # Custom role, defined by a user
 5997:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5998:         } elsif ($trole eq 'gr') {
 5999:         # Role of a member in a group, defined within a course/community
 6000:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6001:             next;
 6002:         } else {
 6003:         # Normal role, defined in roles.tab
 6004:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6005:         }
 6006: 
 6007:         my $cid = $tdomain.'_'.$trest;
 6008:         unless ($firstaccchk{$cid}) {
 6009:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6010:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6011:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6012:                         $coursetimerstarts{$cid}{$item}; 
 6013:                 }
 6014:             }
 6015:             $firstaccchk{$cid} = 1;
 6016:         }
 6017:         unless ($timerintchk{$cid}) {
 6018:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6019:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6020:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6021:                        $coursetimerintervals{$cid}{$item};
 6022:                 }
 6023:             }
 6024:             $timerintchk{$cid} = 1;
 6025:         }
 6026:     }
 6027: 
 6028:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6029:                                                           \%allroles, \%allgroups);
 6030:     $env{'user.adv'} = $userroles{'user.adv'};
 6031:     $env{'user.rar'} = $userroles{'user.rar'};
 6032: 
 6033:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6034: }
 6035: 
 6036: sub set_arearole {
 6037:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6038:     unless ($nolog) {
 6039: # log the associated role with the area
 6040:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6041:     }
 6042:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6043: }
 6044: 
 6045: sub custom_roleprivs {
 6046:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6047:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6048:     my $homsvr = &homeserver($rauthor,$rdomain);
 6049:     if (&hostname($homsvr) ne '') {
 6050:         my ($rdummy,$roledef)=
 6051:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6052:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6053:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6054:             if (defined($syspriv)) {
 6055:                 if ($trest =~ /^$match_community$/) {
 6056:                     $syspriv =~ s/bre\&S//; 
 6057:                 }
 6058:                 $$allroles{'cm./'}.=':'.$syspriv;
 6059:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6060:             }
 6061:             if ($tdomain ne '') {
 6062:                 if (defined($dompriv)) {
 6063:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6064:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6065:                 }
 6066:                 if (($trest ne '') && (defined($coursepriv))) {
 6067:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6068:                         my $rolename = $1;
 6069:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6070:                     }
 6071:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6072:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6073:                 }
 6074:             }
 6075:         }
 6076:     }
 6077: }
 6078: 
 6079: sub course_adhocrole_privs {
 6080:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6081:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6082:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6083:         my (%currprivs,%storeprivs);
 6084:         foreach my $item (split(/:/,$coursepriv)) {
 6085:             my ($priv,$restrict) = split(/\&/,$item);
 6086:             $currprivs{$priv} = $restrict;
 6087:         }
 6088:         my (%possadd,%possremove,%full);
 6089:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6090:             my ($priv,$restrict)=split(/\&/,$item);
 6091:             $full{$priv} = $restrict;
 6092:         }
 6093:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6094:              next if ($item eq '');
 6095:              my ($rule,$rest) = split(/=/,$item);
 6096:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6097:              foreach my $priv (split(/:/,$rest)) {
 6098:                  if ($priv ne '') {
 6099:                      if ($rule eq 'off') {
 6100:                          $possremove{$priv} = 1;
 6101:                      } else {
 6102:                          $possadd{$priv} = 1;
 6103:                      }
 6104:                  }
 6105:              }
 6106:          }
 6107:          foreach my $priv (sort(keys(%full))) {
 6108:              if (exists($currprivs{$priv})) {
 6109:                  unless (exists($possremove{$priv})) {
 6110:                      $storeprivs{$priv} = $currprivs{$priv};
 6111:                  }
 6112:              } elsif (exists($possadd{$priv})) {
 6113:                  $storeprivs{$priv} = $full{$priv};
 6114:              }
 6115:          }
 6116:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6117:      }
 6118:      return $coursepriv;
 6119: }
 6120: 
 6121: sub group_roleprivs {
 6122:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6123:     my $access = 1;
 6124:     my $now = time;
 6125:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6126:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6127:     if ($access) {
 6128:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6129:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6130:     }
 6131: }
 6132: 
 6133: sub standard_roleprivs {
 6134:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6135:     if (defined($pr{$trole.':s'})) {
 6136:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6137:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6138:     }
 6139:     if ($tdomain ne '') {
 6140:         if (defined($pr{$trole.':d'})) {
 6141:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6142:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6143:         }
 6144:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6145:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6146:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6147:         }
 6148:     }
 6149: }
 6150: 
 6151: sub set_userprivs {
 6152:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6153:     my $author=0;
 6154:     my $adv=0;
 6155:     my $rar=0;
 6156:     my %grouproles = ();
 6157:     if (keys(%{$allgroups}) > 0) {
 6158:         my @groupkeys; 
 6159:         foreach my $role (keys(%{$allroles})) {
 6160:             push(@groupkeys,$role);
 6161:         }
 6162:         if (ref($groups_roles) eq 'HASH') {
 6163:             foreach my $key (keys(%{$groups_roles})) {
 6164:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6165:                     push(@groupkeys,$key);
 6166:                 }
 6167:             }
 6168:         }
 6169:         if (@groupkeys > 0) {
 6170:             foreach my $role (@groupkeys) {
 6171:                 my ($trole,$area,$sec,$extendedarea);
 6172:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6173:                     $trole = $1;
 6174:                     $area = $2;
 6175:                     $sec = $3;
 6176:                     $extendedarea = $area.$sec;
 6177:                     if (exists($$allgroups{$area})) {
 6178:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6179:                             my $spec = $trole.'.'.$extendedarea;
 6180:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6181:                                                 $$allgroups{$area}{$group};
 6182:                         }
 6183:                     }
 6184:                 }
 6185:             }
 6186:         }
 6187:     }
 6188:     foreach my $group (keys(%grouproles)) {
 6189:         $$allroles{$group} = $grouproles{$group};
 6190:     }
 6191:     foreach my $role (keys(%{$allroles})) {
 6192:         my %thesepriv;
 6193:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6194:         foreach my $item (split(/:/,$$allroles{$role})) {
 6195:             if ($item ne '') {
 6196:                 my ($privilege,$restrictions)=split(/&/,$item);
 6197:                 if ($restrictions eq '') {
 6198:                     $thesepriv{$privilege}='F';
 6199:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6200:                     $thesepriv{$privilege}.=$restrictions;
 6201:                 }
 6202:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6203:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6204:             }
 6205:         }
 6206:         my $thesestr='';
 6207:         foreach my $priv (sort(keys(%thesepriv))) {
 6208: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6209: 	}
 6210:         $userroles->{'user.priv.'.$role} = $thesestr;
 6211:     }
 6212:     return ($author,$adv,$rar);
 6213: }
 6214: 
 6215: sub role_status {
 6216:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6217:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6218:         my ($one,$two) = split(m{\./},$rolekey,2);
 6219:         (undef,undef,$$role) = split(/\./,$one,3);
 6220:         unless (!defined($$role) || $$role eq '') {
 6221:             $$where = '/'.$two;
 6222:             $$trolecode=$$role.'.'.$$where;
 6223:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6224:             $$tstatus='is';
 6225:             if ($$tstart && $$tstart>$update) {
 6226:                 $$tstatus='future';
 6227:                 if ($$tstart<$now) {
 6228:                     if ($$tstart && $$tstart>$refresh) {
 6229:                         if (($$where ne '') && ($$role ne '')) {
 6230:                             my (%allroles,%allgroups,$group_privs,
 6231:                                 %groups_roles,@rolecodes);
 6232:                             my %userroles = (
 6233:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6234:                             );
 6235:                             @rolecodes = ('cm'); 
 6236:                             my $spec=$$role.'.'.$$where;
 6237:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6238:                             if ($$role =~ /^cr\//) {
 6239:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6240:                                 push(@rolecodes,'cr');
 6241:                             } elsif ($$role eq 'gr') {
 6242:                                 push(@rolecodes,$$role);
 6243:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6244:                                                     $env{'user.name'});
 6245:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6246:                                 (undef,my $group_privs) = split(/\//,$trole);
 6247:                                 $group_privs = &unescape($group_privs);
 6248:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6249:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6250:                                 &get_groups_roles($tdomain,$trest,
 6251:                                                   \%course_roles,\@rolecodes,
 6252:                                                   \%groups_roles);
 6253:                             } else {
 6254:                                 push(@rolecodes,$$role);
 6255:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6256:                             }
 6257:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6258:                                                                    \%groups_roles);
 6259:                             &appenv(\%userroles,\@rolecodes);
 6260:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6261:                         }
 6262:                     }
 6263:                     $$tstatus = 'is';
 6264:                 }
 6265:             }
 6266:             if ($$tend) {
 6267:                 if ($$tend<$update) {
 6268:                     $$tstatus='expired';
 6269:                 } elsif ($$tend<$now) {
 6270:                     $$tstatus='will_not';
 6271:                 }
 6272:             }
 6273:         }
 6274:     }
 6275: }
 6276: 
 6277: sub get_groups_roles {
 6278:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6279:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6280:                   (ref($rolecodes) eq 'ARRAY') && 
 6281:                   (ref($groups_roles) eq 'HASH')); 
 6282:     if (keys(%{$cdom_courseroles}) > 0) {
 6283:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6284:         if ($cdom ne '' && $cnum ne '') {
 6285:             foreach my $key (keys(%{$cdom_courseroles})) {
 6286:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6287:                     my $crsrole = $1;
 6288:                     my $crssec = $2;
 6289:                     if ($crsrole =~ /^cr/) {
 6290:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6291:                             push(@{$rolecodes},'cr');
 6292:                         }
 6293:                     } else {
 6294:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6295:                             push(@{$rolecodes},$crsrole);
 6296:                         }
 6297:                     }
 6298:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6299:                     if ($crssec ne '') {
 6300:                         $rolekey .= "/$crssec";
 6301:                     }
 6302:                     $rolekey .= './';
 6303:                     $groups_roles->{$rolekey} = $rolecodes;
 6304:                 }
 6305:             }
 6306:         }
 6307:     }
 6308:     return;
 6309: }
 6310: 
 6311: sub delete_env_groupprivs {
 6312:     my ($where,$courseroles,$possroles) = @_;
 6313:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6314:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6315:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6316:         %{$courseroles->{$udom}} =
 6317:             &get_my_roles('','','userroles',['active'],
 6318:                           $possroles,[$udom],1);
 6319:     }
 6320:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6321:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6322:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6323:             my $area = '/'.$cdom.'/'.$cnum;
 6324:             my $privkey = "user.priv.$crsrole.$area";
 6325:             if ($crssec ne '') {
 6326:                 $privkey .= '/'.$crssec;
 6327:             }
 6328:             $privkey .= ".$area/$group";
 6329:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6330:         }
 6331:     }
 6332:     return;
 6333: }
 6334: 
 6335: sub check_adhoc_privs {
 6336:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6337:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6338:     if ($sec) {
 6339:         $cckey .= '/'.$sec;
 6340:     } 
 6341:     my $setprivs;
 6342:     if ($env{$cckey}) {
 6343:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6344:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6345:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6346:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6347:             $setprivs = 1;
 6348:         }
 6349:     } else {
 6350:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6351:         $setprivs = 1;
 6352:     }
 6353:     return $setprivs;
 6354: }
 6355: 
 6356: sub set_adhoc_privileges {
 6357: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6358:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6359:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6360:     if ($sec ne '') {
 6361:         $area .= '/'.$sec;
 6362:     }
 6363:     my $spec = $role.'.'.$area;
 6364:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6365:                                   $env{'user.name'},1);
 6366:     my %rolehash = ();
 6367:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6368:         my $rolename = $1;
 6369:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6370:         my %domdef = &get_domain_defaults($dcdom);
 6371:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6372:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6373:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6374:             }
 6375:         }
 6376:     } else {
 6377:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6378:     }
 6379:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6380:     &appenv(\%userroles,[$role,'cm']);
 6381:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6382:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6383:         &appenv( {'request.role'        => $spec,
 6384:                   'request.role.domain' => $dcdom,
 6385:                   'request.course.sec'  => $sec,
 6386:                  }
 6387:                );
 6388:         my $tadv=0;
 6389:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6390:         &appenv({'request.role.adv'    => $tadv});
 6391:     }
 6392: }
 6393: 
 6394: # --------------------------------------------------------------- get interface
 6395: 
 6396: sub get {
 6397:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6398:    my $items='';
 6399:    foreach my $item (@$storearr) {
 6400:        $items.=&escape($item).'&';
 6401:    }
 6402:    $items=~s/\&$//;
 6403:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6404:    if (!$uname) { $uname=$env{'user.name'}; }
 6405:    my $uhome=&homeserver($uname,$udomain);
 6406: 
 6407:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6408:    my @pairs=split(/\&/,$rep);
 6409:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6410:      return @pairs;
 6411:    }
 6412:    my %returnhash=();
 6413:    my $i=0;
 6414:    foreach my $item (@$storearr) {
 6415:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6416:       $i++;
 6417:    }
 6418:    return %returnhash;
 6419: }
 6420: 
 6421: # --------------------------------------------------------------- del interface
 6422: 
 6423: sub del {
 6424:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6425:    my $items='';
 6426:    foreach my $item (@$storearr) {
 6427:        $items.=&escape($item).'&';
 6428:    }
 6429: 
 6430:    $items=~s/\&$//;
 6431:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6432:    if (!$uname) { $uname=$env{'user.name'}; }
 6433:    my $uhome=&homeserver($uname,$udomain);
 6434:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6435: }
 6436: 
 6437: # -------------------------------------------------------------- dump interface
 6438: 
 6439: sub unserialize {
 6440:     my ($rep, $escapedkeys) = @_;
 6441: 
 6442:     return {} if $rep =~ /^error/;
 6443: 
 6444:     my %returnhash=();
 6445: 	foreach my $item (split(/\&/,$rep)) {
 6446: 	    my ($key, $value) = split(/=/, $item, 2);
 6447: 	    $key = unescape($key) unless $escapedkeys;
 6448: 	    next if $key =~ /^error: 2 /;
 6449: 	    $returnhash{$key} = &thaw_unescape($value);
 6450: 	}
 6451:     #return %returnhash;
 6452:     return \%returnhash;
 6453: }        
 6454: 
 6455: # see Lond::dump_with_regexp
 6456: # if $escapedkeys hash keys won't get unescaped.
 6457: sub dump {
 6458:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6459:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6460:     if (!$uname) { $uname=$env{'user.name'}; }
 6461:     my $uhome=&homeserver($uname,$udomain);
 6462: 
 6463:     if ($regexp) {
 6464:         $regexp=&escape($regexp);
 6465:     } else {
 6466:         $regexp='.';
 6467:     }
 6468:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6469:         # user is hosted on this machine
 6470:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6471:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6472:         return %{unserialize($reply, $escapedkeys)};
 6473:     }
 6474:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6475:     my @pairs=split(/\&/,$rep);
 6476:     my %returnhash=();
 6477:     if (!($rep =~ /^error/ )) {
 6478: 	foreach my $item (@pairs) {
 6479: 	    my ($key,$value)=split(/=/,$item,2);
 6480:         $key = unescape($key) unless $escapedkeys;
 6481:         #$key = &unescape($key);
 6482: 	    next if ($key =~ /^error: 2 /);
 6483: 	    $returnhash{$key}=&thaw_unescape($value);
 6484: 	}
 6485:     }
 6486:     return %returnhash;
 6487: }
 6488: 
 6489: 
 6490: # --------------------------------------------------------- dumpstore interface
 6491: 
 6492: sub dumpstore {
 6493:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6494:    # same as dump but keys must be escaped. They may contain colon separated
 6495:    # lists of values that may themself contain colons (e.g. symbs).
 6496:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6497: }
 6498: 
 6499: # -------------------------------------------------------------- keys interface
 6500: 
 6501: sub getkeys {
 6502:    my ($namespace,$udomain,$uname)=@_;
 6503:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6504:    if (!$uname) { $uname=$env{'user.name'}; }
 6505:    my $uhome=&homeserver($uname,$udomain);
 6506:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6507:    my @keyarray=();
 6508:    foreach my $key (split(/\&/,$rep)) {
 6509:       next if ($key =~ /^error: 2 /);
 6510:       push(@keyarray,&unescape($key));
 6511:    }
 6512:    return @keyarray;
 6513: }
 6514: 
 6515: # --------------------------------------------------------------- currentdump
 6516: sub currentdump {
 6517:    my ($courseid,$sdom,$sname)=@_;
 6518:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6519:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6520:    $sname    = $env{'user.name'}         if (! defined($sname));
 6521:    my $uhome = &homeserver($sname,$sdom);
 6522:    my $rep;
 6523: 
 6524:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6525:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6526:                    $courseid)));
 6527:    } else {
 6528:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6529:    }
 6530: 
 6531:    return if ($rep =~ /^(error:|no_such_host)/);
 6532:    #
 6533:    my %returnhash=();
 6534:    #
 6535:    if ($rep eq 'unknown_cmd') {
 6536:        # an old lond will not know currentdump
 6537:        # Do a dump and make it look like a currentdump
 6538:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6539:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6540:        my %hash = @tmp;
 6541:        @tmp=();
 6542:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6543:    } else {
 6544:        my @pairs=split(/\&/,$rep);
 6545:        foreach my $pair (@pairs) {
 6546:            my ($key,$value)=split(/=/,$pair,2);
 6547:            my ($symb,$param) = split(/:/,$key);
 6548:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6549:                                                         &thaw_unescape($value);
 6550:        }
 6551:    }
 6552:    return %returnhash;
 6553: }
 6554: 
 6555: sub convert_dump_to_currentdump{
 6556:     my %hash = %{shift()};
 6557:     my %returnhash;
 6558:     # Code ripped from lond, essentially.  The only difference
 6559:     # here is the unescaping done by lonnet::dump().  Conceivably
 6560:     # we might run in to problems with parameter names =~ /^v\./
 6561:     while (my ($key,$value) = each(%hash)) {
 6562:         my ($v,$symb,$param) = split(/:/,$key);
 6563: 	$symb  = &unescape($symb);
 6564: 	$param = &unescape($param);
 6565:         next if ($v eq 'version' || $symb eq 'keys');
 6566:         next if (exists($returnhash{$symb}) &&
 6567:                  exists($returnhash{$symb}->{$param}) &&
 6568:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6569:         $returnhash{$symb}->{$param}=$value;
 6570:         $returnhash{$symb}->{'v.'.$param}=$v;
 6571:     }
 6572:     #
 6573:     # Remove all of the keys in the hashes which keep track of
 6574:     # the version of the parameter.
 6575:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6576:         # use a foreach because we are going to delete from the hash.
 6577:         foreach my $key (keys(%$param_hash)) {
 6578:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6579:         }
 6580:     }
 6581:     return \%returnhash;
 6582: }
 6583: 
 6584: # ------------------------------------------------------ critical inc interface
 6585: 
 6586: sub cinc {
 6587:     return &inc(@_,'critical');
 6588: }
 6589: 
 6590: # --------------------------------------------------------------- inc interface
 6591: 
 6592: sub inc {
 6593:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6594:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6595:     if (!$uname) { $uname=$env{'user.name'}; }
 6596:     my $uhome=&homeserver($uname,$udomain);
 6597:     my $items='';
 6598:     if (! ref($store)) {
 6599:         # got a single value, so use that instead
 6600:         $items = &escape($store).'=&';
 6601:     } elsif (ref($store) eq 'SCALAR') {
 6602:         $items = &escape($$store).'=&';        
 6603:     } elsif (ref($store) eq 'ARRAY') {
 6604:         $items = join('=&',map {&escape($_);} @{$store});
 6605:     } elsif (ref($store) eq 'HASH') {
 6606:         while (my($key,$value) = each(%{$store})) {
 6607:             $items.= &escape($key).'='.&escape($value).'&';
 6608:         }
 6609:     }
 6610:     $items=~s/\&$//;
 6611:     if ($critical) {
 6612: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6613:     } else {
 6614: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6615:     }
 6616: }
 6617: 
 6618: # --------------------------------------------------------------- put interface
 6619: 
 6620: sub put {
 6621:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6622:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6623:    if (!$uname) { $uname=$env{'user.name'}; }
 6624:    my $uhome=&homeserver($uname,$udomain);
 6625:    my $items='';
 6626:    foreach my $item (keys(%$storehash)) {
 6627:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6628:    }
 6629:    $items=~s/\&$//;
 6630:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6631: }
 6632: 
 6633: # ------------------------------------------------------------ newput interface
 6634: 
 6635: sub newput {
 6636:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6637:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6638:    if (!$uname) { $uname=$env{'user.name'}; }
 6639:    my $uhome=&homeserver($uname,$udomain);
 6640:    my $items='';
 6641:    foreach my $key (keys(%$storehash)) {
 6642:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6643:    }
 6644:    $items=~s/\&$//;
 6645:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6646: }
 6647: 
 6648: # ---------------------------------------------------------  putstore interface
 6649: 
 6650: sub putstore {
 6651:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6652:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6653:    if (!$uname) { $uname=$env{'user.name'}; }
 6654:    my $uhome=&homeserver($uname,$udomain);
 6655:    my $items='';
 6656:    foreach my $key (keys(%$storehash)) {
 6657:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6658:    }
 6659:    $items=~s/\&$//;
 6660:    my $esc_symb=&escape($symb);
 6661:    my $esc_v=&escape($version);
 6662:    my $reply =
 6663:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6664: 	      $uhome);
 6665:    if (($tolog) && ($reply eq 'ok')) {
 6666:        my $namevalue='';
 6667:        foreach my $key (keys(%{$storehash})) {
 6668:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6669:        }
 6670:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6671:                      '&host='.&escape($perlvar{'lonHostID'}).
 6672:                      '&version='.$esc_v.
 6673:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6674:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6675:    }
 6676:    if ($reply eq 'unknown_cmd') {
 6677:        # gfall back to way things use to be done
 6678:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6679: 			    $uname);
 6680:    }
 6681:    return $reply;
 6682: }
 6683: 
 6684: sub old_putstore {
 6685:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6686:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6687:     if (!$uname) { $uname=$env{'user.name'}; }
 6688:     my $uhome=&homeserver($uname,$udomain);
 6689:     my %newstorehash;
 6690:     foreach my $item (keys(%$storehash)) {
 6691: 	my $key = $version.':'.&escape($symb).':'.$item;
 6692: 	$newstorehash{$key} = $storehash->{$item};
 6693:     }
 6694:     my $items='';
 6695:     my %allitems = ();
 6696:     foreach my $item (keys(%newstorehash)) {
 6697: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6698: 	    my $key = $1.':keys:'.$2;
 6699: 	    $allitems{$key} .= $3.':';
 6700: 	}
 6701: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6702:     }
 6703:     foreach my $item (keys(%allitems)) {
 6704: 	$allitems{$item} =~ s/\:$//;
 6705: 	$items.= $item.'='.$allitems{$item}.'&';
 6706:     }
 6707:     $items=~s/\&$//;
 6708:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6709: }
 6710: 
 6711: # ------------------------------------------------------ critical put interface
 6712: 
 6713: sub cput {
 6714:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6715:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6716:    if (!$uname) { $uname=$env{'user.name'}; }
 6717:    my $uhome=&homeserver($uname,$udomain);
 6718:    my $items='';
 6719:    foreach my $item (keys(%$storehash)) {
 6720:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6721:    }
 6722:    $items=~s/\&$//;
 6723:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6724: }
 6725: 
 6726: # -------------------------------------------------------------- eget interface
 6727: 
 6728: sub eget {
 6729:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6730:    my $items='';
 6731:    foreach my $item (@$storearr) {
 6732:        $items.=&escape($item).'&';
 6733:    }
 6734:    $items=~s/\&$//;
 6735:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6736:    if (!$uname) { $uname=$env{'user.name'}; }
 6737:    my $uhome=&homeserver($uname,$udomain);
 6738:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6739:    my @pairs=split(/\&/,$rep);
 6740:    my %returnhash=();
 6741:    my $i=0;
 6742:    foreach my $item (@$storearr) {
 6743:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6744:       $i++;
 6745:    }
 6746:    return %returnhash;
 6747: }
 6748: 
 6749: # ------------------------------------------------------------ tmpput interface
 6750: sub tmpput {
 6751:     my ($storehash,$server,$context)=@_;
 6752:     my $items='';
 6753:     foreach my $item (keys(%$storehash)) {
 6754: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6755:     }
 6756:     $items=~s/\&$//;
 6757:     if (defined($context)) {
 6758:         $items .= ':'.&escape($context);
 6759:     }
 6760:     return &reply("tmpput:$items",$server);
 6761: }
 6762: 
 6763: # ------------------------------------------------------------ tmpget interface
 6764: sub tmpget {
 6765:     my ($token,$server)=@_;
 6766:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6767:     my $rep=&reply("tmpget:$token",$server);
 6768:     my %returnhash;
 6769:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6770:         return %returnhash;
 6771:     }
 6772:     foreach my $item (split(/\&/,$rep)) {
 6773: 	my ($key,$value)=split(/=/,$item);
 6774: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6775:     }
 6776:     return %returnhash;
 6777: }
 6778: 
 6779: # ------------------------------------------------------------ tmpdel interface
 6780: sub tmpdel {
 6781:     my ($token,$server)=@_;
 6782:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6783:     return &reply("tmpdel:$token",$server);
 6784: }
 6785: 
 6786: # ------------------------------------------------------------ get_timebased_id 
 6787: 
 6788: sub get_timebased_id {
 6789:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6790:         $maxtries) = @_;
 6791:     my ($newid,$error,$dellock);
 6792:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6793:         return ('','ok','invalid call to get suffix');
 6794:     }
 6795: 
 6796: # set defaults for any optional args for which values were not supplied
 6797:     if ($who eq '') {
 6798:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6799:     }
 6800:     if (!$locktries) {
 6801:         $locktries = 3;
 6802:     }
 6803:     if (!$maxtries) {
 6804:         $maxtries = 10;
 6805:     }
 6806:     
 6807:     if (($cdom eq '') || ($cnum eq '')) {
 6808:         if ($env{'request.course.id'}) {
 6809:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6810:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6811:         }
 6812:         if (($cdom eq '') || ($cnum eq '')) {
 6813:             return ('','ok','call to get suffix not in course context');
 6814:         }
 6815:     }
 6816: 
 6817: # construct locking item
 6818:     my $lockhash = {
 6819:                       $prefix."\0".'locked_'.$keyid => $who,
 6820:                    };
 6821:     my $tries = 0;
 6822: 
 6823: # attempt to get lock on nohist_$namespace file
 6824:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6825:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6826:         $tries ++;
 6827:         sleep 1;
 6828:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6829:     }
 6830: 
 6831: # attempt to get unique identifier, based on current timestamp
 6832:     if ($gotlock eq 'ok') {
 6833:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6834:         my $id = time;
 6835:         $newid = $id;
 6836:         if ($idtype eq 'addcode') {
 6837:             $newid .= &sixnum_code();
 6838:         }
 6839:         my $idtries = 0;
 6840:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6841:             if ($idtype eq 'concat') {
 6842:                 $newid = $id.$idtries;
 6843:             } elsif ($idtype eq 'addcode') {
 6844:                 $newid = $newid.&sixnum_code();
 6845:             } else {
 6846:                 $newid ++;
 6847:             }
 6848:             $idtries ++;
 6849:         }
 6850:         if (!exists($inuse{$prefix."\0".$newid})) {
 6851:             my %new_item =  (
 6852:                               $prefix."\0".$newid => $who,
 6853:                             );
 6854:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6855:                                                  $cdom,$cnum);
 6856:             if ($putresult ne 'ok') {
 6857:                 undef($newid);
 6858:                 $error = 'error saving new item: '.$putresult;
 6859:             }
 6860:         } else {
 6861:              undef($newid);
 6862:              $error = ('error: no unique suffix available for the new item ');
 6863:         }
 6864: #  remove lock
 6865:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6866:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6867:     } else {
 6868:         $error = "error: could not obtain lockfile\n";
 6869:         $dellock = 'ok';
 6870:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6871:             $dellock = 'nolock';
 6872:         }
 6873:     }
 6874:     return ($newid,$dellock,$error);
 6875: }
 6876: 
 6877: sub sixnum_code {
 6878:     my $code;
 6879:     for (0..6) {
 6880:         $code .= int( rand(9) );
 6881:     }
 6882:     return $code;
 6883: }
 6884: 
 6885: # -------------------------------------------------- portfolio access checking
 6886: 
 6887: sub portfolio_access {
 6888:     my ($requrl,$clientip) = @_;
 6889:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6890:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6891:     if ($result) {
 6892:         my %setters;
 6893:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6894:             my ($startblock,$endblock) =
 6895:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6896:             if ($startblock && $endblock) {
 6897:                 return 'B';
 6898:             }
 6899:         } else {
 6900:             my ($startblock,$endblock) =
 6901:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6902:             if ($startblock && $endblock) {
 6903:                 return 'B';
 6904:             }
 6905:         }
 6906:     }
 6907:     if ($result eq 'ok') {
 6908:        return 'F';
 6909:     } elsif ($result =~ /^[^:]+:guest_/) {
 6910:        return 'A';
 6911:     }
 6912:     return '';
 6913: }
 6914: 
 6915: sub get_portfolio_access {
 6916:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6917: 
 6918:     if (!ref($access_hash)) {
 6919: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6920: 	my %access_controls = &get_access_controls($current_perms,$group,
 6921: 						   $file_name);
 6922: 	$access_hash = $access_controls{$file_name};
 6923:     }
 6924: 
 6925:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6926:     my $now = time;
 6927:     if (ref($access_hash) eq 'HASH') {
 6928:         foreach my $key (keys(%{$access_hash})) {
 6929:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6930:             if ($start > $now) {
 6931:                 next;
 6932:             }
 6933:             if ($end && $end<$now) {
 6934:                 next;
 6935:             }
 6936:             if ($scope eq 'public') {
 6937:                 $public = $key;
 6938:                 last;
 6939:             } elsif ($scope eq 'guest') {
 6940:                 $guest = $key;
 6941:             } elsif ($scope eq 'domains') {
 6942:                 push(@domains,$key);
 6943:             } elsif ($scope eq 'users') {
 6944:                 push(@users,$key);
 6945:             } elsif ($scope eq 'course') {
 6946:                 push(@courses,$key);
 6947:             } elsif ($scope eq 'group') {
 6948:                 push(@groups,$key);
 6949:             } elsif ($scope eq 'ip') {
 6950:                 push(@ips,$key);
 6951:             }
 6952:         }
 6953:         if ($public) {
 6954:             return 'ok';
 6955:         } elsif (@ips > 0) {
 6956:             my $allowed;
 6957:             foreach my $ipkey (@ips) {
 6958:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6959:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6960:                         $allowed = 1;
 6961:                         last; 
 6962:                     }
 6963:                 }
 6964:             }
 6965:             if ($allowed) {
 6966:                 return 'ok';
 6967:             }
 6968:         }
 6969:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6970:             if ($guest) {
 6971:                 return $guest;
 6972:             }
 6973:         } else {
 6974:             if (@domains > 0) {
 6975:                 foreach my $domkey (@domains) {
 6976:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6977:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6978:                             return 'ok';
 6979:                         }
 6980:                     }
 6981:                 }
 6982:             }
 6983:             if (@users > 0) {
 6984:                 foreach my $userkey (@users) {
 6985:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6986:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6987:                             if (ref($item) eq 'HASH') {
 6988:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6989:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6990:                                     return 'ok';
 6991:                                 }
 6992:                             }
 6993:                         }
 6994:                     } 
 6995:                 }
 6996:             }
 6997:             my %roleshash;
 6998:             my @courses_and_groups = @courses;
 6999:             push(@courses_and_groups,@groups); 
 7000:             if (@courses_and_groups > 0) {
 7001:                 my (%allgroups,%allroles); 
 7002:                 my ($start,$end,$role,$sec,$group);
 7003:                 foreach my $envkey (%env) {
 7004:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7005:                         my $cid = $2.'_'.$3; 
 7006:                         if ($1 eq 'gr') {
 7007:                             $group = $4;
 7008:                             $allgroups{$cid}{$group} = $env{$envkey};
 7009:                         } else {
 7010:                             if ($4 eq '') {
 7011:                                 $sec = 'none';
 7012:                             } else {
 7013:                                 $sec = $4;
 7014:                             }
 7015:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7016:                         }
 7017:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7018:                         my $cid = $2.'_'.$3;
 7019:                         if ($4 eq '') {
 7020:                             $sec = 'none';
 7021:                         } else {
 7022:                             $sec = $4;
 7023:                         }
 7024:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7025:                     }
 7026:                 }
 7027:                 if (keys(%allroles) == 0) {
 7028:                     return;
 7029:                 }
 7030:                 foreach my $key (@courses_and_groups) {
 7031:                     my %content = %{$$access_hash{$key}};
 7032:                     my $cnum = $content{'number'};
 7033:                     my $cdom = $content{'domain'};
 7034:                     my $cid = $cdom.'_'.$cnum;
 7035:                     if (!exists($allroles{$cid})) {
 7036:                         next;
 7037:                     }    
 7038:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7039:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7040:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7041:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7042:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7043:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7044:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7045:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7046:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7047:                                         if (grep/^all$/,@sections) {
 7048:                                             return 'ok';
 7049:                                         } else {
 7050:                                             if (grep/^$sec$/,@sections) {
 7051:                                                 return 'ok';
 7052:                                             }
 7053:                                         }
 7054:                                     }
 7055:                                 }
 7056:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7057:                                     if (grep/^none$/,@groups) {
 7058:                                         return 'ok';
 7059:                                     }
 7060:                                 } else {
 7061:                                     if (grep/^all$/,@groups) {
 7062:                                         return 'ok';
 7063:                                     } 
 7064:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7065:                                         if (grep/^$group$/,@groups) {
 7066:                                             return 'ok';
 7067:                                         }
 7068:                                     }
 7069:                                 } 
 7070:                             }
 7071:                         }
 7072:                     }
 7073:                 }
 7074:             }
 7075:             if ($guest) {
 7076:                 return $guest;
 7077:             }
 7078:         }
 7079:     }
 7080:     return;
 7081: }
 7082: 
 7083: sub course_group_datechecker {
 7084:     my ($dates,$now,$status) = @_;
 7085:     my ($start,$end) = split(/\./,$dates);
 7086:     if (!$start && !$end) {
 7087:         return 'ok';
 7088:     }
 7089:     if (grep/^active$/,@{$status}) {
 7090:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7091:             return 'ok';
 7092:         }
 7093:     }
 7094:     if (grep/^previous$/,@{$status}) {
 7095:         if ($end > $now ) {
 7096:             return 'ok';
 7097:         }
 7098:     }
 7099:     if (grep/^future$/,@{$status}) {
 7100:         if ($start > $now) {
 7101:             return 'ok';
 7102:         }
 7103:     }
 7104:     return; 
 7105: }
 7106: 
 7107: sub parse_portfolio_url {
 7108:     my ($url) = @_;
 7109: 
 7110:     my ($type,$udom,$unum,$group,$file_name);
 7111:     
 7112:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7113: 	$type = 1;
 7114:         $udom = $1;
 7115:         $unum = $2;
 7116:         $file_name = $3;
 7117:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7118: 	$type = 2;
 7119:         $udom = $1;
 7120:         $unum = $2;
 7121:         $group = $3;
 7122:         $file_name = $3.'/'.$4;
 7123:     }
 7124:     if (wantarray) {
 7125: 	return ($type,$udom,$unum,$file_name,$group);
 7126:     }
 7127:     return $type;
 7128: }
 7129: 
 7130: sub is_portfolio_url {
 7131:     my ($url) = @_;
 7132:     return scalar(&parse_portfolio_url($url));
 7133: }
 7134: 
 7135: sub is_portfolio_file {
 7136:     my ($file) = @_;
 7137:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7138:         return 1;
 7139:     }
 7140:     return;
 7141: }
 7142: 
 7143: sub usertools_access {
 7144:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7145:     my ($access,%tools);
 7146:     if ($context eq '') {
 7147:         $context = 'tools';
 7148:     }
 7149:     if ($context eq 'requestcourses') {
 7150:         %tools = (
 7151:                       official   => 1,
 7152:                       unofficial => 1,
 7153:                       community  => 1,
 7154:                       textbook   => 1,
 7155:                       placement  => 1,
 7156:                       lti        => 1,
 7157:                  );
 7158:     } elsif ($context eq 'requestauthor') {
 7159:         %tools = (
 7160:                       requestauthor => 1,
 7161:                  );
 7162:     } else {
 7163:         %tools = (
 7164:                       aboutme   => 1,
 7165:                       blog      => 1,
 7166:                       webdav    => 1,
 7167:                       portfolio => 1,
 7168:                  );
 7169:     }
 7170:     return if (!defined($tools{$tool}));
 7171: 
 7172:     if (($udom eq '') || ($uname eq '')) {
 7173:         $udom = $env{'user.domain'};
 7174:         $uname = $env{'user.name'};
 7175:     }
 7176: 
 7177:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7178:         if ($action ne 'reload') {
 7179:             if ($context eq 'requestcourses') {
 7180:                 return $env{'environment.canrequest.'.$tool};
 7181:             } elsif ($context eq 'requestauthor') {
 7182:                 return $env{'environment.canrequest.author'};
 7183:             } else {
 7184:                 return $env{'environment.availabletools.'.$tool};
 7185:             }
 7186:         }
 7187:     }
 7188: 
 7189:     my ($toolstatus,$inststatus,$envkey);
 7190:     if ($context eq 'requestauthor') {
 7191:         $envkey = $context; 
 7192:     } else {
 7193:         $envkey = $context.'.'.$tool;
 7194:     }
 7195: 
 7196:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7197:          ($action ne 'reload')) {
 7198:         $toolstatus = $env{'environment.'.$envkey};
 7199:         $inststatus = $env{'environment.inststatus'};
 7200:     } else {
 7201:         if (ref($userenvref) eq 'HASH') {
 7202:             $toolstatus = $userenvref->{$envkey};
 7203:             $inststatus = $userenvref->{'inststatus'};
 7204:         } else {
 7205:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7206:             $toolstatus = $userenv{$envkey};
 7207:             $inststatus = $userenv{'inststatus'};
 7208:         }
 7209:     }
 7210: 
 7211:     if ($toolstatus ne '') {
 7212:         if ($toolstatus) {
 7213:             $access = 1;
 7214:         } else {
 7215:             $access = 0;
 7216:         }
 7217:         return $access;
 7218:     }
 7219: 
 7220:     my ($is_adv,%domdef);
 7221:     if (ref($is_advref) eq 'HASH') {
 7222:         $is_adv = $is_advref->{'is_adv'};
 7223:     } else {
 7224:         $is_adv = &is_advanced_user($udom,$uname);
 7225:     }
 7226:     if (ref($domdefref) eq 'HASH') {
 7227:         %domdef = %{$domdefref};
 7228:     } else {
 7229:         %domdef = &get_domain_defaults($udom);
 7230:     }
 7231:     if (ref($domdef{$tool}) eq 'HASH') {
 7232:         if ($is_adv) {
 7233:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7234:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7235:                     $access = 1;
 7236:                 } else {
 7237:                     $access = 0;
 7238:                 }
 7239:                 return $access;
 7240:             }
 7241:         }
 7242:         if ($inststatus ne '') {
 7243:             my ($hasaccess,$hasnoaccess);
 7244:             foreach my $affiliation (split(/:/,$inststatus)) {
 7245:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7246:                     if ($domdef{$tool}{$affiliation}) {
 7247:                         $hasaccess = 1;
 7248:                     } else {
 7249:                         $hasnoaccess = 1;
 7250:                     }
 7251:                 }
 7252:             }
 7253:             if ($hasaccess || $hasnoaccess) {
 7254:                 if ($hasaccess) {
 7255:                     $access = 1;
 7256:                 } elsif ($hasnoaccess) {
 7257:                     $access = 0; 
 7258:                 }
 7259:                 return $access;
 7260:             }
 7261:         } else {
 7262:             if ($domdef{$tool}{'default'} ne '') {
 7263:                 if ($domdef{$tool}{'default'}) {
 7264:                     $access = 1;
 7265:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7266:                     $access = 0;
 7267:                 }
 7268:                 return $access;
 7269:             }
 7270:         }
 7271:     } else {
 7272:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7273:             $access = 1;
 7274:         } else {
 7275:             $access = 0;
 7276:         }
 7277:         return $access;
 7278:     }
 7279: }
 7280: 
 7281: sub is_course_owner {
 7282:     my ($cdom,$cnum,$udom,$uname) = @_;
 7283:     if (($udom eq '') || ($uname eq '')) {
 7284:         $udom = $env{'user.domain'};
 7285:         $uname = $env{'user.name'};
 7286:     }
 7287:     unless (($udom eq '') || ($uname eq '')) {
 7288:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7289:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7290:                 return 1;
 7291:             } else {
 7292:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7293:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7294:                     return 1;
 7295:                 }
 7296:             }
 7297:         }
 7298:     }
 7299:     return;
 7300: }
 7301: 
 7302: sub is_advanced_user {
 7303:     my ($udom,$uname) = @_;
 7304:     if ($udom ne '' && $uname ne '') {
 7305:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7306:             if (wantarray) {
 7307:                 return ($env{'user.adv'},$env{'user.author'});
 7308:             } else {
 7309:                 return $env{'user.adv'};
 7310:             }
 7311:         }
 7312:     }
 7313:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7314:     my %allroles;
 7315:     my ($is_adv,$is_author);
 7316:     foreach my $role (keys(%roleshash)) {
 7317:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7318:         my $area = '/'.$tdomain.'/'.$trest;
 7319:         if ($sec ne '') {
 7320:             $area .= '/'.$sec;
 7321:         }
 7322:         if (($area ne '') && ($trole ne '')) {
 7323:             my $spec=$trole.'.'.$area;
 7324:             if ($trole =~ /^cr\//) {
 7325:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7326:             } elsif ($trole ne 'gr') {
 7327:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7328:             }
 7329:             if ($trole eq 'au') {
 7330:                 $is_author = 1;
 7331:             }
 7332:         }
 7333:     }
 7334:     foreach my $role (keys(%allroles)) {
 7335:         last if ($is_adv);
 7336:         foreach my $item (split(/:/,$allroles{$role})) {
 7337:             if ($item ne '') {
 7338:                 my ($privilege,$restrictions)=split(/&/,$item);
 7339:                 if ($privilege eq 'adv') {
 7340:                     $is_adv = 1;
 7341:                     last;
 7342:                 }
 7343:             }
 7344:         }
 7345:     }
 7346:     if (wantarray) {
 7347:         return ($is_adv,$is_author);
 7348:     }
 7349:     return $is_adv;
 7350: }
 7351: 
 7352: sub check_can_request {
 7353:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7354:     my $canreq = 0;
 7355:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7356:         $uname = $env{'user.name'};
 7357:         $udom = $env{'user.domain'};
 7358:     }
 7359:     my ($types,$typename) = &Apache::loncommon::course_types();
 7360:     my @options = ('approval','validate','autolimit');
 7361:     my $optregex = join('|',@options);
 7362:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7363:         foreach my $type (@{$types}) {
 7364:             if (&usertools_access($uname,$udom,$type,undef,
 7365:                                   'requestcourses')) {
 7366:                 $canreq ++;
 7367:                 if (ref($request_domains) eq 'HASH') {
 7368:                     push(@{$request_domains->{$type}},$udom);
 7369:                 }
 7370:                 if ($dom eq $udom) {
 7371:                     $can_request->{$type} = 1;
 7372:                 }
 7373:             }
 7374:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7375:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7376:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7377:                 if (@curr > 0) {
 7378:                     foreach my $item (@curr) {
 7379:                         if (ref($request_domains) eq 'HASH') {
 7380:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7381:                             if ($otherdom ne '') {
 7382:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7383:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7384:                                         push(@{$request_domains->{$type}},$otherdom);
 7385:                                     }
 7386:                                 } else {
 7387:                                     push(@{$request_domains->{$type}},$otherdom);
 7388:                                 }
 7389:                             }
 7390:                         }
 7391:                     }
 7392:                     unless ($dom eq $env{'user.domain'}) {
 7393:                         $canreq ++;
 7394:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7395:                             $can_request->{$type} = 1;
 7396:                         }
 7397:                     }
 7398:                 }
 7399:             }
 7400:         }
 7401:     }
 7402:     return $canreq;
 7403: }
 7404: 
 7405: # ---------------------------------------------- Custom access rule evaluation
 7406: 
 7407: sub customaccess {
 7408:     my ($priv,$uri)=@_;
 7409:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7410:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7411:     $udom = &LONCAPA::clean_domain($udom);
 7412:     $ucrs = &LONCAPA::clean_username($ucrs);
 7413:     my $access=0;
 7414:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7415: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7416: 	if ($type eq 'user') {
 7417: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7418: 		my ($tdom,$tuname)=split(m{/},$scope);
 7419: 		if ($tdom) {
 7420: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7421: 		}
 7422: 		if ($tuname) {
 7423: 		    if ($tuname ne $env{'user.name'}) { next; }
 7424: 		}
 7425: 		$access=($effect eq 'allow');
 7426: 		last;
 7427: 	    }
 7428: 	} else {
 7429: 	    if ($role) {
 7430: 		if ($role ne $urole) { next; }
 7431: 	    }
 7432: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7433: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7434: 		if ($tdom) {
 7435: 		    if ($tdom ne $udom) { next; }
 7436: 		}
 7437: 		if ($tcrs) {
 7438: 		    if ($tcrs ne $ucrs) { next; }
 7439: 		}
 7440: 		if ($tsec) {
 7441: 		    if ($tsec ne $usec) { next; }
 7442: 		}
 7443: 		$access=($effect eq 'allow');
 7444: 		last;
 7445: 	    }
 7446: 	    if ($realm eq '' && $role eq '') {
 7447: 		$access=($effect eq 'allow');
 7448: 	    }
 7449: 	}
 7450:     }
 7451:     return $access;
 7452: }
 7453: 
 7454: # ------------------------------------------------- Check for a user privilege
 7455: 
 7456: sub allowed {
 7457:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7458:     my $ver_orguri=$uri;
 7459:     $uri=&deversion($uri);
 7460:     my $orguri=$uri;
 7461:     $uri=&declutter($uri);
 7462: 
 7463:     if ($priv eq 'evb') {
 7464: # Evade communication block restrictions for specified role in a course
 7465:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7466:             return $1;
 7467:         } else {
 7468:             return;
 7469:         }
 7470:     }
 7471: 
 7472:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7473: # Free bre access to adm and meta resources
 7474:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7475: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7476: 	&& ($priv eq 'bre')) {
 7477: 	return 'F';
 7478:     }
 7479: 
 7480: # Free bre access to user's own portfolio contents
 7481:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7482:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7483: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7484:         my %setters;
 7485:         my ($startblock,$endblock) = 
 7486:             &Apache::loncommon::blockcheck(\%setters,'port');
 7487:         if ($startblock && $endblock) {
 7488:             return 'B';
 7489:         } else {
 7490:             return 'F';
 7491:         }
 7492:     }
 7493: 
 7494: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7495:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7496:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7497:         if (exists($env{'request.course.id'})) {
 7498:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7499:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7500:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7501:                 my $courseprivid=$env{'request.course.id'};
 7502:                 $courseprivid=~s/\_/\//;
 7503:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7504:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7505:                     return $1; 
 7506:                 } else {
 7507:                     if ($env{'request.course.sec'}) {
 7508:                         $courseprivid.='/'.$env{'request.course.sec'};
 7509:                     }
 7510:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7511:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7512:                         return $2;
 7513:                     }
 7514:                 }
 7515:             }
 7516:         }
 7517:     }
 7518: 
 7519: # Free bre to public access
 7520: 
 7521:     if ($priv eq 'bre') {
 7522:         my $copyright;
 7523:         unless ($uri =~ /ext\.tool/) {
 7524:             $copyright=&metadata($uri,'copyright');
 7525:         }
 7526: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7527:            return 'F'; 
 7528:         }
 7529:         if ($copyright eq 'priv') {
 7530:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7531: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7532: 		return '';
 7533:             }
 7534:         }
 7535:         if ($copyright eq 'domain') {
 7536:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7537: 	    unless (($env{'user.domain'} eq $1) ||
 7538:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7539: 		return '';
 7540:             }
 7541:         }
 7542:         if ($env{'request.role'}=~ /li\.\//) {
 7543:             # Library role, so allow browsing of resources in this domain.
 7544:             return 'F';
 7545:         }
 7546:         if ($copyright eq 'custom') {
 7547: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7548:         }
 7549:     }
 7550:     # Domain coordinator is trying to create a course
 7551:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7552:         # uri is the requested domain in this case.
 7553:         # comparison to 'request.role.domain' shows if the user has selected
 7554:         # a role of dc for the domain in question.
 7555:         return 'F' if ($uri eq $env{'request.role.domain'});
 7556:     }
 7557: 
 7558:     my $thisallowed='';
 7559:     my $statecond=0;
 7560:     my $courseprivid='';
 7561: 
 7562:     my $ownaccess;
 7563:     # Community Coordinator or Assistant Co-author browsing resource space.
 7564:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7565:         if ($uri eq '') {
 7566:             $ownaccess = 1;
 7567:         } else {
 7568:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7569:                 my $udom = $env{'user.domain'};
 7570:                 my $uname = $env{'user.name'};
 7571:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7572:                     $ownaccess = 1;
 7573:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7574:                     unless ($uri =~ m{\.\./}) {
 7575:                         $ownaccess = 1;
 7576:                     }
 7577:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7578:                     my $now = time;
 7579:                     if ($uri =~ m{^([^/]+)/?$}) {
 7580:                         my $adom = $1;
 7581:                         foreach my $key (keys(%env)) {
 7582:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7583:                                 my ($start,$end) = split('.',$env{$key});
 7584:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7585:                                     $ownaccess = 1;
 7586:                                     last;
 7587:                                 }
 7588:                             }
 7589:                         }
 7590:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7591:                         my $adom = $1;
 7592:                         my $aname = $2;
 7593:                         foreach my $role ('ca','aa') { 
 7594:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7595:                                 my ($start,$end) =
 7596:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7597:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7598:                                     $ownaccess = 1;
 7599:                                     last;
 7600:                                 }
 7601:                             }
 7602:                         }
 7603:                     }
 7604:                 }
 7605:             }
 7606:         }
 7607:     }
 7608: 
 7609: # Course
 7610: 
 7611:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7612:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7613:             $thisallowed.=$1;
 7614:         }
 7615:     }
 7616: 
 7617: # Domain
 7618: 
 7619:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7620:        =~/\Q$priv\E\&([^\:]*)/) {
 7621:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7622:             $thisallowed.=$1;
 7623:         }
 7624:     }
 7625: 
 7626: # User who is not author or co-author might still be able to edit
 7627: # resource of an author in the domain (e.g., if Domain Coordinator).
 7628:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7629:         (&allowed('mdc',$env{'request.course.id'}))) {
 7630:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7631:             $thisallowed.=$1;
 7632:         }
 7633:     }
 7634: 
 7635: # Course: uri itself is a course
 7636:     my $courseuri=$uri;
 7637:     $courseuri=~s/\_(\d)/\/$1/;
 7638:     $courseuri=~s/^([^\/])/\/$1/;
 7639: 
 7640:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7641:        =~/\Q$priv\E\&([^\:]*)/) {
 7642:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7643:             $thisallowed.=$1;
 7644:         }
 7645:     }
 7646: 
 7647: # URI is an uploaded document for this course, default permissions don't matter
 7648: # not allowing 'edit' access (editupload) to uploaded course docs
 7649:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7650: 	$thisallowed='';
 7651:         my ($match)=&is_on_map($uri);
 7652:         if ($match) {
 7653:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7654:                   =~/\Q$priv\E\&([^\:]*)/) {
 7655:                 my $value = $1;
 7656:                 if ($noblockcheck) {
 7657:                     $thisallowed.=$value;
 7658:                 } else {
 7659:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7660:                     if (@blockers > 0) {
 7661:                         $thisallowed = 'B';
 7662:                     } else {
 7663:                         $thisallowed.=$value;
 7664:                     }
 7665:                 }
 7666:             }
 7667:         } else {
 7668:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7669:             if ($refuri) {
 7670:                 if ($refuri =~ m|^/adm/|) {
 7671:                     $thisallowed='F';
 7672:                 } else {
 7673:                     $refuri=&declutter($refuri);
 7674:                     my ($match) = &is_on_map($refuri);
 7675:                     if ($match) {
 7676:                         if ($noblockcheck) {
 7677:                             $thisallowed='F';
 7678:                         } else {
 7679:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7680:                             if (@blockers > 0) {
 7681:                                 $thisallowed = 'B';
 7682:                             } else {
 7683:                                 $thisallowed='F';
 7684:                             }
 7685:                         }
 7686:                     }
 7687:                 }
 7688:             }
 7689:         }
 7690:     }
 7691: 
 7692:     if ($priv eq 'bre'
 7693: 	&& $thisallowed ne 'F' 
 7694: 	&& $thisallowed ne '2'
 7695: 	&& &is_portfolio_url($uri)) {
 7696: 	$thisallowed = &portfolio_access($uri,$clientip);
 7697:     }
 7698: 
 7699: # Full access at system, domain or course-wide level? Exit.
 7700:     if ($thisallowed=~/F/) {
 7701: 	return 'F';
 7702:     }
 7703: 
 7704: # If this is generating or modifying users, exit with special codes
 7705: 
 7706:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7707: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7708: 	    my ($audom,$auname)=split('/',$uri);
 7709: # no author name given, so this just checks on the general right to make a co-author in this domain
 7710: 	    unless ($auname) { return $thisallowed; }
 7711: # an author name is given, so we are about to actually make a co-author for a certain account
 7712: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7713: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7714: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7715: 	}
 7716: 	return $thisallowed;
 7717:     }
 7718: #
 7719: # Gathered so far: system, domain and course wide privileges
 7720: #
 7721: # Course: See if uri or referer is an individual resource that is part of 
 7722: # the course
 7723: 
 7724:     if ($env{'request.course.id'}) {
 7725: 
 7726:        $courseprivid=$env{'request.course.id'};
 7727:        if ($env{'request.course.sec'}) {
 7728:           $courseprivid.='/'.$env{'request.course.sec'};
 7729:        }
 7730:        $courseprivid=~s/\_/\//;
 7731:        my $checkreferer=1;
 7732:        my ($match,$cond)=&is_on_map($uri);
 7733:        if ($match) {
 7734:            $statecond=$cond;
 7735:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7736:                =~/\Q$priv\E\&([^\:]*)/) {
 7737:                my $value = $1;
 7738:                if ($priv eq 'bre') {
 7739:                    if ($noblockcheck) {
 7740:                        $thisallowed.=$value;
 7741:                    } else {
 7742:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7743:                        if (@blockers > 0) {
 7744:                            $thisallowed = 'B';
 7745:                        } else {
 7746:                            $thisallowed.=$value;
 7747:                        }
 7748:                    }
 7749:                } else {
 7750:                    $thisallowed.=$value;
 7751:                }
 7752:                $checkreferer=0;
 7753:            }
 7754:        }
 7755:        
 7756:        if ($checkreferer) {
 7757: 	  my $refuri=$env{'httpref.'.$orguri};
 7758:             unless ($refuri) {
 7759:                 foreach my $key (keys(%env)) {
 7760: 		    if ($key=~/^httpref\..*\*/) {
 7761: 			my $pattern=$key;
 7762:                         $pattern=~s/^httpref\.\/res\///;
 7763:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7764:                         $pattern=~s/\//\\\//g;
 7765:                         if ($orguri=~/$pattern/) {
 7766: 			    $refuri=$env{$key};
 7767:                         }
 7768:                     }
 7769:                 }
 7770:             }
 7771: 
 7772:          if ($refuri) { 
 7773: 	  $refuri=&declutter($refuri);
 7774:           my ($match,$cond)=&is_on_map($refuri);
 7775:             if ($match) {
 7776:               my $refstatecond=$cond;
 7777:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7778:                   =~/\Q$priv\E\&([^\:]*)/) {
 7779:                   my $value = $1;
 7780:                   if ($priv eq 'bre') {
 7781:                       if ($noblockcheck) {
 7782:                           $thisallowed.=$value;
 7783:                       } else {
 7784:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7785:                           if (@blockers > 0) {
 7786:                               $thisallowed = 'B';
 7787:                           } else {
 7788:                               $thisallowed.=$value;
 7789:                           }
 7790:                       }
 7791:                   } else {
 7792:                       $thisallowed.=$value;
 7793:                   }
 7794:                   $uri=$refuri;
 7795:                   $statecond=$refstatecond;
 7796:               }
 7797:           }
 7798:         }
 7799:        }
 7800:    }
 7801: 
 7802: #
 7803: # Gathered now: all privileges that could apply, and condition number
 7804: # 
 7805: #
 7806: # Full or no access?
 7807: #
 7808: 
 7809:     if ($thisallowed=~/F/) {
 7810: 	return 'F';
 7811:     }
 7812: 
 7813:     unless ($thisallowed) {
 7814:         return '';
 7815:     }
 7816: 
 7817: # Restrictions exist, deal with them
 7818: #
 7819: #   C:according to course preferences
 7820: #   R:according to resource settings
 7821: #   L:unless locked
 7822: #   X:according to user session state
 7823: #
 7824: 
 7825: # Possibly locked functionality, check all courses
 7826: # Locks might take effect only after 10 minutes cache expiration for other
 7827: # courses, and 2 minutes for current course
 7828: 
 7829:     my $envkey;
 7830:     if ($thisallowed=~/L/) {
 7831:         foreach $envkey (keys(%env)) {
 7832:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7833:                my $courseid=$2;
 7834:                my $roleid=$1.'.'.$2;
 7835:                $courseid=~s/^\///;
 7836:                my $expiretime=600;
 7837:                if ($env{'request.role'} eq $roleid) {
 7838: 		  $expiretime=120;
 7839:                }
 7840: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7841:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7842:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7843: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7844:                }
 7845:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7846:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7847: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7848:                        &log($env{'user.domain'},$env{'user.name'},
 7849:                             $env{'user.home'},
 7850:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7851:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7852:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7853: 		       return '';
 7854:                    }
 7855:                }
 7856:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7857:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7858: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7859:                        &log($env{'user.domain'},$env{'user.name'},
 7860:                             $env{'user.home'},
 7861:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7862:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7863:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7864: 		       return '';
 7865:                    }
 7866:                }
 7867: 	   }
 7868:        }
 7869:     }
 7870:    
 7871: #
 7872: # Rest of the restrictions depend on selected course
 7873: #
 7874: 
 7875:     unless ($env{'request.course.id'}) {
 7876: 	if ($thisallowed eq 'A') {
 7877: 	    return 'A';
 7878:         } elsif ($thisallowed eq 'B') {
 7879:             return 'B';
 7880: 	} else {
 7881: 	    return '1';
 7882: 	}
 7883:     }
 7884: 
 7885: #
 7886: # Now user is definitely in a course
 7887: #
 7888: 
 7889: 
 7890: # Course preferences
 7891: 
 7892:    if ($thisallowed=~/C/) {
 7893:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7894:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7895:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7896: 	   =~/\Q$rolecode\E/) {
 7897: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7898: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7899: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7900: 			$env{'request.course.id'});
 7901: 	   }
 7902:            return '';
 7903:        }
 7904: 
 7905:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7906: 	   =~/\Q$unamedom\E/) {
 7907: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7908: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7909: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7910: 			$env{'request.course.id'});
 7911: 	   }
 7912:            return '';
 7913:        }
 7914:    }
 7915: 
 7916: # Resource preferences
 7917: 
 7918:    if ($thisallowed=~/R/) {
 7919:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7920:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7921: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7922: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7923: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7924: 	   }
 7925: 	   return '';
 7926:        }
 7927:    }
 7928: 
 7929: # Restricted by state or randomout?
 7930: 
 7931:    if ($thisallowed=~/X/) {
 7932:       if ($env{'acc.randomout'}) {
 7933: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7934:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7935:             return ''; 
 7936:          }
 7937:       }
 7938:       if (&condval($statecond)) {
 7939: 	 return '2';
 7940:       } else {
 7941:          return '';
 7942:       }
 7943:    }
 7944: 
 7945:     if ($thisallowed eq 'A') {
 7946: 	return 'A';
 7947:     } elsif ($thisallowed eq 'B') {
 7948:         return 'B';
 7949:     }
 7950:    return 'F';
 7951: }
 7952: 
 7953: # ------------------------------------------- Check construction space access
 7954: 
 7955: sub constructaccess {
 7956:     my ($url,$setpriv)=@_;
 7957: 
 7958: # We do not allow editing of previous versions of files
 7959:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7960: 
 7961: # Get username and domain from URL
 7962:     my ($ownername,$ownerdomain,$ownerhome);
 7963: 
 7964:     ($ownerdomain,$ownername) =
 7965:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 7966: 
 7967: # The URL does not really point to any authorspace, forget it
 7968:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7969: 
 7970: # Now we need to see if the user has access to the authorspace of
 7971: # $ownername at $ownerdomain
 7972: 
 7973:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7974: # Real author for this?
 7975:        $ownerhome = $env{'user.home'};
 7976:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7977:           return ($ownername,$ownerdomain,$ownerhome);
 7978:        }
 7979:     } else {
 7980: # Co-author for this?
 7981:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7982:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7983:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7984:             return ($ownername,$ownerdomain,$ownerhome);
 7985:         }
 7986:         if ($env{'request.course.id'}) {
 7987:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 7988:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 7989:                 if (&allowed('mdc',$env{'request.course.id'})) {
 7990:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 7991:                     return ($ownername,$ownerdomain,$ownerhome);
 7992:                 }
 7993:             }
 7994:         }
 7995:     }
 7996: 
 7997: # We don't have any access right now. If we are not possibly going to do anything about this,
 7998: # we might as well leave
 7999:    unless ($setpriv) { return ''; }
 8000: 
 8001: # Backdoor access?
 8002:     my $allowed=&allowed('eco',$ownerdomain);
 8003: # Nope
 8004:     unless ($allowed) { return ''; }
 8005: # Looks like we may have access, but could be locked by the owner of the construction space
 8006:     if ($allowed eq 'U') {
 8007:         my %blocked=&get('environment',['domcoord.author'],
 8008:                          $ownerdomain,$ownername);
 8009: # Is blocked by owner
 8010:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8011:     }
 8012:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8013: # Grant temporary access
 8014:         my $then=$env{'user.login.time'};
 8015:         my $update=$env{'user.update.time'};
 8016:         if (!$update) { $update = $then; }
 8017:         my $refresh=$env{'user.refresh.time'};
 8018:         if (!$refresh) { $refresh = $update; }
 8019:         my $now = time;
 8020:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8021:                            $now,'ca','constructaccess');
 8022:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8023:         return($ownername,$ownerdomain,$ownerhome);
 8024:     }
 8025: # No business here
 8026:     return '';
 8027: }
 8028: 
 8029: # ----------------------------------------------------------- Content Blocking
 8030: 
 8031: {
 8032: # Caches for faster Course Contents display where content blocking
 8033: # is in operation (i.e., interval param set) for timed quiz.
 8034: #
 8035: # User for whom data are being temporarily cached.
 8036: my $cacheduser='';
 8037: # Cached blockers for this user (a hash of blocking items). 
 8038: my %cachedblockers=();
 8039: # When the data were last cached.
 8040: my $cachedlast='';
 8041: 
 8042: sub load_all_blockers {
 8043:     my ($uname,$udom,$blocks)=@_;
 8044:     if (($uname ne '') && ($udom ne '')) { 
 8045:         if (($cacheduser eq $uname.':'.$udom) &&
 8046:             (abs($cachedlast-time)<5)) {
 8047:             return;
 8048:         }
 8049:     }
 8050:     $cachedlast=time;
 8051:     $cacheduser=$uname.':'.$udom;
 8052:     %cachedblockers = &get_commblock_resources($blocks);
 8053: }
 8054: 
 8055: sub get_comm_blocks {
 8056:     my ($cdom,$cnum) = @_;
 8057:     if ($cdom eq '' || $cnum eq '') {
 8058:         return unless ($env{'request.course.id'});
 8059:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8060:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8061:     }
 8062:     my %commblocks;
 8063:     my $hashid=$cdom.'_'.$cnum;
 8064:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8065:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8066:         %commblocks = %{$blocksref};
 8067:     } else {
 8068:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8069:         my $cachetime = 600;
 8070:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8071:     }
 8072:     return %commblocks;
 8073: }
 8074: 
 8075: sub get_commblock_resources {
 8076:     my ($blocks) = @_;
 8077:     my %blockers = ();
 8078:     return %blockers unless ($env{'request.course.id'});
 8079:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8080:     my %commblocks;
 8081:     if (ref($blocks) eq 'HASH') {
 8082:         %commblocks = %{$blocks};
 8083:     } else {
 8084:         %commblocks = &get_comm_blocks();
 8085:     }
 8086:     return %blockers unless (keys(%commblocks) > 0); 
 8087:     my $navmap = Apache::lonnavmaps::navmap->new();
 8088:     return %blockers unless (ref($navmap));
 8089:     my $now = time;
 8090:     foreach my $block (keys(%commblocks)) {
 8091:         if ($block =~ /^(\d+)____(\d+)$/) {
 8092:             my ($start,$end) = ($1,$2);
 8093:             if ($start <= $now && $end >= $now) {
 8094:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8095:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8096:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8097:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8098:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8099:                             }
 8100:                         }
 8101:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8102:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8103:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8104:                             }
 8105:                         }
 8106:                     }
 8107:                 }
 8108:             }
 8109:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8110:             my $item = $1;
 8111:             my @to_test;
 8112:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8113:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8114:                     my @interval;
 8115:                     my $type = 'map';
 8116:                     if ($item eq 'course') {
 8117:                         $type = 'course';
 8118:                         @interval=&EXT("resource.0.interval");
 8119:                     } else {
 8120:                         if ($item =~ /___\d+___/) {
 8121:                             $type = 'resource';
 8122:                             @interval=&EXT("resource.0.interval",$item);
 8123:                             if (ref($navmap)) {                        
 8124:                                 my $res = $navmap->getBySymb($item); 
 8125:                                 push(@to_test,$res);
 8126:                             }
 8127:                         } else {
 8128:                             my $mapsymb = &symbread($item,1);
 8129:                             if ($mapsymb) {
 8130:                                 if (ref($navmap)) {
 8131:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8132:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8133:                                     foreach my $res (@to_test) {
 8134:                                         my $symb = $res->symb();
 8135:                                         next if ($symb eq $mapsymb);
 8136:                                         if ($symb ne '') {
 8137:                                             @interval=&EXT("resource.0.interval",$symb);
 8138:                                             if ($interval[1] eq 'map') {
 8139:                                                 last;
 8140:                                             }
 8141:                                         }
 8142:                                     }
 8143:                                 }
 8144:                             }
 8145:                         }
 8146:                     }
 8147:                     if ($interval[0] =~ /^(\d+)/) {
 8148:                         my $timelimit = $1; 
 8149:                         my $first_access;
 8150:                         if ($type eq 'resource') {
 8151:                             $first_access=&get_first_access($interval[1],$item);
 8152:                         } elsif ($type eq 'map') {
 8153:                             $first_access=&get_first_access($interval[1],undef,$item);
 8154:                         } else {
 8155:                             $first_access=&get_first_access($interval[1]);
 8156:                         }
 8157:                         if ($first_access) {
 8158:                             my $timesup = $first_access+$timelimit;
 8159:                             if ($timesup > $now) {
 8160:                                 my $activeblock;
 8161:                                 foreach my $res (@to_test) {
 8162:                                     if ($res->answerable()) {
 8163:                                         $activeblock = 1;
 8164:                                         last;
 8165:                                     }
 8166:                                 }
 8167:                                 if ($activeblock) {
 8168:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8169:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8170:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8171:                                          }
 8172:                                     }
 8173:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8174:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8175:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8176:                                         }
 8177:                                     }
 8178:                                 }
 8179:                             }
 8180:                         }
 8181:                     }
 8182:                 }
 8183:             }
 8184:         }
 8185:     }
 8186:     return %blockers;
 8187: }
 8188: 
 8189: sub has_comm_blocking {
 8190:     my ($priv,$symb,$uri,$blocks) = @_;
 8191:     my @blockers;
 8192:     return unless ($env{'request.course.id'});
 8193:     return unless ($priv eq 'bre');
 8194:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8195:     return if ($env{'request.state'} eq 'construct');
 8196:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8197:     return unless (keys(%cachedblockers) > 0);
 8198:     my (%possibles,@symbs);
 8199:     if (!$symb) {
 8200:         $symb = &symbread($uri,1,1,1,\%possibles);
 8201:     }
 8202:     if ($symb) {
 8203:         @symbs = ($symb);
 8204:     } elsif (keys(%possibles)) { 
 8205:         @symbs = keys(%possibles);
 8206:     }
 8207:     my $noblock;
 8208:     foreach my $symb (@symbs) {
 8209:         last if ($noblock);
 8210:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8211:         foreach my $block (keys(%cachedblockers)) {
 8212:             if ($block =~ /^firstaccess____(.+)$/) {
 8213:                 my $item = $1;
 8214:                 if (($item eq $map) || ($item eq $symb)) {
 8215:                     $noblock = 1;
 8216:                     last;
 8217:                 }
 8218:             }
 8219:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8220:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8221:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8222:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8223:                             push(@blockers,$block);
 8224:                         }
 8225:                     }
 8226:                 }
 8227:             }
 8228:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8229:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8230:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8231:                         push(@blockers,$block);
 8232:                     }
 8233:                 }
 8234:             }
 8235:         }
 8236:     }
 8237:     return if ($noblock);
 8238:     return @blockers;
 8239: }
 8240: }
 8241: 
 8242: # -------------------------------- Deversion and split uri into path an filename   
 8243: 
 8244: #
 8245: #   Removes the version from a URI and
 8246: #   splits it in to its filename and path to the filename.
 8247: #   Seems like File::Basename could have done this more clearly.
 8248: #   Parameters:
 8249: #      $uri   - input URI
 8250: #   Returns:
 8251: #     Two element list consisting of 
 8252: #     $pathname  - the URI up to and excluding the trailing /
 8253: #     $filename  - The part of the URI following the last /
 8254: #  NOTE:
 8255: #    Another realization of this is simply:
 8256: #    use File::Basename;
 8257: #    ...
 8258: #    $uri = shift;
 8259: #    $filename = basename($uri);
 8260: #    $path     = dirname($uri);
 8261: #    return ($filename, $path);
 8262: #
 8263: #     The implementation below is probably faster however.
 8264: #
 8265: sub split_uri_for_cond {
 8266:     my $uri=&deversion(&declutter(shift));
 8267:     my @uriparts=split(/\//,$uri);
 8268:     my $filename=pop(@uriparts);
 8269:     my $pathname=join('/',@uriparts);
 8270:     return ($pathname,$filename);
 8271: }
 8272: # --------------------------------------------------- Is a resource on the map?
 8273: 
 8274: sub is_on_map {
 8275:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8276:     #Trying to find the conditional for the file
 8277:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8278: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8279:     if ($match) {
 8280: 	return (1,$1);
 8281:     } else {
 8282: 	return (0,0);
 8283:     }
 8284: }
 8285: 
 8286: # --------------------------------------------------------- Get symb from alias
 8287: 
 8288: sub get_symb_from_alias {
 8289:     my $symb=shift;
 8290:     my ($map,$resid,$url)=&decode_symb($symb);
 8291: # Already is a symb
 8292:     if ($url) { return $symb; }
 8293: # Must be an alias
 8294:     my $aliassymb='';
 8295:     my %bighash;
 8296:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8297:                             &GDBM_READER(),0640)) {
 8298:         my $rid=$bighash{'mapalias_'.$symb};
 8299: 	if ($rid) {
 8300: 	    my ($mapid,$resid)=split(/\./,$rid);
 8301: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8302: 				    $resid,$bighash{'src_'.$rid});
 8303: 	}
 8304:         untie %bighash;
 8305:     }
 8306:     return $aliassymb;
 8307: }
 8308: 
 8309: # ----------------------------------------------------------------- Define Role
 8310: 
 8311: sub definerole {
 8312:   if (allowed('mcr','/')) {
 8313:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8314:     foreach my $role (split(':',$sysrole)) {
 8315: 	my ($crole,$cqual)=split(/\&/,$role);
 8316:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8317:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8318: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8319:                return "refused:s:$crole&$cqual"; 
 8320:             }
 8321:         }
 8322:     }
 8323:     foreach my $role (split(':',$domrole)) {
 8324: 	my ($crole,$cqual)=split(/\&/,$role);
 8325:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8326:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8327: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8328:                return "refused:d:$crole&$cqual"; 
 8329:             }
 8330:         }
 8331:     }
 8332:     foreach my $role (split(':',$courole)) {
 8333: 	my ($crole,$cqual)=split(/\&/,$role);
 8334:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8335:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8336: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8337:                return "refused:c:$crole&$cqual"; 
 8338:             }
 8339:         }
 8340:     }
 8341:     my $uhome;
 8342:     if (($uname ne '') && ($udom ne '')) {
 8343:         $uhome = &homeserver($uname,$udom);
 8344:         return $uhome if ($uhome eq 'no_host');
 8345:     } else {
 8346:         $uname = $env{'user.name'};
 8347:         $udom = $env{'user.domain'};
 8348:         $uhome = $env{'user.home'};
 8349:     }
 8350:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8351:                 "$udom:$uname:rolesdef_$rolename=".
 8352:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8353:     return reply($command,$uhome);
 8354:   } else {
 8355:     return 'refused';
 8356:   }
 8357: }
 8358: 
 8359: # ---------------- Make a metadata query against the network of library servers
 8360: 
 8361: sub metadata_query {
 8362:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8363:     my %rhash;
 8364:     my %libserv = &all_library();
 8365:     my @server_list = (defined($server_array) ? @$server_array
 8366:                                               : keys(%libserv) );
 8367:     for my $server (@server_list) {
 8368:         my $domains = ''; 
 8369:         if (ref($domains_hash) eq 'HASH') {
 8370:             $domains = $domains_hash->{$server}; 
 8371:         }
 8372: 	unless ($custom or $customshow) {
 8373: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8374: 	    $rhash{$server}=$reply;
 8375: 	}
 8376: 	else {
 8377: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8378: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8379: 			     $server);
 8380: 	    $rhash{$server}=$reply;
 8381: 	}
 8382:     }
 8383:     return \%rhash;
 8384: }
 8385: 
 8386: # ----------------------------------------- Send log queries and wait for reply
 8387: 
 8388: sub log_query {
 8389:     my ($uname,$udom,$query,%filters)=@_;
 8390:     my $uhome=&homeserver($uname,$udom);
 8391:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8392:     my $uhost=&hostname($uhome);
 8393:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8394:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8395:                        $uhome);
 8396:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8397:     return get_query_reply($queryid);
 8398: }
 8399: 
 8400: # -------------------------- Update MySQL table for portfolio file
 8401: 
 8402: sub update_portfolio_table {
 8403:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8404:     if ($group ne '') {
 8405:         $file_name =~s /^\Q$group\E//;
 8406:     }
 8407:     my $homeserver = &homeserver($uname,$udom);
 8408:     my $queryid=
 8409:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8410:                ':'.&escape($file_name).':'.$action,$homeserver);
 8411:     my $reply = &get_query_reply($queryid);
 8412:     return $reply;
 8413: }
 8414: 
 8415: # -------------------------- Update MySQL allusers table
 8416: 
 8417: sub update_allusers_table {
 8418:     my ($uname,$udom,$names) = @_;
 8419:     my $homeserver = &homeserver($uname,$udom);
 8420:     my $queryid=
 8421:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8422:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8423:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8424:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8425:                'generation='.&escape($names->{'generation'}).'%%'.
 8426:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8427:                'id='.&escape($names->{'id'}),$homeserver);
 8428:     return;
 8429: }
 8430: 
 8431: # ------- Request retrieval of institutional classlists for course(s)
 8432: 
 8433: sub fetch_enrollment_query {
 8434:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8435:     my ($homeserver,$sleep,$loopmax);
 8436:     my $maxtries = 1;
 8437:     if ($context eq 'automated') {
 8438:         $homeserver = $perlvar{'lonHostID'};
 8439:         $sleep = 2;
 8440:         $loopmax = 100;
 8441:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8442:     } else {
 8443:         $homeserver = &homeserver($cnum,$dom);
 8444:     }
 8445:     my $host=&hostname($homeserver);
 8446:     my $cmd = '';
 8447:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8448:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8449:     }
 8450:     $cmd =~ s/%%$//;
 8451:     $cmd = &escape($cmd);
 8452:     my $query = 'fetchenrollment';
 8453:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8454:     unless ($queryid=~/^\Q$host\E\_/) { 
 8455:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8456:         return 'error: '.$queryid;
 8457:     }
 8458:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8459:     my $tries = 1;
 8460:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8461:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8462:         $tries ++;
 8463:     }
 8464:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8465:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8466:     } else {
 8467:         my @responses = split(/:/,$reply);
 8468:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8469:             foreach my $line (@responses) {
 8470:                 my ($key,$value) = split(/=/,$line,2);
 8471:                 $$replyref{$key} = $value;
 8472:             }
 8473:         } else {
 8474:             my $pathname = LONCAPA::tempdir();
 8475:             foreach my $line (@responses) {
 8476:                 my ($key,$value) = split(/=/,$line);
 8477:                 $$replyref{$key} = $value;
 8478:                 if ($value > 0) {
 8479:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8480:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8481:                         my $destname = $pathname.'/'.$filename;
 8482:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8483:                         if ($xml_classlist =~ /^error/) {
 8484:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8485:                         } else {
 8486:                             if ( open(FILE,">",$destname) ) {
 8487:                                 print FILE &unescape($xml_classlist);
 8488:                                 close(FILE);
 8489:                             } else {
 8490:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8491:                             }
 8492:                         }
 8493:                     }
 8494:                 }
 8495:             }
 8496:         }
 8497:         return 'ok';
 8498:     }
 8499:     return 'error';
 8500: }
 8501: 
 8502: sub get_query_reply {
 8503:     my ($queryid,$sleep,$loopmax) = @_;;
 8504:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8505:         $sleep = 0.2;
 8506:     }
 8507:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8508:         $loopmax = 100;
 8509:     }
 8510:     my $replyfile=LONCAPA::tempdir().$queryid;
 8511:     my $reply='';
 8512:     for (1..$loopmax) {
 8513: 	sleep($sleep);
 8514:         if (-e $replyfile.'.end') {
 8515: 	    if (open(my $fh,"<",$replyfile)) {
 8516: 		$reply = join('',<$fh>);
 8517: 		close($fh);
 8518: 	   } else { return 'error: reply_file_error'; }
 8519:            return &unescape($reply);
 8520: 	}
 8521:     }
 8522:     return 'timeout:'.$queryid;
 8523: }
 8524: 
 8525: sub courselog_query {
 8526: #
 8527: # possible filters:
 8528: # url: url or symb
 8529: # username
 8530: # domain
 8531: # action: view, submit, grade
 8532: # start: timestamp
 8533: # end: timestamp
 8534: #
 8535:     my (%filters)=@_;
 8536:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8537:     if ($filters{'url'}) {
 8538: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8539:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8540:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8541:     }
 8542:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8543:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8544:     return &log_query($cname,$cdom,'courselog',%filters);
 8545: }
 8546: 
 8547: sub userlog_query {
 8548: #
 8549: # possible filters:
 8550: # action: log check role
 8551: # start: timestamp
 8552: # end: timestamp
 8553: #
 8554:     my ($uname,$udom,%filters)=@_;
 8555:     return &log_query($uname,$udom,'userlog',%filters);
 8556: }
 8557: 
 8558: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8559: 
 8560: sub auto_run {
 8561:     my ($cnum,$cdom) = @_;
 8562:     my $response = 0;
 8563:     my $settings;
 8564:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8565:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8566:         $settings = $domconfig{'autoenroll'};
 8567:         if ($settings->{'run'} eq '1') {
 8568:             $response = 1;
 8569:         }
 8570:     } else {
 8571:         my $homeserver;
 8572:         if (&is_course($cdom,$cnum)) {
 8573:             $homeserver = &homeserver($cnum,$cdom);
 8574:         } else {
 8575:             $homeserver = &domain($cdom,'primary');
 8576:         }
 8577:         if ($homeserver ne 'no_host') {
 8578:             $response = &reply('autorun:'.$cdom,$homeserver);
 8579:         }
 8580:     }
 8581:     return $response;
 8582: }
 8583: 
 8584: sub auto_get_sections {
 8585:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8586:     my $homeserver;
 8587:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8588:         $homeserver = &homeserver($cnum,$cdom);
 8589:     }
 8590:     if (!defined($homeserver)) { 
 8591:         if ($cdom =~ /^$match_domain$/) {
 8592:             $homeserver = &domain($cdom,'primary');
 8593:         }
 8594:     }
 8595:     my @secs;
 8596:     if (defined($homeserver)) {
 8597:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8598:         unless ($response eq 'refused') {
 8599:             @secs = split(/:/,$response);
 8600:         }
 8601:     }
 8602:     return @secs;
 8603: }
 8604: 
 8605: sub auto_new_course {
 8606:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8607:     my $homeserver = &homeserver($cnum,$cdom);
 8608:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8609:     return $response;
 8610: }
 8611: 
 8612: sub auto_validate_courseID {
 8613:     my ($cnum,$cdom,$inst_course_id) = @_;
 8614:     my $homeserver = &homeserver($cnum,$cdom);
 8615:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8616:     return $response;
 8617: }
 8618: 
 8619: sub auto_validate_instcode {
 8620:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8621:     my ($homeserver,$response);
 8622:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8623:         $homeserver = &homeserver($cnum,$cdom);
 8624:     }
 8625:     if (!defined($homeserver)) {
 8626:         if ($cdom =~ /^$match_domain$/) {
 8627:             $homeserver = &domain($cdom,'primary');
 8628:         }
 8629:     }
 8630:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8631:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8632:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8633:     return ($outcome,$description,$defaultcredits);
 8634: }
 8635: 
 8636: sub auto_create_password {
 8637:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8638:     my ($homeserver,$response);
 8639:     my $create_passwd = 0;
 8640:     my $authchk = '';
 8641:     if ($udom =~ /^$match_domain$/) {
 8642:         $homeserver = &domain($udom,'primary');
 8643:     }
 8644:     if ($homeserver eq '') {
 8645:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8646:             $homeserver = &homeserver($cnum,$cdom);
 8647:         }
 8648:     }
 8649:     if ($homeserver eq '') {
 8650:         $authchk = 'nodomain';
 8651:     } else {
 8652:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8653:         if ($response eq 'refused') {
 8654:             $authchk = 'refused';
 8655:         } else {
 8656:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8657:         }
 8658:     }
 8659:     return ($authparam,$create_passwd,$authchk);
 8660: }
 8661: 
 8662: sub auto_photo_permission {
 8663:     my ($cnum,$cdom,$students) = @_;
 8664:     my $homeserver = &homeserver($cnum,$cdom);
 8665:     my ($outcome,$perm_reqd,$conditions) = 
 8666: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8667:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8668: 	return (undef,undef);
 8669:     }
 8670:     return ($outcome,$perm_reqd,$conditions);
 8671: }
 8672: 
 8673: sub auto_checkphotos {
 8674:     my ($uname,$udom,$pid) = @_;
 8675:     my $homeserver = &homeserver($uname,$udom);
 8676:     my ($result,$resulttype);
 8677:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8678: 				   &escape($uname).':'.&escape($pid),
 8679: 				   $homeserver));
 8680:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8681: 	return (undef,undef);
 8682:     }
 8683:     if ($outcome) {
 8684:         ($result,$resulttype) = split(/:/,$outcome);
 8685:     } 
 8686:     return ($result,$resulttype);
 8687: }
 8688: 
 8689: sub auto_photochoice {
 8690:     my ($cnum,$cdom) = @_;
 8691:     my $homeserver = &homeserver($cnum,$cdom);
 8692:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8693: 						       &escape($cdom),
 8694: 						       $homeserver)));
 8695:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8696: 	return (undef,undef);
 8697:     }
 8698:     return ($update,$comment);
 8699: }
 8700: 
 8701: sub auto_photoupdate {
 8702:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8703:     my $homeserver = &homeserver($cnum,$dom);
 8704:     my $host=&hostname($homeserver);
 8705:     my $cmd = '';
 8706:     my $maxtries = 1;
 8707:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8708:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8709:     }
 8710:     $cmd =~ s/%%$//;
 8711:     $cmd = &escape($cmd);
 8712:     my $query = 'institutionalphotos';
 8713:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8714:     unless ($queryid=~/^\Q$host\E\_/) {
 8715:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8716:         return 'error: '.$queryid;
 8717:     }
 8718:     my $reply = &get_query_reply($queryid);
 8719:     my $tries = 1;
 8720:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8721:         $reply = &get_query_reply($queryid);
 8722:         $tries ++;
 8723:     }
 8724:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8725:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8726:     } else {
 8727:         my @responses = split(/:/,$reply);
 8728:         my $outcome = shift(@responses); 
 8729:         foreach my $item (@responses) {
 8730:             my ($key,$value) = split(/=/,$item);
 8731:             $$photo{$key} = $value;
 8732:         }
 8733:         return $outcome;
 8734:     }
 8735:     return 'error';
 8736: }
 8737: 
 8738: sub auto_instcode_format {
 8739:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8740: 	$cat_order) = @_;
 8741:     my $courses = '';
 8742:     my @homeservers;
 8743:     if ($caller eq 'global') {
 8744: 	my %servers = &get_servers($codedom,'library');
 8745: 	foreach my $tryserver (keys(%servers)) {
 8746: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8747: 		push(@homeservers,$tryserver);
 8748: 	    }
 8749:         }
 8750:     } elsif ($caller eq 'requests') {
 8751:         if ($codedom =~ /^$match_domain$/) {
 8752:             my $chome = &domain($codedom,'primary');
 8753:             unless ($chome eq 'no_host') {
 8754:                 push(@homeservers,$chome);
 8755:             }
 8756:         }
 8757:     } else {
 8758:         push(@homeservers,&homeserver($caller,$codedom));
 8759:     }
 8760:     foreach my $code (keys(%{$instcodes})) {
 8761:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8762:     }
 8763:     chop($courses);
 8764:     my $ok_response = 0;
 8765:     my $response;
 8766:     while (@homeservers > 0 && $ok_response == 0) {
 8767:         my $server = shift(@homeservers); 
 8768:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8769:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8770:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8771: 		split(/:/,$response);
 8772:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8773:             push(@{$codetitles},&str2array($codetitles_str));
 8774:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8775:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8776:             $ok_response = 1;
 8777:         }
 8778:     }
 8779:     if ($ok_response) {
 8780:         return 'ok';
 8781:     } else {
 8782:         return $response;
 8783:     }
 8784: }
 8785: 
 8786: sub auto_instcode_defaults {
 8787:     my ($domain,$returnhash,$code_order) = @_;
 8788:     my @homeservers;
 8789: 
 8790:     my %servers = &get_servers($domain,'library');
 8791:     foreach my $tryserver (keys(%servers)) {
 8792: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8793: 	    push(@homeservers,$tryserver);
 8794: 	}
 8795:     }
 8796: 
 8797:     my $response;
 8798:     foreach my $server (@homeservers) {
 8799:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8800:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8801: 	
 8802: 	foreach my $pair (split(/\&/,$response)) {
 8803: 	    my ($name,$value)=split(/\=/,$pair);
 8804: 	    if ($name eq 'code_order') {
 8805: 		@{$code_order} = split(/\&/,&unescape($value));
 8806: 	    } else {
 8807: 		$returnhash->{&unescape($name)}=&unescape($value);
 8808: 	    }
 8809: 	}
 8810: 	return 'ok';
 8811:     }
 8812: 
 8813:     return $response;
 8814: }
 8815: 
 8816: sub auto_possible_instcodes {
 8817:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8818:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8819:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8820:         return;
 8821:     }
 8822:     my (@homeservers,$uhome);
 8823:     if (defined(&domain($domain,'primary'))) {
 8824:         $uhome=&domain($domain,'primary');
 8825:         push(@homeservers,&domain($domain,'primary'));
 8826:     } else {
 8827:         my %servers = &get_servers($domain,'library');
 8828:         foreach my $tryserver (keys(%servers)) {
 8829:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8830:                 push(@homeservers,$tryserver);
 8831:             }
 8832:         }
 8833:     }
 8834:     my $response;
 8835:     foreach my $server (@homeservers) {
 8836:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8837:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8838:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8839:             split(':',$response);
 8840:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8841:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8842:         foreach my $item (split('&',$cat_title)) {   
 8843:             my ($name,$value)=split('=',$item);
 8844:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8845:         }
 8846:         foreach my $item (split('&',$cat_order)) {
 8847:             my ($name,$value)=split('=',$item);
 8848:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8849:         }
 8850:         return 'ok';
 8851:     }
 8852:     return $response;
 8853: }
 8854: 
 8855: sub auto_courserequest_checks {
 8856:     my ($dom) = @_;
 8857:     my ($homeserver,%validations);
 8858:     if ($dom =~ /^$match_domain$/) {
 8859:         $homeserver = &domain($dom,'primary');
 8860:     }
 8861:     unless ($homeserver eq 'no_host') {
 8862:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8863:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8864:             my @items = split(/&/,$response);
 8865:             foreach my $item (@items) {
 8866:                 my ($key,$value) = split('=',$item);
 8867:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8868:             }
 8869:         }
 8870:     }
 8871:     return %validations; 
 8872: }
 8873: 
 8874: sub auto_courserequest_validation {
 8875:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8876:     my ($homeserver,$response);
 8877:     if ($dom =~ /^$match_domain$/) {
 8878:         $homeserver = &domain($dom,'primary');
 8879:     }
 8880:     unless ($homeserver eq 'no_host') {
 8881:         my $customdata;
 8882:         if (ref($custominfo) eq 'HASH') {
 8883:             $customdata = &freeze_escape($custominfo);
 8884:         }
 8885:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8886:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8887:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8888:                                     $customdata,$homeserver));
 8889:     }
 8890:     return $response;
 8891: }
 8892: 
 8893: sub auto_validate_class_sec {
 8894:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8895:     my $homeserver = &homeserver($cnum,$cdom);
 8896:     my $ownerlist;
 8897:     if (ref($owners) eq 'ARRAY') {
 8898:         $ownerlist = join(',',@{$owners});
 8899:     } else {
 8900:         $ownerlist = $owners;
 8901:     }
 8902:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8903:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8904:     return $response;
 8905: }
 8906: 
 8907: sub auto_validate_instclasses {
 8908:     my ($cdom,$cnum,$owners,$classesref) = @_;
 8909:     my ($homeserver,%validations);
 8910:     $homeserver = &homeserver($cnum,$cdom);
 8911:     unless ($homeserver eq 'no_host') {
 8912:         my $ownerlist;
 8913:         if (ref($owners) eq 'ARRAY') {
 8914:             $ownerlist = join(',',@{$owners});
 8915:         } else {
 8916:             $ownerlist = $owners;
 8917:         }
 8918:         if (ref($classesref) eq 'HASH') {
 8919:             my $classes = &freeze_escape($classesref);
 8920:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 8921:                                 ':'.$cdom.':'.$classes,$homeserver);
 8922:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8923:                 my @items = split(/&/,$response);
 8924:                 foreach my $item (@items) {
 8925:                     my ($key,$value) = split('=',$item);
 8926:                     $validations{&unescape($key)} = &thaw_unescape($value);
 8927:                 }
 8928:             }
 8929:         }
 8930:     }
 8931:     return %validations;
 8932: }
 8933: 
 8934: sub auto_crsreq_update {
 8935:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8936:         $code,$accessstart,$accessend,$inbound) = @_;
 8937:     my ($homeserver,%crsreqresponse);
 8938:     if ($cdom =~ /^$match_domain$/) {
 8939:         $homeserver = &domain($cdom,'primary');
 8940:     }
 8941:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8942:         my $info;
 8943:         if (ref($inbound) eq 'HASH') {
 8944:             $info = &freeze_escape($inbound);
 8945:         }
 8946:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8947:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8948:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8949:                             &escape($title).':'.&escape($code).':'.
 8950:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8951:                             $homeserver);
 8952:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8953:             my @items = split(/&/,$response);
 8954:             foreach my $item (@items) {
 8955:                 my ($key,$value) = split('=',$item);
 8956:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8957:             }
 8958:         }
 8959:     }
 8960:     return \%crsreqresponse;
 8961: }
 8962: 
 8963: sub auto_export_grades {
 8964:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 8965:     my ($homeserver,%exportresponse);
 8966:     if ($cdom =~ /^$match_domain$/) {
 8967:         $homeserver = &domain($cdom,'primary');
 8968:     }
 8969:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8970:         my $info;
 8971:         if (ref($inforef) eq 'HASH') {
 8972:             $info = &freeze_escape($inforef);
 8973:         }
 8974:         if (ref($gradesref) eq 'HASH') {
 8975:             my $grades = &freeze_escape($gradesref);
 8976:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 8977:                                 $info.':'.$grades,$homeserver);
 8978:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 8979:                 my @items = split(/&/,$response);
 8980:                 foreach my $item (@items) {
 8981:                     my ($key,$value) = split('=',$item);
 8982:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 8983:                 }
 8984:             }
 8985:         }
 8986:     }
 8987:     return \%exportresponse;
 8988: }
 8989: 
 8990: sub check_instcode_cloning {
 8991:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 8992:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8993:         return;
 8994:     }
 8995:     my $canclone;
 8996:     if (@{$code_order} > 0) {
 8997:         my $instcoderegexp ='^';
 8998:         my @clonecodes = split(/\&/,$cloner);
 8999:         foreach my $item (@{$code_order}) {
 9000:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9001:                 foreach my $pair (@clonecodes) {
 9002:                     my ($key,$val) = split(/\=/,$pair,2);
 9003:                     $val = &unescape($val);
 9004:                     if ($key eq $item) {
 9005:                         $instcoderegexp .= '('.$val.')';
 9006:                         last;
 9007:                     }
 9008:                 }
 9009:             } else {
 9010:                 $instcoderegexp .= $codedefaults->{$item};
 9011:             }
 9012:         }
 9013:         $instcoderegexp .= '$';
 9014:         my (@from,@to);
 9015:         eval {
 9016:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9017:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9018:         };
 9019:         if ((@from > 0) && (@to > 0)) {
 9020:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9021:             if (!@diffs) {
 9022:                 $canclone = 1;
 9023:             }
 9024:         }
 9025:     }
 9026:     return $canclone;
 9027: }
 9028: 
 9029: sub default_instcode_cloning {
 9030:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9031:     my (%codedefaults,@code_order,$canclone);
 9032:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9033:         %codedefaults = %{$codedefaultsref};
 9034:         @code_order = @{$codeorderref};
 9035:     } elsif ($clonedom) {
 9036:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9037:     }
 9038:     if (($domdefclone) && (@code_order)) {
 9039:         my @clonecodes = split(/\+/,$domdefclone);
 9040:         my $instcoderegexp ='^';
 9041:         foreach my $item (@code_order) {
 9042:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9043:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9044:             } else {
 9045:                 $instcoderegexp .= $codedefaults{$item};
 9046:             }
 9047:         }
 9048:         $instcoderegexp .= '$';
 9049:         my (@from,@to);
 9050:         eval {
 9051:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9052:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9053:         };
 9054:         if ((@from > 0) && (@to > 0)) {
 9055:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9056:             if (!@diffs) {
 9057:                 $canclone = 1;
 9058:             }
 9059:         }
 9060:     }
 9061:     return $canclone;
 9062: }
 9063: 
 9064: # ------------------------------------------------------- Course Group routines
 9065: 
 9066: sub get_coursegroups {
 9067:     my ($cdom,$cnum,$group,$namespace) = @_;
 9068:     return(&dump($namespace,$cdom,$cnum,$group));
 9069: }
 9070: 
 9071: sub modify_coursegroup {
 9072:     my ($cdom,$cnum,$groupsettings) = @_;
 9073:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9074: }
 9075: 
 9076: sub toggle_coursegroup_status {
 9077:     my ($cdom,$cnum,$group,$action) = @_;
 9078:     my ($from_namespace,$to_namespace);
 9079:     if ($action eq 'delete') {
 9080:         $from_namespace = 'coursegroups';
 9081:         $to_namespace = 'deleted_groups';
 9082:     } else {
 9083:         $from_namespace = 'deleted_groups';
 9084:         $to_namespace = 'coursegroups';
 9085:     }
 9086:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9087:     if (my $tmp = &error(%curr_group)) {
 9088:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9089:         return ('read error',$tmp);
 9090:     } else {
 9091:         my %savedsettings = %curr_group; 
 9092:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9093:         my $deloutcome;
 9094:         if ($result eq 'ok') {
 9095:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9096:         } else {
 9097:             return ('write error',$result);
 9098:         }
 9099:         if ($deloutcome eq 'ok') {
 9100:             return 'ok';
 9101:         } else {
 9102:             return ('delete error',$deloutcome);
 9103:         }
 9104:     }
 9105: }
 9106: 
 9107: sub modify_group_roles {
 9108:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9109:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9110:     my $role = 'gr/'.&escape($userprivs);
 9111:     my ($uname,$udom) = split(/:/,$user);
 9112:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9113:     if ($result eq 'ok') {
 9114:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9115:     }
 9116:     return $result;
 9117: }
 9118: 
 9119: sub modify_coursegroup_membership {
 9120:     my ($cdom,$cnum,$membership) = @_;
 9121:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9122:     return $result;
 9123: }
 9124: 
 9125: sub get_active_groups {
 9126:     my ($udom,$uname,$cdom,$cnum) = @_;
 9127:     my $now = time;
 9128:     my %groups = ();
 9129:     foreach my $key (keys(%env)) {
 9130:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9131:             my ($start,$end) = split(/\./,$env{$key});
 9132:             if (($end!=0) && ($end<$now)) { next; }
 9133:             if (($start!=0) && ($start>$now)) { next; }
 9134:             if ($1 eq $cdom && $2 eq $cnum) {
 9135:                 $groups{$3} = $env{$key} ;
 9136:             }
 9137:         }
 9138:     }
 9139:     return %groups;
 9140: }
 9141: 
 9142: sub get_group_membership {
 9143:     my ($cdom,$cnum,$group) = @_;
 9144:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9145: }
 9146: 
 9147: sub get_users_groups {
 9148:     my ($udom,$uname,$courseid) = @_;
 9149:     my @usersgroups;
 9150:     my $cachetime=1800;
 9151: 
 9152:     my $hashid="$udom:$uname:$courseid";
 9153:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9154:     if (defined($cached)) {
 9155:         @usersgroups = split(/:/,$grouplist);
 9156:     } else {  
 9157:         $grouplist = '';
 9158:         my $courseurl = &courseid_to_courseurl($courseid);
 9159:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9160:         my $access_end = $env{'course.'.$courseid.
 9161:                               '.default_enrollment_end_date'};
 9162:         my $now = time;
 9163:         foreach my $key (keys(%roleshash)) {
 9164:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9165:                 my $group = $1;
 9166:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9167:                     my $start = $2;
 9168:                     my $end = $1;
 9169:                     if ($start == -1) { next; } # deleted from group
 9170:                     if (($start!=0) && ($start>$now)) { next; }
 9171:                     if (($end!=0) && ($end<$now)) {
 9172:                         if ($access_end && $access_end < $now) {
 9173:                             if ($access_end - $end < 86400) {
 9174:                                 push(@usersgroups,$group);
 9175:                             }
 9176:                         }
 9177:                         next;
 9178:                     }
 9179:                     push(@usersgroups,$group);
 9180:                 }
 9181:             }
 9182:         }
 9183:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9184:         $grouplist = join(':',@usersgroups);
 9185:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9186:     }
 9187:     return @usersgroups;
 9188: }
 9189: 
 9190: sub devalidate_getgroups_cache {
 9191:     my ($udom,$uname,$cdom,$cnum)=@_;
 9192:     my $courseid = $cdom.'_'.$cnum;
 9193: 
 9194:     my $hashid="$udom:$uname:$courseid";
 9195:     &devalidate_cache_new('getgroups',$hashid);
 9196: }
 9197: 
 9198: # ------------------------------------------------------------------ Plain Text
 9199: 
 9200: sub plaintext {
 9201:     my ($short,$type,$cid,$forcedefault) = @_;
 9202:     if ($short =~ m{^cr/}) {
 9203: 	return (split('/',$short))[-1];
 9204:     }
 9205:     if (!defined($cid)) {
 9206:         $cid = $env{'request.course.id'};
 9207:     }
 9208:     my %rolenames = (
 9209:                       Course    => 'std',
 9210:                       Community => 'alt1',
 9211:                       Placement => 'std',
 9212:                     );
 9213:     if ($cid ne '') {
 9214:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9215:             unless ($forcedefault) {
 9216:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9217:                 &Apache::lonlocal::mt_escape(\$roletext);
 9218:                 return &Apache::lonlocal::mt($roletext);
 9219:             }
 9220:         }
 9221:     }
 9222:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9223:         (defined($rolenames{$type})) && 
 9224:         (defined($prp{$short}{$rolenames{$type}}))) {
 9225:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9226:     } elsif ($cid ne '') {
 9227:         my $crstype = $env{'course.'.$cid.'.type'};
 9228:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9229:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9230:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9231:         }
 9232:     }
 9233:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9234: }
 9235: 
 9236: # ----------------------------------------------------------------- Assign Role
 9237: 
 9238: sub assignrole {
 9239:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9240:         $context)=@_;
 9241:     my $mrole;
 9242:     if ($role =~ /^cr\//) {
 9243:         my $cwosec=$url;
 9244:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9245: 	unless (&allowed('ccr',$cwosec)) {
 9246:            my $refused = 1;
 9247:            if ($context eq 'requestcourses') {
 9248:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9249:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9250:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9251:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9252:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9253:                            if ($crsenv{'internal.courseowner'} eq
 9254:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9255:                                $refused = '';
 9256:                            }
 9257:                        }
 9258:                    }
 9259:                }
 9260:            }
 9261:            if ($refused) {
 9262:                &logthis('Refused custom assignrole: '.
 9263:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9264:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9265:                return 'refused';
 9266:            }
 9267:         }
 9268:         $mrole='cr';
 9269:     } elsif ($role =~ /^gr\//) {
 9270:         my $cwogrp=$url;
 9271:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9272:         unless (&allowed('mdg',$cwogrp)) {
 9273:             &logthis('Refused group assignrole: '.
 9274:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9275:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9276:             return 'refused';
 9277:         }
 9278:         $mrole='gr';
 9279:     } else {
 9280:         my $cwosec=$url;
 9281:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9282:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9283:             my $refused;
 9284:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9285:                 if (!(&allowed('c'.$role,$url))) {
 9286:                     $refused = 1;
 9287:                 }
 9288:             } else {
 9289:                 $refused = 1;
 9290:             }
 9291:             if ($refused) {
 9292:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9293:                 if (!$selfenroll && $context eq 'course') {
 9294:                     my %crsenv;
 9295:                     if ($role eq 'cc' || $role eq 'co') {
 9296:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9297:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9298:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9299:                                 if ($crsenv{'internal.courseowner'} eq 
 9300:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9301:                                     $refused = '';
 9302:                                 }
 9303:                             }
 9304:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9305:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9306:                                 if ($crsenv{'internal.courseowner'} eq 
 9307:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9308:                                     $refused = '';
 9309:                                 }
 9310:                             }
 9311:                         }
 9312:                     }
 9313:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9314:                     if ($role eq 'st') {
 9315:                         $refused = '';
 9316:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti'})) {
 9317:                         $refused = '';
 9318:                     }
 9319:                 } elsif ($context eq 'requestcourses') {
 9320:                     my @possroles = ('st','ta','ep','in','cc','co');
 9321:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9322:                         my $wrongcc;
 9323:                         if ($cnum =~ /^$match_community$/) {
 9324:                             $wrongcc = 1 if ($role eq 'cc');
 9325:                         } else {
 9326:                             $wrongcc = 1 if ($role eq 'co');
 9327:                         }
 9328:                         unless ($wrongcc) {
 9329:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9330:                             if ($crsenv{'internal.courseowner'} eq 
 9331:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9332:                                 $refused = '';
 9333:                             }
 9334:                         }
 9335:                     }
 9336:                 } elsif ($context eq 'requestauthor') {
 9337:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9338:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9339:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9340:                             $refused = '';
 9341:                         } else {
 9342:                             my %domdefaults = &get_domain_defaults($udom);
 9343:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9344:                                 my $checkbystatus;
 9345:                                 if ($env{'user.adv'}) { 
 9346:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9347:                                     if ($disposition eq 'automatic') {
 9348:                                         $refused = '';
 9349:                                     } elsif ($disposition eq '') {
 9350:                                         $checkbystatus = 1;
 9351:                                     } 
 9352:                                 } else {
 9353:                                     $checkbystatus = 1;
 9354:                                 }
 9355:                                 if ($checkbystatus) {
 9356:                                     if ($env{'environment.inststatus'}) {
 9357:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9358:                                         foreach my $type (@inststatuses) {
 9359:                                             if (($type ne '') &&
 9360:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9361:                                                 $refused = '';
 9362:                                             }
 9363:                                         }
 9364:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9365:                                         $refused = '';
 9366:                                     }
 9367:                                 }
 9368:                             }
 9369:                         }
 9370:                     }
 9371:                 }
 9372:                 if ($refused) {
 9373:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9374:                              ' '.$role.' '.$end.' '.$start.' by '.
 9375: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9376:                     return 'refused';
 9377:                 }
 9378:             }
 9379:         } elsif ($role eq 'au') {
 9380:             if ($url ne '/'.$udom.'/') {
 9381:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9382:                          ' to assign author role for '.$uname.':'.$udom.
 9383:                          ' in domain: '.$url.' refused (wrong domain).');
 9384:                 return 'refused';
 9385:             }
 9386:         }
 9387:         $mrole=$role;
 9388:     }
 9389:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9390:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9391:     if ($end) { $command.='_'.$end; }
 9392:     if ($start) {
 9393: 	if ($end) { 
 9394:            $command.='_'.$start; 
 9395:         } else {
 9396:            $command.='_0_'.$start;
 9397:         }
 9398:     }
 9399:     my $origstart = $start;
 9400:     my $origend = $end;
 9401:     my $delflag;
 9402: # actually delete
 9403:     if ($deleteflag) {
 9404: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9405: # modify command to delete the role
 9406:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9407:                 "$udom:$uname:$url".'_'."$mrole";
 9408: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9409: # set start and finish to negative values for userrolelog
 9410:            $start=-1;
 9411:            $end=-1;
 9412:            $delflag = 1;
 9413:         }
 9414:     }
 9415: # send command
 9416:     my $answer=&reply($command,&homeserver($uname,$udom));
 9417: # log new user role if status is ok
 9418:     if ($answer eq 'ok') {
 9419: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9420:         if (($role eq 'cc') || ($role eq 'in') ||
 9421:             ($role eq 'ep') || ($role eq 'ad') ||
 9422:             ($role eq 'ta') || ($role eq 'st') ||
 9423:             ($role=~/^cr/) || ($role eq 'gr') ||
 9424:             ($role eq 'co')) {
 9425: # for course roles, perform group memberships changes triggered by role change.
 9426:             unless ($role =~ /^gr/) {
 9427:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9428:                                                  $origstart,$selfenroll,$context);
 9429:             }
 9430:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9431:                            $selfenroll,$context);
 9432:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9433:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9434:                  ($role eq 'da')) {
 9435:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9436:                            $context);
 9437:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9438:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9439:                              $context); 
 9440:         }
 9441:         if ($role eq 'cc') {
 9442:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9443:         }
 9444:     }
 9445:     return $answer;
 9446: }
 9447: 
 9448: sub autoupdate_coowners {
 9449:     my ($url,$end,$start,$uname,$udom) = @_;
 9450:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9451:     if (($cdom ne '') && ($cnum ne '')) {
 9452:         my $now = time;
 9453:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9454:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9455:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9456:             my $instcode = $coursehash{'internal.coursecode'};
 9457:             if ($instcode ne '') {
 9458:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9459:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9460:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9461:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9462:                         if ($result eq 'valid') {
 9463:                             if ($coursehash{'internal.co-owners'}) {
 9464:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9465:                                     push(@newcoowners,$coowner);
 9466:                                 }
 9467:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9468:                                     push(@newcoowners,$uname.':'.$udom);
 9469:                                 }
 9470:                                 @newcoowners = sort(@newcoowners);
 9471:                             } else {
 9472:                                 push(@newcoowners,$uname.':'.$udom);
 9473:                             }
 9474:                         } else {
 9475:                             if ($coursehash{'internal.co-owners'}) {
 9476:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9477:                                     unless ($coowner eq $uname.':'.$udom) {
 9478:                                         push(@newcoowners,$coowner);
 9479:                                     }
 9480:                                 }
 9481:                                 unless (@newcoowners > 0) {
 9482:                                     $delcoowners = 1;
 9483:                                     $coowners = '';
 9484:                                 }
 9485:                             }
 9486:                         }
 9487:                         if (@newcoowners || $delcoowners) {
 9488:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9489:                                             $delcoowners,@newcoowners);
 9490:                         }
 9491:                     }
 9492:                 }
 9493:             }
 9494:         }
 9495:     }
 9496: }
 9497: 
 9498: sub store_coowners {
 9499:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9500:     my $cid = $cdom.'_'.$cnum;
 9501:     my ($coowners,$delresult,$putresult);
 9502:     if (@newcoowners) {
 9503:         $coowners = join(',',@newcoowners);
 9504:         my %coownershash = (
 9505:                             'internal.co-owners' => $coowners,
 9506:                            );
 9507:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9508:         if ($putresult eq 'ok') {
 9509:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9510:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9511:             }
 9512:         }
 9513:     }
 9514:     if ($delcoowners) {
 9515:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9516:         if ($delresult eq 'ok') {
 9517:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9518:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9519:             }
 9520:         }
 9521:     }
 9522:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9523:         my %crsinfo =
 9524:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9525:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9526:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9527:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9528:         }
 9529:     }
 9530: }
 9531: 
 9532: # -------------------------------------------------- Modify user authentication
 9533: # Overrides without validation
 9534: 
 9535: sub modifyuserauth {
 9536:     my ($udom,$uname,$umode,$upass)=@_;
 9537:     my $uhome=&homeserver($uname,$udom);
 9538:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9539:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9540:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9541:              ' in domain '.$env{'request.role.domain'});  
 9542:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9543: 		     &escape($upass),$uhome);
 9544:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9545:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9546:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9547:     &log($udom,,$uname,$uhome,
 9548:         'Authentication changed by '.$env{'user.domain'}.', '.
 9549:                                      $env{'user.name'}.', '.$umode.
 9550:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9551:     unless ($reply eq 'ok') {
 9552:         &logthis('Authentication mode error: '.$reply);
 9553: 	return 'error: '.$reply;
 9554:     }   
 9555:     return 'ok';
 9556: }
 9557: 
 9558: # --------------------------------------------------------------- Modify a user
 9559: 
 9560: sub modifyuser {
 9561:     my ($udom,    $uname, $uid,
 9562:         $umode,   $upass, $first,
 9563:         $middle,  $last,  $gene,
 9564:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9565:     $udom= &LONCAPA::clean_domain($udom);
 9566:     $uname=&LONCAPA::clean_username($uname);
 9567:     my $showcandelete = 'none';
 9568:     if (ref($candelete) eq 'ARRAY') {
 9569:         if (@{$candelete} > 0) {
 9570:             $showcandelete = join(', ',@{$candelete});
 9571:         }
 9572:     }
 9573:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9574:              $umode.', '.$first.', '.$middle.', '.
 9575: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9576:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9577:                                      ' desiredhome not specified'). 
 9578:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9579:              ' in domain '.$env{'request.role.domain'});
 9580:     my $uhome=&homeserver($uname,$udom,'true');
 9581:     my $newuser;
 9582:     if ($uhome eq 'no_host') {
 9583:         $newuser = 1;
 9584:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
 9585:                 ($umode eq 'lti')) {
 9586:             return 'error: more information needed to create new user';
 9587:         }
 9588:     }
 9589: # ----------------------------------------------------------------- Create User
 9590:     if (($uhome eq 'no_host') && 
 9591: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
 9592:         my $unhome='';
 9593:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9594:             $unhome = $desiredhome;
 9595: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9596: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9597:         } else { # load balancing routine for determining $unhome
 9598:             my $loadm=10000000;
 9599: 	    my %servers = &get_servers($udom,'library');
 9600: 	    foreach my $tryserver (keys(%servers)) {
 9601: 		my $answer=reply('load',$tryserver);
 9602: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9603: 		    $loadm=$answer;
 9604: 		    $unhome=$tryserver;
 9605: 		}
 9606: 	    }
 9607:         }
 9608:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9609: 	    return 'error: unable to find a home server for '.$uname.
 9610:                    ' in domain '.$udom;
 9611:         }
 9612:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9613:                          &escape($upass),$unhome);
 9614: 	unless ($reply eq 'ok') {
 9615:             return 'error: '.$reply;
 9616:         }   
 9617:         $uhome=&homeserver($uname,$udom,'true');
 9618:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9619: 	    return 'error: unable verify users home machine.';
 9620:         }
 9621:     }   # End of creation of new user
 9622: # ---------------------------------------------------------------------- Add ID
 9623:     if ($uid) {
 9624:        $uid=~tr/A-Z/a-z/;
 9625:        my %uidhash=&idrget($udom,$uname);
 9626:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9627:          && (!$forceid)) {
 9628: 	  unless ($uid eq $uidhash{$uname}) {
 9629: 	      return 'error: user id "'.$uid.'" does not match '.
 9630:                   'current user id "'.$uidhash{$uname}.'".';
 9631:           }
 9632:        } else {
 9633: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9634:        }
 9635:     }
 9636: # -------------------------------------------------------------- Add names, etc
 9637:     my @tmp=&get('environment',
 9638: 		   ['firstname','middlename','lastname','generation','id',
 9639:                     'permanentemail','inststatus'],
 9640: 		   $udom,$uname);
 9641:     my (%names,%oldnames);
 9642:     if ($tmp[0] =~ m/^error:.*/) { 
 9643:         %names=(); 
 9644:     } else {
 9645:         %names = @tmp;
 9646:         %oldnames = %names;
 9647:     }
 9648: #
 9649: # If name, email and/or uid are blank (e.g., because an uploaded file
 9650: # of users did not contain them), do not overwrite existing values
 9651: # unless field is in $candelete array ref.  
 9652: #
 9653: 
 9654:     my @fields = ('firstname','middlename','lastname','generation',
 9655:                   'permanentemail','id');
 9656:     my %newvalues;
 9657:     if (ref($candelete) eq 'ARRAY') {
 9658:         foreach my $field (@fields) {
 9659:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9660:                 if ($field eq 'firstname') {
 9661:                     $names{$field} = $first;
 9662:                 } elsif ($field eq 'middlename') {
 9663:                     $names{$field} = $middle;
 9664:                 } elsif ($field eq 'lastname') {
 9665:                     $names{$field} = $last;
 9666:                 } elsif ($field eq 'generation') { 
 9667:                     $names{$field} = $gene;
 9668:                 } elsif ($field eq 'permanentemail') {
 9669:                     $names{$field} = $email;
 9670:                 } elsif ($field eq 'id') {
 9671:                     $names{$field}  = $uid;
 9672:                 }
 9673:             }
 9674:         }
 9675:     }
 9676:     if ($first)  { $names{'firstname'}  = $first; }
 9677:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9678:     if ($last)   { $names{'lastname'}   = $last; }
 9679:     if (defined($gene))   { $names{'generation'} = $gene; }
 9680:     if ($email) {
 9681:        $email=~s/[^\w\@\.\-\,]//gs;
 9682:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9683:     }
 9684:     if ($uid) { $names{'id'}  = $uid; }
 9685:     if (defined($inststatus)) {
 9686:         $names{'inststatus'} = '';
 9687:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9688:         if (ref($usertypes) eq 'HASH') {
 9689:             my @okstatuses; 
 9690:             foreach my $item (split(/:/,$inststatus)) {
 9691:                 if (defined($usertypes->{$item})) {
 9692:                     push(@okstatuses,$item);  
 9693:                 }
 9694:             }
 9695:             if (@okstatuses) {
 9696:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9697:             }
 9698:         }
 9699:     }
 9700:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9701:                  $umode.', '.$first.', '.$middle.', '.
 9702:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9703:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9704:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9705:     } else {
 9706:         $logmsg .= ' during self creation';
 9707:     }
 9708:     my $changed;
 9709:     if ($newuser) {
 9710:         $changed = 1;
 9711:     } else {
 9712:         foreach my $field (@fields) {
 9713:             if ($names{$field} ne $oldnames{$field}) {
 9714:                 $changed = 1;
 9715:                 last;
 9716:             }
 9717:         }
 9718:     }
 9719:     unless ($changed) {
 9720:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9721:         &logthis($logmsg);
 9722:         return 'ok';
 9723:     }
 9724:     my $reply = &put('environment', \%names, $udom,$uname);
 9725:     if ($reply ne 'ok') { 
 9726:         return 'error: '.$reply;
 9727:     }
 9728:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9729:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9730:     }
 9731:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9732:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9733:     $logmsg = 'Success modifying user '.$logmsg;
 9734:     &logthis($logmsg);
 9735:     return 'ok';
 9736: }
 9737: 
 9738: # -------------------------------------------------------------- Modify student
 9739: 
 9740: sub modifystudent {
 9741:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9742:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9743:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9744:     if (!$cid) {
 9745: 	unless ($cid=$env{'request.course.id'}) {
 9746: 	    return 'not_in_class';
 9747: 	}
 9748:     }
 9749: # --------------------------------------------------------------- Make the user
 9750:     my $reply=&modifyuser
 9751: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9752:          $desiredhome,$email,$inststatus);
 9753:     unless ($reply eq 'ok') { return $reply; }
 9754:     # This will cause &modify_student_enrollment to get the uid from the
 9755:     # student's environment
 9756:     $uid = undef if (!$forceid);
 9757:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9758:                                         $gene,$usec,$end,$start,$type,$locktype,
 9759:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9760:     return $reply;
 9761: }
 9762: 
 9763: sub modify_student_enrollment {
 9764:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9765:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9766:     my ($cdom,$cnum,$chome);
 9767:     if (!$cid) {
 9768: 	unless ($cid=$env{'request.course.id'}) {
 9769: 	    return 'not_in_class';
 9770: 	}
 9771: 	$cdom=$env{'course.'.$cid.'.domain'};
 9772: 	$cnum=$env{'course.'.$cid.'.num'};
 9773:     } else {
 9774: 	($cdom,$cnum)=split(/_/,$cid);
 9775:     }
 9776:     $chome=$env{'course.'.$cid.'.home'};
 9777:     if (!$chome) {
 9778: 	$chome=&homeserver($cnum,$cdom);
 9779:     }
 9780:     if (!$chome) { return 'unknown_course'; }
 9781:     # Make sure the user exists
 9782:     my $uhome=&homeserver($uname,$udom);
 9783:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9784: 	return 'error: no such user';
 9785:     }
 9786:     # Get student data if we were not given enough information
 9787:     if (!defined($first)  || $first  eq '' || 
 9788:         !defined($last)   || $last   eq '' || 
 9789:         !defined($uid)    || $uid    eq '' || 
 9790:         !defined($middle) || $middle eq '' || 
 9791:         !defined($gene)   || $gene   eq '') {
 9792:         # They did not supply us with enough data to enroll the student, so
 9793:         # we need to pick up more information.
 9794:         my %tmp = &get('environment',
 9795:                        ['firstname','middlename','lastname', 'generation','id']
 9796:                        ,$udom,$uname);
 9797: 
 9798:         #foreach my $key (keys(%tmp)) {
 9799:         #    &logthis("key $key = ".$tmp{$key});
 9800:         #}
 9801:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9802:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9803:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9804:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9805:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9806:     }
 9807:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9808:     my $user = "$uname:$udom";
 9809:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9810:     my $reply=cput('classlist',
 9811: 		   {$user => 
 9812: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9813: 		   $cdom,$cnum);
 9814:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9815:         &devalidate_getsection_cache($udom,$uname,$cid);
 9816:     } else { 
 9817: 	return 'error: '.$reply;
 9818:     }
 9819:     # Add student role to user
 9820:     my $uurl='/'.$cid;
 9821:     $uurl=~s/\_/\//g;
 9822:     if ($usec) {
 9823: 	$uurl.='/'.$usec;
 9824:     }
 9825:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9826:                              $selfenroll,$context);
 9827:     if ($result ne 'ok') {
 9828:         if ($old_entry{$user} ne '') {
 9829:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9830:         } else {
 9831:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9832:         }
 9833:     }
 9834:     return $result; 
 9835: }
 9836: 
 9837: sub format_name {
 9838:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9839:     my $name;
 9840:     if ($first ne 'lastname') {
 9841: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9842:     } else {
 9843: 	if ($lastname=~/\S/) {
 9844: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9845: 	    $name=~s/\s+,/,/;
 9846: 	} else {
 9847: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9848: 	}
 9849:     }
 9850:     $name=~s/^\s+//;
 9851:     $name=~s/\s+$//;
 9852:     $name=~s/\s+/ /g;
 9853:     return $name;
 9854: }
 9855: 
 9856: # ------------------------------------------------- Write to course preferences
 9857: 
 9858: sub writecoursepref {
 9859:     my ($courseid,%prefs)=@_;
 9860:     $courseid=~s/^\///;
 9861:     $courseid=~s/\_/\//g;
 9862:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9863:     my $chome=homeserver($cnum,$cdomain);
 9864:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9865: 	return 'error: no such course';
 9866:     }
 9867:     my $cstring='';
 9868:     foreach my $pref (keys(%prefs)) {
 9869: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9870:     }
 9871:     $cstring=~s/\&$//;
 9872:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9873: }
 9874: 
 9875: # ---------------------------------------------------------- Make/modify course
 9876: 
 9877: sub createcourse {
 9878:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9879:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9880:     $url=&declutter($url);
 9881:     my $cid='';
 9882:     if ($context eq 'requestcourses') {
 9883:         my $can_create = 0;
 9884:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9885:         if ($udom eq $ownerdom) {
 9886:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9887:                                   $context)) {
 9888:                 $can_create = 1;
 9889:             }
 9890:         } else {
 9891:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9892:                                            $category);
 9893:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9894:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9895:                 if (@curr > 0) {
 9896:                     my @options = qw(approval validate autolimit);
 9897:                     my $optregex = join('|',@options);
 9898:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9899:                         $can_create = 1;
 9900:                     }
 9901:                 }
 9902:             }
 9903:         }
 9904:         if ($can_create) {
 9905:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 9906:                 unless (&allowed('ccc',$udom)) {
 9907:                     return 'refused'; 
 9908:                 }
 9909:             }
 9910:         } else {
 9911:             return 'refused';
 9912:         }
 9913:     } elsif (!&allowed('ccc',$udom)) {
 9914:         return 'refused';
 9915:     }
 9916: # --------------------------------------------------------------- Get Unique ID
 9917:     my $uname;
 9918:     if ($cnum =~ /^$match_courseid$/) {
 9919:         my $chome=&homeserver($cnum,$udom,'true');
 9920:         if (($chome eq '') || ($chome eq 'no_host')) {
 9921:             $uname = $cnum;
 9922:         } else {
 9923:             $uname = &generate_coursenum($udom,$crstype);
 9924:         }
 9925:     } else {
 9926:         $uname = &generate_coursenum($udom,$crstype);
 9927:     }
 9928:     return $uname if ($uname =~ /^error/);
 9929: # -------------------------------------------------- Check supplied server name
 9930:     if (!defined($course_server)) {
 9931:         if (defined(&domain($udom,'primary'))) {
 9932:             $course_server = &domain($udom,'primary');
 9933:         } else {
 9934:             $course_server = $env{'user.home'}; 
 9935:         }
 9936:     }
 9937:     my %host_servers =
 9938:         &Apache::lonnet::get_servers($udom,'library');
 9939:     unless ($host_servers{$course_server}) {
 9940:         return 'error: invalid home server for course: '.$course_server;
 9941:     }
 9942: # ------------------------------------------------------------- Make the course
 9943:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 9944:                       $course_server);
 9945:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 9946:     my $uhome=&homeserver($uname,$udom,'true');
 9947:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9948: 	return 'error: no such course';
 9949:     }
 9950: # ----------------------------------------------------------------- Course made
 9951: # log existence
 9952:     my $now = time;
 9953:     my $newcourse = {
 9954:                     $udom.'_'.$uname => {
 9955:                                      description => $description,
 9956:                                      inst_code   => $inst_code,
 9957:                                      owner       => $course_owner,
 9958:                                      type        => $crstype,
 9959:                                      creator     => $env{'user.name'}.':'.
 9960:                                                     $env{'user.domain'},
 9961:                                      created     => $now,
 9962:                                      context     => $context,
 9963:                                                 },
 9964:                     };
 9965:     &courseidput($udom,$newcourse,$uhome,'notime');
 9966: # set toplevel url
 9967:     my $topurl=$url;
 9968:     unless ($nonstandard) {
 9969: # ------------------------------------------ For standard courses, make top url
 9970:         my $mapurl=&clutter($url);
 9971:         if ($mapurl eq '/res/') { $mapurl=''; }
 9972:         $env{'form.initmap'}=(<<ENDINITMAP);
 9973: <map>
 9974: <resource id="1" type="start"></resource>
 9975: <resource id="2" src="$mapurl"></resource>
 9976: <resource id="3" type="finish"></resource>
 9977: <link index="1" from="1" to="2"></link>
 9978: <link index="2" from="2" to="3"></link>
 9979: </map>
 9980: ENDINITMAP
 9981:         $topurl=&declutter(
 9982:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 9983:                           );
 9984:     }
 9985: # ----------------------------------------------------------- Write preferences
 9986:     &writecoursepref($udom.'_'.$uname,
 9987:                      ('description'              => $description,
 9988:                       'url'                      => $topurl,
 9989:                       'internal.creator'         => $env{'user.name'}.':'.
 9990:                                                     $env{'user.domain'},
 9991:                       'internal.created'         => $now,
 9992:                       'internal.creationcontext' => $context)
 9993:                     );
 9994:     return '/'.$udom.'/'.$uname;
 9995: }
 9996: 
 9997: # ------------------------------------------------------------------- Create ID
 9998: sub generate_coursenum {
 9999:     my ($udom,$crstype) = @_;
10000:     my $domdesc = &domain($udom);
10001:     return 'error: invalid domain' if ($domdesc eq '');
10002:     my $first;
10003:     if ($crstype eq 'Community') {
10004:         $first = '0';
10005:     } else {
10006:         $first = int(1+rand(9)); 
10007:     } 
10008:     my $uname=$first.
10009:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10010:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10011:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10012: # ----------------------------------------------- Make sure that does not exist
10013:     my $uhome=&homeserver($uname,$udom,'true');
10014:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10015:         if ($crstype eq 'Community') {
10016:             $first = '0';
10017:         } else {
10018:             $first = int(1+rand(9));
10019:         }
10020:         $uname=$first.
10021:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10022:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10023:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10024:         $uhome=&homeserver($uname,$udom,'true');
10025:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10026:             return 'error: unable to generate unique course-ID';
10027:         }
10028:     }
10029:     return $uname;
10030: }
10031: 
10032: sub is_course {
10033:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10034:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10035: 
10036:     return unless $cdom and $cnum;
10037: 
10038:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
10039:         '.');
10040: 
10041:     return unless(exists($courses{$cdom.'_'.$cnum}));
10042:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10043: }
10044: 
10045: sub store_userdata {
10046:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10047:     my $result;
10048:     if ($datakey ne '') {
10049:         if (ref($storehash) eq 'HASH') {
10050:             if ($udom eq '' || $uname eq '') {
10051:                 $udom = $env{'user.domain'};
10052:                 $uname = $env{'user.name'};
10053:             }
10054:             my $uhome=&homeserver($uname,$udom);
10055:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10056:                 $result = 'error: no_host';
10057:             } else {
10058:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10059:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10060: 
10061:                 my $namevalue='';
10062:                 foreach my $key (keys(%{$storehash})) {
10063:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10064:                 }
10065:                 $namevalue=~s/\&$//;
10066:                 unless ($namespace eq 'courserequests') {
10067:                     $datakey = &escape($datakey);
10068:                 }
10069:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10070:                                   $namevalue,$uhome);
10071:             }
10072:         } else {
10073:             $result = 'error: data to store was not a hash reference'; 
10074:         }
10075:     } else {
10076:         $result= 'error: invalid requestkey'; 
10077:     }
10078:     return $result;
10079: }
10080: 
10081: # ---------------------------------------------------------- Assign Custom Role
10082: 
10083: sub assigncustomrole {
10084:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10085:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10086:                        $end,$start,$deleteflag,$selfenroll,$context);
10087: }
10088: 
10089: # ----------------------------------------------------------------- Revoke Role
10090: 
10091: sub revokerole {
10092:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10093:     my $now=time;
10094:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10095: }
10096: 
10097: # ---------------------------------------------------------- Revoke Custom Role
10098: 
10099: sub revokecustomrole {
10100:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10101:     my $now=time;
10102:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10103:            $deleteflag,$selfenroll,$context);
10104: }
10105: 
10106: # ------------------------------------------------------------ Disk usage
10107: sub diskusage {
10108:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10109:     $directorypath =~ s/\/$//;
10110:     my $listing=&reply('du2:'.&escape($directorypath).':'
10111:                        .&escape($getpropath).':'.&escape($uname).':'
10112:                        .&escape($udom),homeserver($uname,$udom));
10113:     if ($listing eq 'unknown_cmd') {
10114:         if ($getpropath) {
10115:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10116:         }
10117:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10118:     }
10119:     return $listing;
10120: }
10121: 
10122: sub is_locked {
10123:     my ($file_name, $domain, $user, $which) = @_;
10124:     my @check;
10125:     my $is_locked;
10126:     push (@check,$file_name);
10127:     my %locked = &get('file_permissions',\@check,
10128: 		      $env{'user.domain'},$env{'user.name'});
10129:     my ($tmp)=keys(%locked);
10130:     if ($tmp=~/^error:/) { undef(%locked); }
10131:     
10132:     if (ref($locked{$file_name}) eq 'ARRAY') {
10133:         $is_locked = 'false';
10134:         foreach my $entry (@{$locked{$file_name}}) {
10135:            if (ref($entry) eq 'ARRAY') {
10136:                $is_locked = 'true';
10137:                if (ref($which) eq 'ARRAY') {
10138:                    push(@{$which},$entry);
10139:                } else {
10140:                    last;
10141:                }
10142:            }
10143:        }
10144:     } else {
10145:         $is_locked = 'false';
10146:     }
10147:     return $is_locked;
10148: }
10149: 
10150: sub declutter_portfile {
10151:     my ($file) = @_;
10152:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10153:     return $file;
10154: }
10155: 
10156: # ------------------------------------------------------------- Mark as Read Only
10157: 
10158: sub mark_as_readonly {
10159:     my ($domain,$user,$files,$what) = @_;
10160:     my %current_permissions = &dump('file_permissions',$domain,$user);
10161:     my ($tmp)=keys(%current_permissions);
10162:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10163:     foreach my $file (@{$files}) {
10164: 	$file = &declutter_portfile($file);
10165:         push(@{$current_permissions{$file}},$what);
10166:     }
10167:     &put('file_permissions',\%current_permissions,$domain,$user);
10168:     return;
10169: }
10170: 
10171: # ------------------------------------------------------------Save Selected Files
10172: 
10173: sub save_selected_files {
10174:     my ($user, $path, @files) = @_;
10175:     my $filename = $user."savedfiles";
10176:     my @other_files = &files_not_in_path($user, $path);
10177:     open (OUT,'>',LONCAPA::tempdir().$filename);
10178:     foreach my $file (@files) {
10179:         print (OUT $env{'form.currentpath'}.$file."\n");
10180:     }
10181:     foreach my $file (@other_files) {
10182:         print (OUT $file."\n");
10183:     }
10184:     close (OUT);
10185:     return 'ok';
10186: }
10187: 
10188: sub clear_selected_files {
10189:     my ($user) = @_;
10190:     my $filename = $user."savedfiles";
10191:     open (OUT,'>',LONCAPA::tempdir().$filename);
10192:     print (OUT undef);
10193:     close (OUT);
10194:     return ("ok");    
10195: }
10196: 
10197: sub files_in_path {
10198:     my ($user, $path) = @_;
10199:     my $filename = $user."savedfiles";
10200:     my %return_files;
10201:     open (IN,'<',LONCAPA::tempdir().$filename);
10202:     while (my $line_in = <IN>) {
10203:         chomp ($line_in);
10204:         my @paths_and_file = split (m!/!, $line_in);
10205:         my $file_part = pop (@paths_and_file);
10206:         my $path_part = join ('/', @paths_and_file);
10207:         $path_part.='/';
10208:         my $path_and_file = $path_part.$file_part;
10209:         if ($path_part eq $path) {
10210:             $return_files{$file_part}= 'selected';
10211:         }
10212:     }
10213:     close (IN);
10214:     return (\%return_files);
10215: }
10216: 
10217: # called in portfolio select mode, to show files selected NOT in current directory
10218: sub files_not_in_path {
10219:     my ($user, $path) = @_;
10220:     my $filename = $user."savedfiles";
10221:     my @return_files;
10222:     my $path_part;
10223:     open(IN, '<',LONCAPA::tempdir().$filename);
10224:     while (my $line = <IN>) {
10225:         #ok, I know it's clunky, but I want it to work
10226:         my @paths_and_file = split(m|/|, $line);
10227:         my $file_part = pop(@paths_and_file);
10228:         chomp($file_part);
10229:         my $path_part = join('/', @paths_and_file);
10230:         $path_part .= '/';
10231:         my $path_and_file = $path_part.$file_part;
10232:         if ($path_part ne $path) {
10233:             push(@return_files, ($path_and_file));
10234:         }
10235:     }
10236:     close(OUT);
10237:     return (@return_files);
10238: }
10239: 
10240: #------------------------------Submitted/Handedback Portfolio Files Versioning
10241:  
10242: sub portfiles_versioning {
10243:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10244:     my $portfolio_root = '/userfiles/portfolio';
10245:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10246:     foreach my $file (@{$portfiles}) {
10247:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10248:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10249:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10250:         my $getpropath = 1;
10251:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10252:                                              $stu_name,$getpropath);
10253:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10254:         my $new_answer = 
10255:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10256:         if ($new_answer ne 'problem getting file') {
10257:             push(@{$versioned_portfiles}, $directory.$new_answer);
10258:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10259:                               [$symb,$env{'request.course.id'},'graded']);
10260:         }
10261:     }
10262: }
10263: 
10264: sub get_next_version {
10265:     my ($answer_name, $answer_ext, $dir_list) = @_;
10266:     my $version;
10267:     if (ref($dir_list) eq 'ARRAY') {
10268:         foreach my $row (@{$dir_list}) {
10269:             my ($file) = split(/\&/,$row,2);
10270:             my ($file_name,$file_version,$file_ext) =
10271:                 &file_name_version_ext($file);
10272:             if (($file_name eq $answer_name) &&
10273:                 ($file_ext eq $answer_ext)) {
10274:                      # gets here if filename and extension match,
10275:                      # regardless of version
10276:                 if ($file_version ne '') {
10277:                     # a versioned file is found  so save it for later
10278:                     if ($file_version > $version) {
10279:                         $version = $file_version;
10280:                     }
10281:                 }
10282:             }
10283:         }
10284:     }
10285:     $version ++;
10286:     return($version);
10287: }
10288: 
10289: sub version_selected_portfile {
10290:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10291:     my ($answer_name,$answer_ver,$answer_ext) =
10292:         &file_name_version_ext($file_name);
10293:     my $new_answer;
10294:     $env{'form.copy'} =
10295:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10296:     if($env{'form.copy'} eq '-1') {
10297:         $new_answer = 'problem getting file';
10298:     } else {
10299:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10300:         my $copy_result = 
10301:             &finishuserfileupload($stu_name,$domain,'copy',
10302:                                   '/portfolio'.$directory.$new_answer);
10303:     }
10304:     undef($env{'form.copy'});
10305:     return ($new_answer);
10306: }
10307: 
10308: sub file_name_version_ext {
10309:     my ($file)=@_;
10310:     my @file_parts = split(/\./, $file);
10311:     my ($name,$version,$ext);
10312:     if (@file_parts > 1) {
10313:         $ext=pop(@file_parts);
10314:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10315:             $version=pop(@file_parts);
10316:         }
10317:         $name=join('.',@file_parts);
10318:     } else {
10319:         $name=join('.',@file_parts);
10320:     }
10321:     return($name,$version,$ext);
10322: }
10323: 
10324: #----------------------------------------------Get portfolio file permissions
10325: 
10326: sub get_portfile_permissions {
10327:     my ($domain,$user) = @_;
10328:     my %current_permissions = &dump('file_permissions',$domain,$user);
10329:     my ($tmp)=keys(%current_permissions);
10330:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10331:     return \%current_permissions;
10332: }
10333: 
10334: #---------------------------------------------Get portfolio file access controls
10335: 
10336: sub get_access_controls {
10337:     my ($current_permissions,$group,$file) = @_;
10338:     my %access;
10339:     my $real_file = $file;
10340:     $file =~ s/\.meta$//;
10341:     if (defined($file)) {
10342:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10343:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10344:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10345:             }
10346:         }
10347:     } else {
10348:         foreach my $key (keys(%{$current_permissions})) {
10349:             if ($key =~ /\0accesscontrol$/) {
10350:                 if (defined($group)) {
10351:                     if ($key !~ m-^\Q$group\E/-) {
10352:                         next;
10353:                     }
10354:                 }
10355:                 my ($fullpath) = split(/\0/,$key);
10356:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10357:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10358:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10359:                     }
10360:                 }
10361:             }
10362:         }
10363:     }
10364:     return %access;
10365: }
10366: 
10367: sub modify_access_controls {
10368:     my ($file_name,$changes,$domain,$user)=@_;
10369:     my ($outcome,$deloutcome);
10370:     my %store_permissions;
10371:     my %new_values;
10372:     my %new_control;
10373:     my %translation;
10374:     my @deletions = ();
10375:     my $now = time;
10376:     if (exists($$changes{'activate'})) {
10377:         if (ref($$changes{'activate'}) eq 'HASH') {
10378:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10379:             my $numnew = scalar(@newitems);
10380:             for (my $i=0; $i<$numnew; $i++) {
10381:                 my $newkey = $newitems[$i];
10382:                 my $newid = &Apache::loncommon::get_cgi_id();
10383:                 if ($newkey =~ /^\d+:/) { 
10384:                     $newkey =~ s/^(\d+)/$newid/;
10385:                     $translation{$1} = $newid;
10386:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10387:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10388:                     $translation{$1} = $newid;
10389:                 }
10390:                 $new_values{$file_name."\0".$newkey} = 
10391:                                           $$changes{'activate'}{$newitems[$i]};
10392:                 $new_control{$newkey} = $now;
10393:             }
10394:         }
10395:     }
10396:     my %todelete;
10397:     my %changed_items;
10398:     foreach my $action ('delete','update') {
10399:         if (exists($$changes{$action})) {
10400:             if (ref($$changes{$action}) eq 'HASH') {
10401:                 foreach my $key (keys(%{$$changes{$action}})) {
10402:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10403:                     if ($action eq 'delete') { 
10404:                         $todelete{$itemnum} = 1;
10405:                     } else {
10406:                         $changed_items{$itemnum} = $key;
10407:                     }
10408:                 }
10409:             }
10410:         }
10411:     }
10412:     # get lock on access controls for file.
10413:     my $lockhash = {
10414:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10415:                                                        ':'.$env{'user.domain'},
10416:                    }; 
10417:     my $tries = 0;
10418:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10419:    
10420:     while (($gotlock ne 'ok') && $tries < 10) {
10421:         $tries ++;
10422:         sleep(0.1);
10423:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10424:     }
10425:     if ($gotlock eq 'ok') {
10426:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10427:         my ($tmp)=keys(%curr_permissions);
10428:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10429:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10430:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10431:             if (ref($curr_controls) eq 'HASH') {
10432:                 foreach my $control_item (keys(%{$curr_controls})) {
10433:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10434:                     if (defined($todelete{$itemnum})) {
10435:                         push(@deletions,$file_name."\0".$control_item);
10436:                     } else {
10437:                         if (defined($changed_items{$itemnum})) {
10438:                             $new_control{$changed_items{$itemnum}} = $now;
10439:                             push(@deletions,$file_name."\0".$control_item);
10440:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10441:                         } else {
10442:                             $new_control{$control_item} = $$curr_controls{$control_item};
10443:                         }
10444:                     }
10445:                 }
10446:             }
10447:         }
10448:         my ($group);
10449:         if (&is_course($domain,$user)) {
10450:             ($group,my $file) = split(/\//,$file_name,2);
10451:         }
10452:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10453:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10454:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10455:         #  remove lock
10456:         my @del_lock = ($file_name."\0".'locked_access_records');
10457:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10458:         my $sqlresult =
10459:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10460:                                     $group);
10461:     } else {
10462:         $outcome = "error: could not obtain lockfile\n";  
10463:     }
10464:     return ($outcome,$deloutcome,\%new_values,\%translation);
10465: }
10466: 
10467: sub make_public_indefinitely {
10468:     my (@requrl) = @_;
10469:     return &automated_portfile_access('public',\@requrl);
10470: }
10471: 
10472: sub automated_portfile_access {
10473:     my ($accesstype,$addsref,$delsref,$info) = @_;
10474:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10475:         return 'invalid';
10476:     }
10477:     my %urls;
10478:     if (ref($addsref) eq 'ARRAY') {
10479:         foreach my $requrl (@{$addsref}) {
10480:             if (&is_portfolio_url($requrl)) {
10481:                 unless (exists($urls{$requrl})) {
10482:                     $urls{$requrl} = 'add';
10483:                 }
10484:             }
10485:         }
10486:     }
10487:     if (ref($delsref) eq 'ARRAY') {
10488:         foreach my $requrl (@{$delsref}) { 
10489:             if (&is_portfolio_url($requrl)) {
10490:                 unless (exists($urls{$requrl})) {
10491:                     $urls{$requrl} = 'delete'; 
10492:                 }
10493:             }
10494:         }
10495:     }
10496:     unless (keys(%urls)) {
10497:         return 'invalid';
10498:     }
10499:     my $ip;
10500:     if ($accesstype eq 'ip') {
10501:         if (ref($info) eq 'HASH') {
10502:             if ($info->{'ip'} ne '') {
10503:                 $ip = $info->{'ip'};
10504:             }
10505:         }
10506:         if ($ip eq '') {
10507:             return 'invalid';
10508:         }
10509:     }
10510:     my $errors;
10511:     my $now = time;
10512:     my %current_perms;
10513:     foreach my $requrl (sort(keys(%urls))) {
10514:         my $action;
10515:         if ($urls{$requrl} eq 'add') {
10516:             $action = 'activate';
10517:         } else {
10518:             $action = 'none';
10519:         }
10520:         my $aclnum = 0;
10521:         my (undef,$udom,$unum,$file_name,$group) =
10522:             &parse_portfolio_url($requrl);
10523:         unless (exists($current_perms{$unum.':'.$udom})) {
10524:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10525:         }
10526:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10527:                                                    $group,$file_name);
10528:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10529:             my ($num,$scope,$end,$start) = 
10530:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10531:             if ($scope eq $accesstype) {
10532:                 if (($start <= $now) && ($end == 0)) {
10533:                     if ($accesstype eq 'ip') {
10534:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10535:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10536:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10537:                                     if ($urls{$requrl} eq 'add') {
10538:                                         $action = 'none';
10539:                                         last;
10540:                                     } else {
10541:                                         $action = 'delete';
10542:                                         $aclnum = $num;
10543:                                         last;
10544:                                     }
10545:                                 }
10546:                             }
10547:                         }
10548:                     } elsif ($accesstype eq 'public') {
10549:                         if ($urls{$requrl} eq 'add') {
10550:                             $action = 'none';
10551:                             last;
10552:                         } else {
10553:                             $action = 'delete';
10554:                             $aclnum = $num;
10555:                             last;
10556:                         }
10557:                     }
10558:                 } elsif ($accesstype eq 'public') {
10559:                     $action = 'update';
10560:                     $aclnum = $num;
10561:                     last;
10562:                 }
10563:             }
10564:         }
10565:         if ($action eq 'none') {
10566:             next;
10567:         } else {
10568:             my %changes;
10569:             my $newend = 0;
10570:             my $newstart = $now;
10571:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10572:             $changes{$action}{$newkey} = {
10573:                 type => $accesstype,
10574:                 time => {
10575:                     start => $newstart,
10576:                     end   => $newend,
10577:                 },
10578:             };
10579:             if ($accesstype eq 'ip') {
10580:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10581:             }
10582:             my ($outcome,$deloutcome,$new_values,$translation) =
10583:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10584:             unless ($outcome eq 'ok') {
10585:                 $errors .= $outcome.' ';
10586:             }
10587:         }
10588:     }
10589:     if ($errors) {
10590:         $errors =~ s/\s$//;
10591:         return $errors;
10592:     } else {
10593:         return 'ok';
10594:     }
10595: }
10596: 
10597: #------------------------------------------------------Get Marked as Read Only
10598: 
10599: sub get_marked_as_readonly {
10600:     my ($domain,$user,$what,$group) = @_;
10601:     my $current_permissions = &get_portfile_permissions($domain,$user);
10602:     my @readonly_files;
10603:     my $cmp1=$what;
10604:     if (ref($what)) { $cmp1=join('',@{$what}) };
10605:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10606:         if (defined($group)) {
10607:             if ($file_name !~ m-^\Q$group\E/-) {
10608:                 next;
10609:             }
10610:         }
10611:         if (ref($value) eq "ARRAY"){
10612:             foreach my $stored_what (@{$value}) {
10613:                 my $cmp2=$stored_what;
10614:                 if (ref($stored_what) eq 'ARRAY') {
10615:                     $cmp2=join('',@{$stored_what});
10616:                 }
10617:                 if ($cmp1 eq $cmp2) {
10618:                     push(@readonly_files, $file_name);
10619:                     last;
10620:                 } elsif (!defined($what)) {
10621:                     push(@readonly_files, $file_name);
10622:                     last;
10623:                 }
10624:             }
10625:         }
10626:     }
10627:     return @readonly_files;
10628: }
10629: #-----------------------------------------------------------Get Marked as Read Only Hash
10630: 
10631: sub get_marked_as_readonly_hash {
10632:     my ($current_permissions,$group,$what) = @_;
10633:     my %readonly_files;
10634:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10635:         if (defined($group)) {
10636:             if ($file_name !~ m-^\Q$group\E/-) {
10637:                 next;
10638:             }
10639:         }
10640:         if (ref($value) eq "ARRAY"){
10641:             foreach my $stored_what (@{$value}) {
10642:                 if (ref($stored_what) eq 'ARRAY') {
10643:                     foreach my $lock_descriptor(@{$stored_what}) {
10644:                         if ($lock_descriptor eq 'graded') {
10645:                             $readonly_files{$file_name} = 'graded';
10646:                         } elsif ($lock_descriptor eq 'handback') {
10647:                             $readonly_files{$file_name} = 'handback';
10648:                         } else {
10649:                             if (!exists($readonly_files{$file_name})) {
10650:                                 $readonly_files{$file_name} = 'locked';
10651:                             }
10652:                         }
10653:                     }
10654:                 } 
10655:             }
10656:         } 
10657:     }
10658:     return %readonly_files;
10659: }
10660: # ------------------------------------------------------------ Unmark as Read Only
10661: 
10662: sub unmark_as_readonly {
10663:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10664:     # for portfolio submissions, $what contains [$symb,$crsid] 
10665:     my ($domain,$user,$what,$file_name,$group) = @_;
10666:     $file_name = &declutter_portfile($file_name);
10667:     my $symb_crs = $what;
10668:     if (ref($what)) { $symb_crs=join('',@$what); }
10669:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10670:     my ($tmp)=keys(%current_permissions);
10671:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10672:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10673:     foreach my $file (@readonly_files) {
10674: 	my $clean_file = &declutter_portfile($file);
10675: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10676: 	my $current_locks = $current_permissions{$file};
10677:         my @new_locks;
10678:         my @del_keys;
10679:         if (ref($current_locks) eq "ARRAY"){
10680:             foreach my $locker (@{$current_locks}) {
10681:                 my $compare=$locker;
10682:                 if (ref($locker) eq 'ARRAY') {
10683:                     $compare=join('',@{$locker});
10684:                     if ($compare ne $symb_crs) {
10685:                         push(@new_locks, $locker);
10686:                     }
10687:                 }
10688:             }
10689:             if (scalar(@new_locks) > 0) {
10690:                 $current_permissions{$file} = \@new_locks;
10691:             } else {
10692:                 push(@del_keys, $file);
10693:                 &del('file_permissions',\@del_keys, $domain, $user);
10694:                 delete($current_permissions{$file});
10695:             }
10696:         }
10697:     }
10698:     &put('file_permissions',\%current_permissions,$domain,$user);
10699:     return;
10700: }
10701: 
10702: # ------------------------------------------------------------ Directory lister
10703: 
10704: sub dirlist {
10705:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10706:     $uri=~s/^\///;
10707:     $uri=~s/\/$//;
10708:     my ($udom, $uname);
10709:     if ($getuserdir) {
10710:         $udom = $userdomain;
10711:         $uname = $username;
10712:     } else {
10713:         (undef,$udom,$uname)=split(/\//,$uri);
10714:         if(defined($userdomain)) {
10715:             $udom = $userdomain;
10716:         }
10717:         if(defined($username)) {
10718:             $uname = $username;
10719:         }
10720:     }
10721:     my ($dirRoot,$listing,@listing_results);
10722: 
10723:     $dirRoot = $perlvar{'lonDocRoot'};
10724:     if (defined($getpropath)) {
10725:         $dirRoot = &propath($udom,$uname);
10726:         $dirRoot =~ s/\/$//;
10727:     } elsif (defined($getuserdir)) {
10728:         my $subdir=$uname.'__';
10729:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10730:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10731:                    ."/$udom/$subdir/$uname";
10732:     } elsif (defined($alternateRoot)) {
10733:         $dirRoot = $alternateRoot;
10734:     }
10735: 
10736:     if($udom) {
10737:         if($uname) {
10738:             my $uhome = &homeserver($uname,$udom);
10739:             if ($uhome eq 'no_host') {
10740:                 return ([],'no_host');
10741:             }
10742:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10743:                               .$getuserdir.':'.&escape($dirRoot)
10744:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10745:             if ($listing eq 'unknown_cmd') {
10746:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10747:             } else {
10748:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10749:             }
10750:             if ($listing eq 'unknown_cmd') {
10751:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10752:                 @listing_results = split(/:/,$listing);
10753:             } else {
10754:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10755:             }
10756:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10757:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10758:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10759:                 return ([],$listing);
10760:             } else {
10761:                 return (\@listing_results);
10762:             }
10763:         } elsif(!$alternateRoot) {
10764:             my (%allusers,%listerror);
10765: 	    my %servers = &get_servers($udom,'library');
10766:  	    foreach my $tryserver (keys(%servers)) {
10767:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10768:                                   &escape($udom),$tryserver);
10769:                 if ($listing eq 'unknown_cmd') {
10770: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10771: 				      $udom, $tryserver);
10772:                 } else {
10773:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10774:                 }
10775: 		if ($listing eq 'unknown_cmd') {
10776: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10777: 				      $udom, $tryserver);
10778: 		    @listing_results = split(/:/,$listing);
10779: 		} else {
10780: 		    @listing_results =
10781: 			map { &unescape($_); } split(/:/,$listing);
10782: 		}
10783:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10784:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10785:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10786:                     $listerror{$tryserver} = $listing;
10787:                 } else {
10788: 		    foreach my $line (@listing_results) {
10789: 			my ($entry) = split(/&/,$line,2);
10790: 			$allusers{$entry} = 1;
10791: 		    }
10792: 		}
10793:             }
10794:             my @alluserslist=();
10795:             foreach my $user (sort(keys(%allusers))) {
10796:                 push(@alluserslist,$user.'&user');
10797:             }
10798: 
10799:             if (!%listerror) {
10800:                 # no errors
10801:                 return (\@alluserslist);
10802:             } elsif (scalar(keys(%servers)) == 1) {
10803:                 # one library server, one error 
10804:                 my ($key) = keys(%listerror);
10805:                 return (\@alluserslist, $listerror{$key});
10806:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10807:                 # con_lost indicates that we might miss data from at least one
10808:                 # library server
10809:                 return (\@alluserslist, 'con_lost');
10810:             } else {
10811:                 # multiple library servers and no con_lost -> data should be
10812:                 # complete. 
10813:                 return (\@alluserslist);
10814:             }
10815: 
10816:         } else {
10817:             return ([],'missing username');
10818:         }
10819:     } elsif(!defined($getpropath)) {
10820:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10821:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10822:         return (\@all_domains);
10823:     } else {
10824:         return ([],'missing domain');
10825:     }
10826: }
10827: 
10828: # --------------------------------------------- GetFileTimestamp
10829: # This function utilizes dirlist and returns the date stamp for
10830: # when it was last modified.  It will also return an error of -1
10831: # if an error occurs
10832: 
10833: sub GetFileTimestamp {
10834:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10835:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10836:     $studentName   = &LONCAPA::clean_username($studentName);
10837:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10838:                                     undef,$getuserdir);
10839:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10840:         return -1;
10841:     }
10842:     if (ref($fileref) eq 'ARRAY') {
10843:         my @stats = split('&',$fileref->[0]);
10844:         # @stats contains first the filename, then the stat output
10845:         return $stats[10]; # so this is 10 instead of 9.
10846:     } else {
10847:         return -1;
10848:     }
10849: }
10850: 
10851: sub stat_file {
10852:     my ($uri) = @_;
10853:     $uri = &clutter_with_no_wrapper($uri);
10854: 
10855:     my ($udom,$uname,$file);
10856:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10857: 	($udom,$uname,$file) =
10858: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10859: 	$file = 'userfiles/'.$file;
10860:     }
10861:     if ($uri =~ m-^/res/-) {
10862: 	($udom,$uname) = 
10863: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10864: 	$file = $uri;
10865:     }
10866: 
10867:     if (!$udom || !$uname || !$file) {
10868: 	# unable to handle the uri
10869: 	return ();
10870:     }
10871:     my $getpropath;
10872:     if ($file =~ /^userfiles\//) {
10873:         $getpropath = 1;
10874:     }
10875:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10876:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10877:         return ();
10878:     } else {
10879:         if (ref($listref) eq 'ARRAY') {
10880:             my @stats = split('&',$listref->[0]);
10881: 	    shift(@stats); #filename is first
10882: 	    return @stats;
10883:         }
10884:     }
10885:     return ();
10886: }
10887: 
10888: # --------------------------------------------------------- recursedirs
10889: # Recursive function to traverse either a specific user's Authoring Space
10890: # or corresponding Published Resource Space, and populate the hash ref:
10891: # $dirhashref with URLs of all directories, and if $filehashref hash
10892: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10893: # or .rights files in resource space, and .meta, .save, .log, and .bak
10894: # files in Authoring Space.
10895: #
10896: # Inputs:
10897: #
10898: # $is_home - true if current server is home server for user's space
10899: # $context - either: priv, or res respectively for Authoring or Resource Space.
10900: # $docroot - Document root (i.e., /home/httpd/html
10901: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10902: # $relpath - Current path (relative to top level).
10903: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10904: # $filehashref - reference to hash to populate with URLs of files (Optional)
10905: #
10906: # Returns: nothing
10907: #
10908: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10909: #
10910: # Currently used by interface/londocs.pm to create linked select boxes for
10911: # directory and filename to import a Course "Author" resource into a course, and
10912: # also to create linked select boxes for Authoring Space and Directory to choose
10913: # save location for creation of a new "standard" problem from the Course Editor.
10914: #
10915: 
10916: sub recursedirs {
10917:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10918:     return unless (ref($dirhashref) eq 'HASH');
10919:     my $currpath = $docroot.$toppath;
10920:     if ($relpath) {
10921:         $currpath .= "/$relpath";
10922:     }
10923:     my $savefile;
10924:     if (ref($filehashref)) {
10925:         $savefile = 1;
10926:     }
10927:     if ($is_home) {
10928:         if (opendir(my $dirh,$currpath)) {
10929:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10930:                 next if ($item eq '');
10931:                 if (-d "$currpath/$item") {
10932:                     my $newpath;
10933:                     if ($relpath) {
10934:                         $newpath = "$relpath/$item";
10935:                     } else {
10936:                         $newpath = $item;
10937:                     }
10938:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10939:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10940:                 } elsif ($savefile) {
10941:                     if ($context eq 'priv') {
10942:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10943:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10944:                         }
10945:                     } else {
10946:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10947:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10948:                         }
10949:                     }
10950:                 }
10951:             }
10952:             closedir($dirh);
10953:         }
10954:     } else {
10955:         my ($dirlistref,$listerror) =
10956:             &dirlist($toppath.$relpath);
10957:         my @dir_lines;
10958:         my $dirptr=16384;
10959:         if (ref($dirlistref) eq 'ARRAY') {
10960:             foreach my $dir_line (sort
10961:                               {
10962:                                   my ($afile)=split('&',$a,2);
10963:                                   my ($bfile)=split('&',$b,2);
10964:                                   return (lc($afile) cmp lc($bfile));
10965:                               } (@{$dirlistref})) {
10966:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10967:                     split(/\&/,$dir_line,16);
10968:                 $item =~ s/\s+$//;
10969:                 next if (($item =~ /^\.\.?$/) || ($obs));
10970:                 if ($dirptr&$testdir) {
10971:                     my $newpath;
10972:                     if ($relpath) {
10973:                         $newpath = "$relpath/$item";
10974:                     } else {
10975:                         $relpath = '/';
10976:                         $newpath = $item;
10977:                     }
10978:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10979:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10980:                 } elsif ($savefile) {
10981:                     if ($context eq 'priv') {
10982:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10983:                             $filehashref->{$relpath}{$item} = 1;
10984:                         }
10985:                     } else {
10986:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10987:                             $filehashref->{$relpath}{$item} = 1;
10988:                         }
10989:                     }
10990:                 }
10991:             }
10992:         }
10993:     }
10994:     return;
10995: }
10996: 
10997: # -------------------------------------------------------- Value of a Condition
10998: 
10999: # gets the value of a specific preevaluated condition
11000: #    stored in the string  $env{user.state.<cid>}
11001: # or looks up a condition reference in the bighash and if if hasn't
11002: # already been evaluated recurses into docondval to get the value of
11003: # the condition, then memoizing it to 
11004: #   $env{user.state.<cid>.<condition>}
11005: sub directcondval {
11006:     my $number=shift;
11007:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11008: 	&Apache::lonuserstate::evalstate();
11009:     }
11010:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11011: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11012:     } elsif ($number =~ /^_/) {
11013: 	my $sub_condition;
11014: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11015: 		&GDBM_READER(),0640)) {
11016: 	    $sub_condition=$bighash{'conditions'.$number};
11017: 	    untie(%bighash);
11018: 	}
11019: 	my $value = &docondval($sub_condition);
11020: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11021: 	return $value;
11022:     }
11023:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11024:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11025:     } else {
11026:        return 2;
11027:     }
11028: }
11029: 
11030: # get the collection of conditions for this resource
11031: sub condval {
11032:     my $condidx=shift;
11033:     my $allpathcond='';
11034:     foreach my $cond (split(/\|/,$condidx)) {
11035: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11036: 	    $allpathcond.=
11037: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11038: 	}
11039:     }
11040:     $allpathcond=~s/\|$//;
11041:     return &docondval($allpathcond);
11042: }
11043: 
11044: #evaluates an expression of conditions
11045: sub docondval {
11046:     my ($allpathcond) = @_;
11047:     my $result=0;
11048:     if ($env{'request.course.id'}
11049: 	&& defined($allpathcond)) {
11050: 	my $operand='|';
11051: 	my @stack;
11052: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11053: 	    if ($chunk eq '(') {
11054: 		push @stack,($operand,$result);
11055: 	    } elsif ($chunk eq ')') {
11056: 		my $before=pop @stack;
11057: 		if (pop @stack eq '&') {
11058: 		    $result=$result>$before?$before:$result;
11059: 		} else {
11060: 		    $result=$result>$before?$result:$before;
11061: 		}
11062: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11063: 		$operand=$chunk;
11064: 	    } else {
11065: 		my $new=directcondval($chunk);
11066: 		if ($operand eq '&') {
11067: 		    $result=$result>$new?$new:$result;
11068: 		} else {
11069: 		    $result=$result>$new?$result:$new;
11070: 		}
11071: 	    }
11072: 	}
11073:     }
11074:     return $result;
11075: }
11076: 
11077: # ---------------------------------------------------- Devalidate courseresdata
11078: 
11079: sub devalidatecourseresdata {
11080:     my ($coursenum,$coursedomain)=@_;
11081:     my $hashid=$coursenum.':'.$coursedomain;
11082:     &devalidate_cache_new('courseres',$hashid);
11083: }
11084: 
11085: 
11086: # --------------------------------------------------- Course Resourcedata Query
11087: #
11088: #  Parameters:
11089: #      $coursenum    - Number of the course.
11090: #      $coursedomain - Domain at which the course was created.
11091: #  Returns:
11092: #     A hash of the course parameters along (I think) with timestamps
11093: #     and version info.
11094: 
11095: sub get_courseresdata {
11096:     my ($coursenum,$coursedomain)=@_;
11097:     my $coursehom=&homeserver($coursenum,$coursedomain);
11098:     my $hashid=$coursenum.':'.$coursedomain;
11099:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11100:     my %dumpreply;
11101:     unless (defined($cached)) {
11102: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11103: 	$result=\%dumpreply;
11104: 	my ($tmp) = keys(%dumpreply);
11105: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11106: 	    &do_cache_new('courseres',$hashid,$result,600);
11107: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11108: 	    return $tmp;
11109: 	} elsif ($tmp =~ /^(error)/) {
11110: 	    $result=undef;
11111: 	    &do_cache_new('courseres',$hashid,$result,600);
11112: 	}
11113:     }
11114:     return $result;
11115: }
11116: 
11117: sub devalidateuserresdata {
11118:     my ($uname,$udom)=@_;
11119:     my $hashid="$udom:$uname";
11120:     &devalidate_cache_new('userres',$hashid);
11121: }
11122: 
11123: sub get_userresdata {
11124:     my ($uname,$udom)=@_;
11125:     #most student don\'t have any data set, check if there is some data
11126:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11127: 
11128:     my $hashid="$udom:$uname";
11129:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11130:     if (!defined($cached)) {
11131: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11132: 	$result=\%resourcedata;
11133: 	&do_cache_new('userres',$hashid,$result,600);
11134:     }
11135:     my ($tmp)=keys(%$result);
11136:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11137: 	return $result;
11138:     }
11139:     #error 2 occurs when the .db doesn't exist
11140:     if ($tmp!~/error: 2 /) {
11141:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11142: 	    &logthis("<font color=\"blue\">WARNING:".
11143: 		     " Trying to get resource data for ".
11144: 		     $uname." at ".$udom.": ".
11145: 		     $tmp."</font>");
11146:         }
11147:     } elsif ($tmp=~/error: 2 /) {
11148: 	#&EXT_cache_set($udom,$uname);
11149: 	&do_cache_new('userres',$hashid,undef,600);
11150: 	undef($tmp); # not really an error so don't send it back
11151:     }
11152:     return $tmp;
11153: }
11154: #----------------------------------------------- resdata - return resource data
11155: #  Purpose:
11156: #    Return resource data for either users or for a course.
11157: #  Parameters:
11158: #     $name      - Course/user name.
11159: #     $domain    - Name of the domain the user/course is registered on.
11160: #     $type      - Type of thing $name is (must be 'course' or 'user')
11161: #     $mapp      - decluttered URL of enclosing map  
11162: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11163: #     $recurseup - Ref to array of map URLs, starting with map containing
11164: #                  $mapp up through hierarchy of nested maps to top level map.  
11165: #     $courseid  - CourseID (first part of param identifier).
11166: #     $modifier  - Middle part of param identifier.
11167: #     $what      - Last part of param identifier.
11168: #     @which     - Array of names of resources desired.
11169: #  Returns:
11170: #     The value of the first reasource in @which that is found in the
11171: #     resource hash.
11172: #  Exceptional Conditions:
11173: #     If the $type passed in is not valid (not the string 'course' or 
11174: #     'user', an undefined  reference is returned.
11175: #     If none of the resources are found, an undef is returned
11176: sub resdata {
11177:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11178:         $modifier,$what,@which)=@_;
11179:     my $result;
11180:     if ($type eq 'course') {
11181: 	$result=&get_courseresdata($name,$domain);
11182:     } elsif ($type eq 'user') {
11183: 	$result=&get_userresdata($name,$domain);
11184:     }
11185:     if (!ref($result)) { return $result; }    
11186:     foreach my $item (@which) {
11187:         if ($item->[1] eq 'course') {
11188:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11189:                 unless ($$recursed) {
11190:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11191:                     $$recursed = 1;
11192:                 }
11193:                 foreach my $item (@${recurseup}) {
11194:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11195:                     last if (defined($result->{$norecursechk}));
11196:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11197:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11198:                 }
11199:             }
11200:         }
11201:         if (defined($result->{$item->[0]})) {
11202: 	    return [$result->{$item->[0]},$item->[1]];
11203: 	}
11204:     }
11205:     return undef;
11206: }
11207: 
11208: sub get_domain_lti {
11209:     my ($cdom,$context) = @_;
11210:     my ($name,%lti);
11211:     if ($context eq 'consumer') {
11212:         $name = 'ltitools';
11213:     } elsif ($context eq 'provider') {
11214:         $name = 'lti';
11215:     } else {
11216:         return %lti;
11217:     }
11218:     my ($result,$cached)=&is_cached_new($name,$cdom);
11219:     if (defined($cached)) {
11220:         if (ref($result) eq 'HASH') {
11221:             %lti = %{$result};
11222:         }
11223:     } else {
11224:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11225:         if (ref($domconfig{$name}) eq 'HASH') {
11226:             %lti = %{$domconfig{$name}};
11227:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11228:             if (ref($encdomconfig{$name}) eq 'HASH') {
11229:                 foreach my $id (keys(%lti)) {
11230:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11231:                         foreach my $item ('key','secret') {
11232:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11233:                         }
11234:                     }
11235:                 }
11236:             }
11237:         }
11238:         my $cachetime = 24*60*60;
11239:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11240:     }
11241:     return %lti;
11242: }
11243: 
11244: sub get_numsuppfiles {
11245:     my ($cnum,$cdom,$ignorecache)=@_;
11246:     my $hashid=$cnum.':'.$cdom;
11247:     my ($suppcount,$cached);
11248:     unless ($ignorecache) {
11249:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11250:     }
11251:     unless (defined($cached)) {
11252:         my $chome=&homeserver($cnum,$cdom);
11253:         unless ($chome eq 'no_host') {
11254:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11255:             my $suppmap = 'supplemental.sequence';
11256:             ($suppcount,$supptools,$errors) =
11257:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11258:                                                          $supptools,$errors);
11259:         }
11260:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11261:     }
11262:     return $suppcount;
11263: }
11264: 
11265: #
11266: # EXT resource caching routines
11267: #
11268: 
11269: {
11270: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11271: #
11272: # The course for which we cache
11273: my $cachedmapkey='';
11274: # The cached recursive maps for this course
11275: my %cachedmaps=();
11276: # When this was last done
11277: my $cachedmaptime='';
11278: 
11279: sub clear_EXT_cache_status {
11280:     &delenv('cache.EXT.');
11281: }
11282: 
11283: sub EXT_cache_status {
11284:     my ($target_domain,$target_user) = @_;
11285:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11286:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11287:         # We know already the user has no data
11288:         return 1;
11289:     } else {
11290:         return 0;
11291:     }
11292: }
11293: 
11294: sub EXT_cache_set {
11295:     my ($target_domain,$target_user) = @_;
11296:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11297:     #&appenv({$cachename => time});
11298: }
11299: 
11300: # --------------------------------------------------------- Value of a Variable
11301: sub EXT {
11302: 
11303:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11304:     unless ($varname) { return ''; }
11305:     #get real user name/domain, courseid and symb
11306:     my $courseid;
11307:     my $publicuser;
11308:     if ($symbparm) {
11309: 	$symbparm=&get_symb_from_alias($symbparm);
11310:     }
11311:     if (!($uname && $udom)) {
11312:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11313:       if (!$symbparm) {	$symbparm=$cursymb; }
11314:     } else {
11315: 	$courseid=$env{'request.course.id'};
11316:     }
11317:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11318:     my $rest;
11319:     if (defined($therest[0])) {
11320:        $rest=join('.',@therest);
11321:     } else {
11322:        $rest='';
11323:     }
11324: 
11325:     my $qualifierrest=$qualifier;
11326:     if ($rest) { $qualifierrest.='.'.$rest; }
11327:     my $spacequalifierrest=$space;
11328:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11329:     if ($realm eq 'user') {
11330: # --------------------------------------------------------------- user.resource
11331: 	if ($space eq 'resource') {
11332: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11333: 		  || defined($Apache::lonhomework::parsing_a_task))
11334: 		 &&
11335: 		 ($symbparm eq &symbread()) ) {	
11336: 		# if we are in the middle of processing the resource the
11337: 		# get the value we are planning on committing
11338:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11339:                     return $Apache::lonhomework::results{$qualifierrest};
11340:                 } else {
11341:                     return $Apache::lonhomework::history{$qualifierrest};
11342:                 }
11343: 	    } else {
11344: 		my %restored;
11345: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11346: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11347: 		} else {
11348: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11349: 		}
11350: 		return $restored{$qualifierrest};
11351: 	    }
11352: # ----------------------------------------------------------------- user.access
11353:         } elsif ($space eq 'access') {
11354: 	    # FIXME - not supporting calls for a specific user
11355:             return &allowed($qualifier,$rest);
11356: # ------------------------------------------ user.preferences, user.environment
11357:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11358: 	    if (($uname eq $env{'user.name'}) &&
11359: 		($udom eq $env{'user.domain'})) {
11360: 		return $env{join('.',('environment',$qualifierrest))};
11361: 	    } else {
11362: 		my %returnhash;
11363: 		if (!$publicuser) {
11364: 		    %returnhash=&userenvironment($udom,$uname,
11365: 						 $qualifierrest);
11366: 		}
11367: 		return $returnhash{$qualifierrest};
11368: 	    }
11369: # ----------------------------------------------------------------- user.course
11370:         } elsif ($space eq 'course') {
11371: 	    # FIXME - not supporting calls for a specific user
11372:             return $env{join('.',('request.course',$qualifier))};
11373: # ------------------------------------------------------------------- user.role
11374:         } elsif ($space eq 'role') {
11375: 	    # FIXME - not supporting calls for a specific user
11376:             my ($role,$where)=split(/\./,$env{'request.role'});
11377:             if ($qualifier eq 'value') {
11378: 		return $role;
11379:             } elsif ($qualifier eq 'extent') {
11380:                 return $where;
11381:             }
11382: # ----------------------------------------------------------------- user.domain
11383:         } elsif ($space eq 'domain') {
11384:             return $udom;
11385: # ------------------------------------------------------------------- user.name
11386:         } elsif ($space eq 'name') {
11387:             return $uname;
11388: # ---------------------------------------------------- Any other user namespace
11389:         } else {
11390: 	    my %reply;
11391: 	    if (!$publicuser) {
11392: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11393: 	    }
11394: 	    return $reply{$qualifierrest};
11395:         }
11396:     } elsif ($realm eq 'query') {
11397: # ---------------------------------------------- pull stuff out of query string
11398:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11399: 						[$spacequalifierrest]);
11400: 	return $env{'form.'.$spacequalifierrest}; 
11401:    } elsif ($realm eq 'request') {
11402: # ------------------------------------------------------------- request.browser
11403:         if ($space eq 'browser') {
11404:             return $env{'browser.'.$qualifier};
11405: # ------------------------------------------------------------ request.filename
11406:         } else {
11407:             return $env{'request.'.$spacequalifierrest};
11408:         }
11409:     } elsif ($realm eq 'course') {
11410: # ---------------------------------------------------------- course.description
11411:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11412:     } elsif ($realm eq 'resource') {
11413: 
11414: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11415: 	    if (!$symbparm) { $symbparm=&symbread(); }
11416: 	}
11417: 
11418:         if ($qualifier eq '') {
11419: 	    if ($space eq 'title') {
11420: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11421: 	        return &gettitle($symbparm);
11422: 	    }
11423: 	
11424: 	    if ($space eq 'map') {
11425: 	        my ($map) = &decode_symb($symbparm);
11426: 	        return &symbread($map);
11427: 	    }
11428:             if ($space eq 'maptitle') {
11429:                 my ($map) = &decode_symb($symbparm);
11430:                 return &gettitle($map);
11431:             }
11432: 	    if ($space eq 'filename') {
11433: 	        if ($symbparm) {
11434: 		    return &clutter((&decode_symb($symbparm))[2]);
11435: 	        }
11436: 	        return &hreflocation('',$env{'request.filename'});
11437: 	    }
11438: 
11439:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11440:                 if ($space eq 'visibleparts') {
11441:                     my $navmap = Apache::lonnavmaps::navmap->new();
11442:                     my $item;
11443:                     if (ref($navmap)) {
11444:                         my $res = $navmap->getBySymb($symbparm);
11445:                         my $parts = $res->parts();
11446:                         if (ref($parts) eq 'ARRAY') {
11447:                             $item = join(',',@{$parts});
11448:                         }
11449:                         undef($navmap);
11450:                     }
11451:                     return $item;
11452:                 }
11453:             }
11454:         }
11455: 
11456: 	my ($section, $group, @groups, @recurseup, $recursed);
11457: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11458:         if (($courseid eq '') && ($cid)) {
11459:             $courseid = $cid;
11460:         }
11461: 	if (($symbparm && $courseid) && 
11462: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11463: 
11464: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11465: 
11466: # ----------------------------------------------------- Cascading lookup scheme
11467: 	    my $symbp=$symbparm;
11468: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11469: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11470:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11471: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11472: 	    if (($env{'user.name'} eq $uname) &&
11473: 		($env{'user.domain'} eq $udom)) {
11474: 		$section=$env{'request.course.sec'};
11475:                 @groups = split(/:/,$env{'request.course.groups'});  
11476:                 @groups=&sort_course_groups($courseid,@groups); 
11477: 	    } else {
11478: 		if (! defined($usection)) {
11479: 		    $section=&getsection($udom,$uname,$courseid);
11480: 		} else {
11481: 		    $section = $usection;
11482: 		}
11483:                 @groups = &get_users_groups($udom,$uname,$courseid);
11484: 	    }
11485: 
11486: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11487: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11488:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11489: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11490: 
11491: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11492: 	    my $courselevelr=$courseid.'.'.$symbparm;
11493:             $courseleveli=$courseid.'.'.$recurseparm;
11494: 	    $courselevelm=$courseid.'.'.$mapparm;
11495: 
11496: # ----------------------------------------------------------- first, check user
11497: 
11498: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11499:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11500: 				       ([$courselevelr,'resource'],
11501: 					[$courselevelm,'map'     ],
11502:                                         [$courseleveli,'map'     ],
11503: 					[$courselevel, 'course'  ]));
11504: 	    if (defined($userreply)) { return &get_reply($userreply); }
11505: 
11506: # ------------------------------------------------ second, check some of course
11507:             my $coursereply;
11508:             if (@groups > 0) {
11509:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11510:                                        $recurseparm,$mapparm,$spacequalifierrest,
11511:                                        $mapp,\$recursed,\@recurseup);
11512:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11513:             }
11514: 
11515: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11516: 				  $env{'course.'.$courseid.'.domain'},
11517: 				  'course',$mapp,\$recursed,\@recurseup,
11518:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11519: 				  ([$seclevelr,   'resource'],
11520: 				   [$seclevelm,   'map'     ],
11521:                                    [$secleveli,   'map'     ],
11522: 				   [$seclevel,    'course'  ],
11523: 				   [$courselevelr,'resource']));
11524: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11525: 
11526: # ------------------------------------------------------ third, check map parms
11527: 	    my %parmhash=();
11528: 	    my $thisparm='';
11529: 	    if (tie(%parmhash,'GDBM_File',
11530: 		    $env{'request.course.fn'}.'_parms.db',
11531: 		    &GDBM_READER(),0640)) {
11532: 		$thisparm=$parmhash{$symbparm};
11533: 		untie(%parmhash);
11534: 	    }
11535: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11536: 	}
11537: # ------------------------------------------ fourth, look in resource metadata
11538:  
11539:         my $what = $spacequalifierrest;
11540: 	$what=~s/\./\_/;
11541: 	my $filename;
11542: 	if (!$symbparm) { $symbparm=&symbread(); }
11543: 	if ($symbparm) {
11544: 	    $filename=(&decode_symb($symbparm))[2];
11545: 	} else {
11546: 	    $filename=$env{'request.filename'};
11547: 	}
11548:         my $toolsymb;
11549:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
11550:             $toolsymb = $symbparm;
11551:         }
11552: 	my $metadata=&metadata($filename,$what,$toolsymb);
11553: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11554: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
11555: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11556: 
11557: # ----------------------------------------------- fifth, look in rest of course
11558: 	if ($symbparm && defined($courseid) && 
11559: 	    $courseid eq $env{'request.course.id'}) {
11560: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11561: 				     $env{'course.'.$courseid.'.domain'},
11562: 				     'course',$mapp,\$recursed,\@recurseup,
11563:                                      $courseid,'.',$spacequalifierrest,
11564: 				     ([$courselevelm,'map'   ],
11565:                                       [$courseleveli,'map'   ],
11566: 				      [$courselevel, 'course']));
11567: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11568: 	}
11569: # ------------------------------------------------------------------ Cascade up
11570: 	unless ($space eq '0') {
11571: 	    my @parts=split(/_/,$space);
11572: 	    my $id=pop(@parts);
11573: 	    my $part=join('_',@parts);
11574: 	    if ($part eq '') { $part='0'; }
11575: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11576: 				 $symbparm,$udom,$uname,$section,1);
11577: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11578: 	}
11579: 	if ($recurse) { return undef; }
11580: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
11581: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11582: # ---------------------------------------------------- Any other user namespace
11583:     } elsif ($realm eq 'environment') {
11584: # ----------------------------------------------------------------- environment
11585: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11586: 	    return $env{'environment.'.$spacequalifierrest};
11587: 	} else {
11588: 	    if ($uname eq 'anonymous' && $udom eq '') {
11589: 		return '';
11590: 	    }
11591: 	    my %returnhash=&userenvironment($udom,$uname,
11592: 					    $spacequalifierrest);
11593: 	    return $returnhash{$spacequalifierrest};
11594: 	}
11595:     } elsif ($realm eq 'system') {
11596: # ----------------------------------------------------------------- system.time
11597: 	if ($space eq 'time') {
11598: 	    return time;
11599:         }
11600:     } elsif ($realm eq 'server') {
11601: # ----------------------------------------------------------------- system.time
11602: 	if ($space eq 'name') {
11603: 	    return $ENV{'SERVER_NAME'};
11604:         }
11605:     }
11606:     return '';
11607: }
11608: 
11609: sub get_reply {
11610:     my ($reply_value) = @_;
11611:     if (ref($reply_value) eq 'ARRAY') {
11612:         if (wantarray) {
11613: 	    return @$reply_value;
11614:         }
11615:         return $reply_value->[0];
11616:     } else {
11617:         return $reply_value;
11618:     }
11619: }
11620: 
11621: sub check_group_parms {
11622:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11623:         $recursed,$recurseupref) = @_;
11624:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11625:                   [$what,'course']);
11626:     my $coursereply;
11627:     foreach my $group (@{$groups}) {
11628:         my @groupitems = ();
11629:         foreach my $level (@levels) {
11630:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11631:              push(@groupitems,[$item,$level->[1]]);
11632:         }
11633:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11634:                                    $env{'course.'.$courseid.'.domain'},
11635:                                    'course',$mapp,$recursed,$recurseupref,
11636:                                    $courseid,'.['.$group.'].',$what,
11637:                                    @groupitems);
11638:         last if (defined($coursereply));
11639:     }
11640:     return $coursereply;
11641: }
11642: 
11643: sub get_map_hierarchy {
11644:     my ($mapname,$courseid) = @_;
11645:     my @recurseup = ();
11646:     if ($mapname) {
11647:         if (($cachedmapkey eq $courseid) &&
11648:             (abs($cachedmaptime-time)<5)) {
11649:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11650:                 return @{$cachedmaps{$mapname}};
11651:             }
11652:         }
11653:         my $navmap = Apache::lonnavmaps::navmap->new();
11654:         if (ref($navmap)) {
11655:             @recurseup = $navmap->recurseup_maps($mapname);
11656:             undef($navmap);
11657:             $cachedmaps{$mapname} = \@recurseup;
11658:             $cachedmaptime=time;
11659:             $cachedmapkey=$courseid;
11660:         }
11661:     }
11662:     return @recurseup;
11663: }
11664: 
11665: }
11666: 
11667: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11668:     my ($courseid,@groups) = @_;
11669:     @groups = sort(@groups);
11670:     return @groups;
11671: }
11672: 
11673: sub packages_tab_default {
11674:     my ($uri,$varname,$toolsymb)=@_;
11675:     my (undef,$part,$name)=split(/\./,$varname);
11676: 
11677:     my (@extension,@specifics,$do_default);
11678:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
11679: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11680: 	if ($pack_type eq 'default') {
11681: 	    $do_default=1;
11682: 	} elsif ($pack_type eq 'extension') {
11683: 	    push(@extension,[$package,$pack_type,$pack_part]);
11684: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11685: 	    # only look at packages defaults for packages that this id is
11686: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11687: 	}
11688:     }
11689:     # first look for a package that matches the requested part id
11690:     foreach my $package (@specifics) {
11691: 	my (undef,$pack_type,$pack_part)=@{$package};
11692: 	next if ($pack_part ne $part);
11693: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11694: 	    return $packagetab{"$pack_type&$name&default"};
11695: 	}
11696:     }
11697:     # look for any possible matching non extension_ package
11698:     foreach my $package (@specifics) {
11699: 	my (undef,$pack_type,$pack_part)=@{$package};
11700: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11701: 	    return $packagetab{"$pack_type&$name&default"};
11702: 	}
11703: 	if ($pack_type eq 'part') { $pack_part='0'; }
11704: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11705: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11706: 	}
11707:     }
11708:     # look for any posible extension_ match
11709:     foreach my $package (@extension) {
11710: 	my ($package,$pack_type)=@{$package};
11711: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11712: 	    return $packagetab{"$pack_type&$name&default"};
11713: 	}
11714: 	if (defined($packagetab{$package."&$name&default"})) {
11715: 	    return $packagetab{$package."&$name&default"};
11716: 	}
11717:     }
11718:     # look for a global default setting
11719:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11720: 	return $packagetab{"default&$name&default"};
11721:     }
11722:     return undef;
11723: }
11724: 
11725: sub add_prefix_and_part {
11726:     my ($prefix,$part)=@_;
11727:     my $keyroot;
11728:     if (defined($prefix) && $prefix !~ /^__/) {
11729: 	# prefix that has a part already
11730: 	$keyroot=$prefix;
11731:     } elsif (defined($prefix)) {
11732: 	# prefix that is missing a part
11733: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11734:     } else {
11735: 	# no prefix at all
11736: 	if (defined($part)) { $keyroot='_'.$part; }
11737:     }
11738:     return $keyroot;
11739: }
11740: 
11741: # ---------------------------------------------------------------- Get metadata
11742: 
11743: my %metaentry;
11744: my %importedpartids;
11745: my %importedrespids;
11746: sub metadata {
11747:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
11748:     $uri=&declutter($uri);
11749:     # if it is a non metadata possible uri return quickly
11750:     if (($uri eq '') || 
11751: 	(($uri =~ m|^/*adm/|) && 
11752: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11753:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11754: 	return undef;
11755:     }
11756:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11757: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11758: 	return undef;
11759:     }
11760:     my $filename=$uri;
11761:     $uri=~s/\.meta$//;
11762: #
11763: # Is the metadata already cached?
11764: # Look at timestamp of caching
11765: # Everything is cached by the main uri, libraries are never directly cached
11766: #
11767:     if (!defined($liburi)) {
11768: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11769: 	if (defined($cached)) { return $result->{':'.$what}; }
11770:     }
11771: 
11772: #
11773: # If the uri is for an external tool the file from
11774: # which metadata should be retrieved depends on whether
11775: # the tool had been configured to be gradable (set in the Course
11776: # Editor or Resource Editor).
11777: #
11778: # If a valid symb has been included as the third arg in the call
11779: # to &metadata() that can be used to retrieve the value of
11780: # parameter_0_gradable set for the resource, and included in the
11781: # uploaded map containing the tool. The value is retrieved via
11782: # &EXT(), if a valid symb is available.  Otherwise the value of
11783: # gradable in the exttool_$marker.db file for the tool instance
11784: # is retrieved via &get().
11785: #
11786: # When lonuserstate::traceroute() calls lonnet::EXT() for 
11787: # hiddenresource and encrypturl (during course initialization)
11788: # the map-level parameter for resource.0.gradable included in the 
11789: # uploaded map containing the tool will not yet have been stored
11790: # in the user_course_parms.db file for the user's session, so in 
11791: # this case fall back to retrieving gradable status from the
11792: # exttool_$marker.db file.
11793: #
11794: # In order to avoid an infinite loop, &metadata() will return
11795: # before a call to &EXT(), if the uri is for an external tool
11796: # and the $what for which metadata is being requested is
11797: # parameter_0_gradable or 0_gradable.
11798: #
11799: 
11800:     if ($uri =~ /ext\.tool$/) {
11801:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
11802:             return;
11803:         } else {
11804:             my ($checked,$use_passback);
11805:             if ($toolsymb ne '') {
11806:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
11807:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
11808:                     $checked = 1;
11809:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
11810:                         $use_passback = 1;
11811:                     }
11812:                 }
11813:             }
11814:             unless ($checked) {
11815:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
11816:                 $marker=~s/\D//g;
11817:                 if ($marker) {
11818:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
11819:                     $use_passback = $toolsettings{'gradable'};
11820:                 }
11821:             }
11822:             if ($use_passback) {
11823:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
11824:             } else {
11825:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
11826:             }
11827:         }
11828:     }
11829: 
11830:     {
11831: # Imported parts would go here
11832:         my @origfiletagids=();
11833:         my $importedparts=0;
11834: 
11835: # Imported responseids would go here
11836:         my $importedresponses=0;
11837: #
11838: # Is this a recursive call for a library?
11839: #
11840: #	if (! exists($metacache{$uri})) {
11841: #	    $metacache{$uri}={};
11842: #	}
11843: 	my $cachetime = 60*60;
11844:         if ($liburi) {
11845: 	    $liburi=&declutter($liburi);
11846:             $filename=$liburi;
11847:         } else {
11848: 	    &devalidate_cache_new('meta',$uri);
11849: 	    undef(%metaentry);
11850: 	}
11851:         my %metathesekeys=();
11852:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11853: 	my $metastring;
11854: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11855: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11856: 	    $metastring = 
11857: 		&Apache::lonnet::ssi_body($which,
11858: 					  ('grade_target' => 'meta'));
11859: 	    $cachetime = 1; # only want this cached in the child not long term
11860: 	} elsif (($uri !~ m -^(editupload)/-) && 
11861:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11862: 	    my $file=&filelocation('',&clutter($filename));
11863: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11864: 	    $metastring=&getfile($file);
11865: 	}
11866:         my $parser=HTML::LCParser->new(\$metastring);
11867:         my $token;
11868:         undef %metathesekeys;
11869:         while ($token=$parser->get_token) {
11870: 	    if ($token->[0] eq 'S') {
11871: 		if (defined($token->[2]->{'package'})) {
11872: #
11873: # This is a package - get package info
11874: #
11875: 		    my $package=$token->[2]->{'package'};
11876: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11877: 		    if (defined($token->[2]->{'id'})) { 
11878: 			$keyroot.='_'.$token->[2]->{'id'}; 
11879: 		    }
11880: 		    if ($metaentry{':packages'}) {
11881: 			$metaentry{':packages'}.=','.$package.$keyroot;
11882: 		    } else {
11883: 			$metaentry{':packages'}=$package.$keyroot;
11884: 		    }
11885: 		    foreach my $pack_entry (keys(%packagetab)) {
11886: 			my $part=$keyroot;
11887: 			$part=~s/^\_//;
11888: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11889: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11890: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11891: 			    # ignore package.tab specified default values
11892:                             # here &package_tab_default() will fetch those
11893: 			    if ($subp eq 'default') { next; }
11894: 			    my $value=$packagetab{$pack_entry};
11895: 			    my $unikey;
11896: 			    if ($pack =~ /_0$/) {
11897: 				$unikey='parameter_0_'.$name;
11898: 				$part=0;
11899: 			    } else {
11900: 				$unikey='parameter'.$keyroot.'_'.$name;
11901: 			    }
11902: 			    if ($subp eq 'display') {
11903: 				$value.=' [Part: '.$part.']';
11904: 			    }
11905: 			    $metaentry{':'.$unikey.'.part'}=$part;
11906: 			    $metathesekeys{$unikey}=1;
11907: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11908: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11909: 			    }
11910: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11911: 				$metaentry{':'.$unikey}=
11912: 				    $metaentry{':'.$unikey.'.default'};
11913: 			    }
11914: 			}
11915: 		    }
11916: 		} else {
11917: #
11918: # This is not a package - some other kind of start tag
11919: #
11920: 		    my $entry=$token->[1];
11921: 		    my $unikey='';
11922: 
11923: 		    if ($entry eq 'import') {
11924: #
11925: # Importing a library here
11926: #
11927:                         my $location=$parser->get_text('/import');
11928:                         my $dir=$filename;
11929:                         $dir=~s|[^/]*$||;
11930:                         $location=&filelocation($dir,$location);
11931: 
11932:                         my $importid=$token->[2]->{'id'};
11933:                         my $importmode=$token->[2]->{'importmode'};
11934: #
11935: # Check metadata for imported file to
11936: # see if it contained response items
11937: #
11938:                         my ($origfile,@libfilekeys);
11939:                         my %currmetaentry = %metaentry;
11940:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
11941:                                                            $depthcount+1));
11942:                         if (grep(/^responseorder$/,@libfilekeys)) {
11943:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
11944:                                                              undef,$depthcount+1);
11945:                             if ($libresponseorder ne '') {
11946:                                 if ($#origfiletagids<0) {
11947:                                     undef(%importedrespids);
11948:                                     undef(%importedpartids);
11949:                                 }
11950:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
11951:                                 if (@respids) {
11952:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
11953:                                 }
11954:                                 if ($importedrespids{$importid} ne '') {
11955:                                     $importedresponses = 1;
11956: # We need to get the original file and the imported file to get the response order correct
11957: # Load and inspect original file
11958:                                     if ($#origfiletagids<0) {
11959:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11960:                                         $origfile=&getfile($origfilelocation);
11961:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11962:                                     }
11963:                                 }
11964:                             }
11965:                         }
11966: # Do not overwrite contents of %metaentry hash for resource itself with 
11967: # hash populated for imported library file
11968:                         %metaentry = %currmetaentry;
11969:                         undef(%currmetaentry);
11970:                         if ($importmode eq 'part') {
11971: # Import as part(s)
11972:                            $importedparts=1;
11973: # We need to get the original file and the imported file to get the part order correct
11974: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11975: # Load and inspect original file if we didn't do that already
11976:                            if ($#origfiletagids<0) {
11977:                                undef(%importedrespids);
11978:                                undef(%importedpartids);
11979:                                if ($origfile eq '') {
11980:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11981:                                    $origfile=&getfile($origfilelocation);
11982:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11983:                                }
11984:                            }
11985:                            my @impfilepartids;
11986: # If <partorder> tag is included in metadata for the imported file
11987: # get the parts in the imported file from that.
11988:                            if (grep(/^partorder$/,@libfilekeys)) {
11989:                                %currmetaentry = %metaentry;
11990:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
11991:                                                             $depthcount+1);
11992:                                %metaentry = %currmetaentry;
11993:                                undef(%currmetaentry);
11994:                                if ($libpartorder ne '') {
11995:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
11996:                                }
11997:                            } else {
11998: # If no <partorder> tag available, load and inspect imported file
11999:                                my $impfile=&getfile($location);
12000:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12001:                            }
12002:                            if ($#impfilepartids>=0) {
12003: # This problem had parts
12004:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12005:                            } else {
12006: # Importing by turning a single problem into a problem part
12007: # It gets the import-tags ID as part-ID
12008:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12009:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12010:                            }
12011:                         } else {
12012: # Import as problem or as normal import
12013:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12014:                             unless ($importmode eq 'problem') {
12015: # Normal import
12016:                                 if (defined($token->[2]->{'id'})) {
12017:                                     $unikey.='_'.$token->[2]->{'id'};
12018:                                 }
12019:                             }
12020: # Check metadata for imported file to
12021: # see if it contained parts
12022:                             if (grep(/^partorder$/,@libfilekeys)) {
12023:                                 %currmetaentry = %metaentry;
12024:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12025:                                                              $depthcount+1);
12026:                                 %metaentry = %currmetaentry;
12027:                                 undef(%currmetaentry);
12028:                                 if ($libpartorder ne '') {
12029:                                     $importedparts = 1;
12030:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12031:                                 }
12032:                             }
12033:                         }
12034: 			if ($depthcount<20) {
12035: 			    my $metadata = 
12036: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12037: 					  $depthcount+1);
12038: 			    foreach my $meta (split(',',$metadata)) {
12039: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12040: 				$metathesekeys{$meta}=1;
12041: 			    }
12042:                         }
12043: 		    } else {
12044: #
12045: # Not importing, some other kind of non-package, non-library start tag
12046: # 
12047:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12048:                         if (defined($token->[2]->{'id'})) {
12049:                             $unikey.='_'.$token->[2]->{'id'};
12050:                         }
12051: 			if (defined($token->[2]->{'name'})) { 
12052: 			    $unikey.='_'.$token->[2]->{'name'}; 
12053: 			}
12054: 			$metathesekeys{$unikey}=1;
12055: 			foreach my $param (@{$token->[3]}) {
12056: 			    $metaentry{':'.$unikey.'.'.$param} =
12057: 				$token->[2]->{$param};
12058: 			}
12059: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12060: 			my $default=$metaentry{':'.$unikey.'.default'};
12061: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12062: 		 # only ws inside the tag, and not in default, so use default
12063: 		 # as value
12064: 			    $metaentry{':'.$unikey}=$default;
12065: 			} elsif ( $internaltext =~ /\S/ ) {
12066: 		  # something interesting inside the tag
12067: 			    $metaentry{':'.$unikey}=$internaltext;
12068: 			} else {
12069: 		  # no interesting values, don't set a default
12070: 			}
12071: # end of not-a-package not-a-library import
12072: 		    }
12073: # end of not-a-package start tag
12074: 		}
12075: # the next is the end of "start tag"
12076: 	    }
12077: 	}
12078: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12079: 	$extension = lc($extension);
12080: 	if ($extension eq 'htm') { $extension='html'; }
12081: 
12082: 	foreach my $key (keys(%packagetab)) {
12083: 	    #no specific packages #how's our extension
12084: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12085: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12086: 					 \%metathesekeys);
12087: 	}
12088: 
12089: 	if (!exists($metaentry{':packages'})
12090: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12091: 	    foreach my $key (keys(%packagetab)) {
12092: 		#no specific packages well let's get default then
12093: 		if ($key!~/^default&/) { next; }
12094: 		&metadata_create_package_def($uri,$key,'default',
12095: 					     \%metathesekeys);
12096: 	    }
12097: 	}
12098: # are there custom rights to evaluate
12099: 	if ($metaentry{':copyright'} eq 'custom') {
12100: 
12101:     #
12102:     # Importing a rights file here
12103:     #
12104: 	    unless ($depthcount) {
12105: 		my $location=$metaentry{':customdistributionfile'};
12106: 		my $dir=$filename;
12107: 		$dir=~s|[^/]*$||;
12108: 		$location=&filelocation($dir,$location);
12109: 		my $rights_metadata =
12110: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12111: 			      $depthcount+1);
12112: 		foreach my $rights (split(',',$rights_metadata)) {
12113: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12114: 		    $metathesekeys{$rights}=1;
12115: 		}
12116: 	    }
12117: 	}
12118: 	# uniqifiy package listing
12119: 	my %seen;
12120: 	my @uniq_packages =
12121: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12122: 	$metaentry{':packages'} = join(',',@uniq_packages);
12123: 
12124:         if (($importedresponses) || ($importedparts)) {
12125:             if ($importedparts) {
12126: # We had imported parts and need to rebuild partorder
12127:                 $metaentry{':partorder'}='';
12128:                 $metathesekeys{'partorder'}=1;
12129:             }
12130:             if ($importedresponses) {
12131: # We had imported responses and need to rebuil responseorder
12132:                 $metaentry{':responseorder'}='';
12133:                 $metathesekeys{'responseorder'}=1;
12134:             }
12135:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12136:                 my $origid = $origfiletagids[$index+1];
12137:                 if ($origfiletagids[$index] eq 'part') {
12138: # Original part, part of the problem
12139:                     if ($importedparts) {
12140:                         $metaentry{':partorder'}.=','.$origid;
12141:                     }
12142:                 } elsif ($origfiletagids[$index] eq 'import') {
12143:                     if ($importedparts) {
12144: # We have imported parts at this position
12145:                         if ($importedpartids{$origid} ne '') {
12146:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12147:                         }
12148:                     }
12149:                     if ($importedresponses) {
12150: # We have imported responses at this position
12151:                         if ($importedrespids{$origid} ne '') {
12152:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12153:                         }
12154:                     }
12155:                 } else {
12156: # Original response item, part of the problem
12157:                     if ($importedresponses) {
12158:                         $metaentry{':responseorder'}.=','.$origid;
12159:                     }
12160:                 }
12161:             }
12162:             if ($importedparts) {
12163:                 $metaentry{':partorder'}=~s/^\,//;
12164:             }
12165:             if ($importedresponses) {
12166:                 $metaentry{':responseorder'}=~s/^\,//;
12167:             }
12168:         }
12169: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12170: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12171: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12172:         unless ($liburi) {
12173: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12174:         }
12175: # this is the end of "was not already recently cached
12176:     }
12177:     return $metaentry{':'.$what};
12178: }
12179: 
12180: sub metadata_create_package_def {
12181:     my ($uri,$key,$package,$metathesekeys)=@_;
12182:     my ($pack,$name,$subp)=split(/\&/,$key);
12183:     if ($subp eq 'default') { next; }
12184:     
12185:     if (defined($metaentry{':packages'})) {
12186: 	$metaentry{':packages'}.=','.$package;
12187:     } else {
12188: 	$metaentry{':packages'}=$package;
12189:     }
12190:     my $value=$packagetab{$key};
12191:     my $unikey;
12192:     $unikey='parameter_0_'.$name;
12193:     $metaentry{':'.$unikey.'.part'}=0;
12194:     $$metathesekeys{$unikey}=1;
12195:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12196: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12197:     }
12198:     if (defined($metaentry{':'.$unikey.'.default'})) {
12199: 	$metaentry{':'.$unikey}=
12200: 	    $metaentry{':'.$unikey.'.default'};
12201:     }
12202: }
12203: 
12204: sub metadata_generate_part0 {
12205:     my ($metadata,$metacache,$uri) = @_;
12206:     my %allnames;
12207:     foreach my $metakey (keys(%$metadata)) {
12208: 	if ($metakey=~/^parameter\_(.*)/) {
12209: 	  my $part=$$metacache{':'.$metakey.'.part'};
12210: 	  my $name=$$metacache{':'.$metakey.'.name'};
12211: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12212: 	    $allnames{$name}=$part;
12213: 	  }
12214: 	}
12215:     }
12216:     foreach my $name (keys(%allnames)) {
12217:       $$metadata{"parameter_0_$name"}=1;
12218:       my $key=":parameter_0_$name";
12219:       $$metacache{"$key.part"}='0';
12220:       $$metacache{"$key.name"}=$name;
12221:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12222: 					   $allnames{$name}.'_'.$name.
12223: 					   '.type'};
12224:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12225: 			     '.display'};
12226:       my $expr='[Part: '.$allnames{$name}.']';
12227:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12228:       $$metacache{"$key.display"}=$olddis;
12229:     }
12230: }
12231: 
12232: # ------------------------------------------------------ Devalidate title cache
12233: 
12234: sub devalidate_title_cache {
12235:     my ($url)=@_;
12236:     if (!$env{'request.course.id'}) { return; }
12237:     my $symb=&symbread($url);
12238:     if (!$symb) { return; }
12239:     my $key=$env{'request.course.id'}."\0".$symb;
12240:     &devalidate_cache_new('title',$key);
12241: }
12242: 
12243: # ------------------------------------------------- Get the title of a course
12244: 
12245: sub current_course_title {
12246:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12247: }
12248: # ------------------------------------------------- Get the title of a resource
12249: 
12250: sub gettitle {
12251:     my $urlsymb=shift;
12252:     my $symb=&symbread($urlsymb);
12253:     if ($symb) {
12254: 	my $key=$env{'request.course.id'}."\0".$symb;
12255: 	my ($result,$cached)=&is_cached_new('title',$key);
12256: 	if (defined($cached)) { 
12257: 	    return $result;
12258: 	}
12259: 	my ($map,$resid,$url)=&decode_symb($symb);
12260: 	my $title='';
12261: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12262: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12263: 	} else {
12264: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12265: 		    &GDBM_READER(),0640)) {
12266: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12267: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12268: 		untie(%bighash);
12269: 	    }
12270: 	}
12271: 	$title=~s/\&colon\;/\:/gs;
12272: 	if ($title) {
12273: # Remember both $symb and $title for dynamic metadata
12274:             $accesshash{$symb.'___crstitle'}=$title;
12275:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12276: # Cache this title and then return it
12277: 	    return &do_cache_new('title',$key,$title,600);
12278: 	}
12279: 	$urlsymb=$url;
12280:     }
12281:     my $title=&metadata($urlsymb,'title');
12282:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12283:     return $title;
12284: }
12285: 
12286: sub get_slot {
12287:     my ($which,$cnum,$cdom)=@_;
12288:     if (!$cnum || !$cdom) {
12289: 	(undef,my $courseid)=&whichuser();
12290: 	$cdom=$env{'course.'.$courseid.'.domain'};
12291: 	$cnum=$env{'course.'.$courseid.'.num'};
12292:     }
12293:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12294:     my %slotinfo;
12295:     if (exists($remembered{$key})) {
12296: 	$slotinfo{$which} = $remembered{$key};
12297:     } else {
12298: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12299: 	&Apache::lonhomework::showhash(%slotinfo);
12300: 	my ($tmp)=keys(%slotinfo);
12301: 	if ($tmp=~/^error:/) { return (); }
12302: 	$remembered{$key} = $slotinfo{$which};
12303:     }
12304:     if (ref($slotinfo{$which}) eq 'HASH') {
12305: 	return %{$slotinfo{$which}};
12306:     }
12307:     return $slotinfo{$which};
12308: }
12309: 
12310: sub get_reservable_slots {
12311:     my ($cnum,$cdom,$uname,$udom) = @_;
12312:     my $now = time;
12313:     my $reservable_info;
12314:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12315:     if (exists($remembered{$key})) {
12316:         $reservable_info = $remembered{$key};
12317:     } else {
12318:         my %resv;
12319:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12320:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12321:         $reservable_info = \%resv;
12322:         $remembered{$key} = $reservable_info;
12323:     }
12324:     return $reservable_info;
12325: }
12326: 
12327: sub get_course_slots {
12328:     my ($cnum,$cdom) = @_;
12329:     my $hashid=$cnum.':'.$cdom;
12330:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12331:     if (defined($cached)) {
12332:         if (ref($result) eq 'HASH') {
12333:             return %{$result};
12334:         }
12335:     } else {
12336:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12337:         my ($tmp) = keys(%slots);
12338:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12339:             &do_cache_new('allslots',$hashid,\%slots,600);
12340:             return %slots;
12341:         }
12342:     }
12343:     return;
12344: }
12345: 
12346: sub devalidate_slots_cache {
12347:     my ($cnum,$cdom)=@_;
12348:     my $hashid=$cnum.':'.$cdom;
12349:     &devalidate_cache_new('allslots',$hashid);
12350: }
12351: 
12352: sub get_coursechange {
12353:     my ($cdom,$cnum) = @_;
12354:     if ($cdom eq '' || $cnum eq '') {
12355:         return unless ($env{'request.course.id'});
12356:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12357:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12358:     }
12359:     my $hashid=$cdom.'_'.$cnum;
12360:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12361:     if ((defined($cached)) && ($change ne '')) {
12362:         return $change;
12363:     } else {
12364:         my %crshash;
12365:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12366:         if ($crshash{'internal.contentchange'} eq '') {
12367:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12368:             if ($change eq '') {
12369:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12370:                 $change = $crshash{'internal.created'};
12371:             }
12372:         } else {
12373:             $change = $crshash{'internal.contentchange'};
12374:         }
12375:         my $cachetime = 600;
12376:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12377:     }
12378:     return $change;
12379: }
12380: 
12381: sub devalidate_coursechange_cache {
12382:     my ($cnum,$cdom)=@_;
12383:     my $hashid=$cnum.':'.$cdom;
12384:     &devalidate_cache_new('crschange',$hashid);
12385: }
12386: 
12387: # ------------------------------------------------- Update symbolic store links
12388: 
12389: sub symblist {
12390:     my ($mapname,%newhash)=@_;
12391:     $mapname=&deversion(&declutter($mapname));
12392:     my %hash;
12393:     if (($env{'request.course.fn'}) && (%newhash)) {
12394:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12395:                       &GDBM_WRCREAT(),0640)) {
12396: 	    foreach my $url (keys(%newhash)) {
12397: 		next if ($url eq 'last_known'
12398: 			 && $env{'form.no_update_last_known'});
12399: 		$hash{declutter($url)}=&encode_symb($mapname,
12400: 						    $newhash{$url}->[1],
12401: 						    $newhash{$url}->[0]);
12402:             }
12403:             if (untie(%hash)) {
12404: 		return 'ok';
12405:             }
12406:         }
12407:     }
12408:     return 'error';
12409: }
12410: 
12411: # --------------------------------------------------------------- Verify a symb
12412: 
12413: sub symbverify {
12414:     my ($symb,$thisurl,$encstate)=@_;
12415:     my $thisfn=$thisurl;
12416:     $thisfn=&declutter($thisfn);
12417: # direct jump to resource in page or to a sequence - will construct own symbs
12418:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12419: # check URL part
12420:     my ($map,$resid,$url)=&decode_symb($symb);
12421: 
12422:     unless ($url eq $thisfn) { return 0; }
12423: 
12424:     $symb=&symbclean($symb);
12425:     $thisurl=&deversion($thisurl);
12426:     $thisfn=&deversion($thisfn);
12427: 
12428:     my %bighash;
12429:     my $okay=0;
12430: 
12431:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12432:                             &GDBM_READER(),0640)) {
12433:         my $noclutter;
12434:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12435:             $thisurl =~ s/\?.+$//;
12436:             if ($map =~ m{^uploaded/.+\.page$}) {
12437:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12438:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12439:                 $noclutter = 1;
12440:             }
12441:         }
12442:         my $ids;
12443:         if ($noclutter) {
12444:             $ids=$bighash{'ids_'.$thisurl};
12445:         } else {
12446:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12447:         }
12448:         unless ($ids) {
12449:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12450:             $ids=$bighash{$idkey};
12451:         }
12452:         if ($ids) {
12453: # ------------------------------------------------------------------- Has ID(s)
12454:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12455:                 $symb =~ s/\?.+$//;
12456:             }
12457: 	    foreach my $id (split(/\,/,$ids)) {
12458: 	       my ($mapid,$resid)=split(/\./,$id);
12459:                if (
12460:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12461:    eq $symb) {
12462:                    if (ref($encstate)) {
12463:                        $$encstate = $bighash{'encrypted_'.$id};
12464:                    }
12465: 		   if (($env{'request.role.adv'}) ||
12466: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12467:                        ($thisurl eq '/adm/navmaps')) {
12468: 		       $okay=1;
12469:                        last;
12470: 		   }
12471: 	       }
12472: 	   }
12473:         }
12474: 	untie(%bighash);
12475:     }
12476:     return $okay;
12477: }
12478: 
12479: # --------------------------------------------------------------- Clean-up symb
12480: 
12481: sub symbclean {
12482:     my $symb=shift;
12483:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12484: # remove version from map
12485:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12486: 
12487: # remove version from URL
12488:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12489: 
12490: # remove wrapper
12491: 
12492:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12493:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12494:     return $symb;
12495: }
12496: 
12497: # ---------------------------------------------- Split symb to find map and url
12498: 
12499: sub encode_symb {
12500:     my ($map,$resid,$url)=@_;
12501:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12502: }
12503: 
12504: sub decode_symb {
12505:     my $symb=shift;
12506:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12507:     my ($map,$resid,$url)=split(/___/,$symb);
12508:     return (&fixversion($map),$resid,&fixversion($url));
12509: }
12510: 
12511: sub fixversion {
12512:     my $fn=shift;
12513:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12514:     my %bighash;
12515:     my $uri=&clutter($fn);
12516:     my $key=$env{'request.course.id'}.'_'.$uri;
12517: # is this cached?
12518:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12519:     if (defined($cached)) { return $result; }
12520: # unfortunately not cached, or expired
12521:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12522: 	    &GDBM_READER(),0640)) {
12523:  	if ($bighash{'version_'.$uri}) {
12524:  	    my $version=$bighash{'version_'.$uri};
12525:  	    unless (($version eq 'mostrecent') || 
12526: 		    ($version==&getversion($uri))) {
12527:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12528:  	    }
12529:  	}
12530:  	untie %bighash;
12531:     }
12532:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12533: }
12534: 
12535: sub deversion {
12536:     my $url=shift;
12537:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12538:     return $url;
12539: }
12540: 
12541: # ------------------------------------------------------ Return symb list entry
12542: 
12543: sub symbread {
12544:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12545:     my $cache_str='request.symbread.cached.'.$thisfn;
12546:     if (defined($env{$cache_str})) {
12547:         if ($ignorecachednull) {
12548:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12549:         } else {
12550:             return $env{$cache_str};
12551:         }
12552:     }
12553: # no filename provided? try from environment
12554:     unless ($thisfn) {
12555:         if ($env{'request.symb'}) {
12556: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12557: 	}
12558: 	$thisfn=$env{'request.filename'};
12559:     }
12560:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12561: # is that filename actually a symb? Verify, clean, and return
12562:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12563: 	if (&symbverify($thisfn,$1)) {
12564: 	    return $env{$cache_str}=&symbclean($thisfn);
12565: 	}
12566:     }
12567:     $thisfn=declutter($thisfn);
12568:     my %hash;
12569:     my %bighash;
12570:     my $syval='';
12571:     if (($env{'request.course.fn'}) && ($thisfn)) {
12572:         my $targetfn = $thisfn;
12573:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12574:             $targetfn = 'adm/wrapper/'.$thisfn;
12575:         }
12576: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12577: 	    $targetfn=$1;
12578: 	}
12579:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12580:                       &GDBM_READER(),0640)) {
12581: 	    $syval=$hash{$targetfn};
12582:             untie(%hash);
12583:         }
12584: # ---------------------------------------------------------- There was an entry
12585:         if ($syval) {
12586: 	    #unless ($syval=~/\_\d+$/) {
12587: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12588: 		    #&appenv({'request.ambiguous' => $thisfn});
12589: 		    #return $env{$cache_str}='';
12590: 		#}    
12591: 		#$syval.=$1;
12592: 	    #}
12593:         } else {
12594: # ------------------------------------------------------- Was not in symb table
12595:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12596:                             &GDBM_READER(),0640)) {
12597: # ---------------------------------------------- Get ID(s) for current resource
12598:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12599:               unless ($ids) { 
12600:                  $ids=$bighash{'ids_/'.$thisfn};
12601:               }
12602:               unless ($ids) {
12603: # alias?
12604: 		  $ids=$bighash{'mapalias_'.$thisfn};
12605:               }
12606:               if ($ids) {
12607: # ------------------------------------------------------------------- Has ID(s)
12608:                  my @possibilities=split(/\,/,$ids);
12609:                  if ($#possibilities==0) {
12610: # ----------------------------------------------- There is only one possibility
12611: 		     my ($mapid,$resid)=split(/\./,$ids);
12612: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12613: 						    $resid,$thisfn);
12614:                      if (ref($possibles) eq 'HASH') {
12615:                          $possibles->{$syval} = 1;    
12616:                      }
12617:                      if ($checkforblock) {
12618:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12619:                          if (@blockers) {
12620:                              $syval = '';
12621:                              return;
12622:                          }
12623:                      }
12624:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12625: # ------------------------------------------ There is more than one possibility
12626:                      my $realpossible=0;
12627:                      foreach my $id (@possibilities) {
12628: 			 my $file=$bighash{'src_'.$id};
12629:                          my $canaccess;
12630:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12631:                              $canaccess = 1;
12632:                          } else { 
12633:                              $canaccess = &allowed('bre',$file);
12634:                          }
12635:                          if ($canaccess) {
12636:          		     my ($mapid,$resid)=split(/\./,$id);
12637:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12638:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12639: 						             $resid,$thisfn);
12640:                                  if (ref($possibles) eq 'HASH') {
12641:                                      $possibles->{$syval} = 1;
12642:                                  }
12643:                                  if ($checkforblock) {
12644:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12645:                                      unless (@blockers > 0) {
12646:                                          $syval = $poss_syval;
12647:                                          $realpossible++;
12648:                                      }
12649:                                  } else {
12650:                                      $syval = $poss_syval;
12651:                                      $realpossible++;
12652:                                  }
12653:                              }
12654: 			 }
12655:                      }
12656: 		     if ($realpossible!=1) { $syval=''; }
12657:                  } else {
12658:                      $syval='';
12659:                  }
12660: 	      }
12661:               untie(%bighash);
12662:            }
12663:         }
12664:         if ($syval) {
12665: 	    return $env{$cache_str}=$syval;
12666:         }
12667:     }
12668:     &appenv({'request.ambiguous' => $thisfn});
12669:     return $env{$cache_str}='';
12670: }
12671: 
12672: # ---------------------------------------------------------- Return random seed
12673: 
12674: sub numval {
12675:     my $txt=shift;
12676:     $txt=~tr/A-J/0-9/;
12677:     $txt=~tr/a-j/0-9/;
12678:     $txt=~tr/K-T/0-9/;
12679:     $txt=~tr/k-t/0-9/;
12680:     $txt=~tr/U-Z/0-5/;
12681:     $txt=~tr/u-z/0-5/;
12682:     $txt=~s/\D//g;
12683:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12684:     return int($txt);
12685: }
12686: 
12687: sub numval2 {
12688:     my $txt=shift;
12689:     $txt=~tr/A-J/0-9/;
12690:     $txt=~tr/a-j/0-9/;
12691:     $txt=~tr/K-T/0-9/;
12692:     $txt=~tr/k-t/0-9/;
12693:     $txt=~tr/U-Z/0-5/;
12694:     $txt=~tr/u-z/0-5/;
12695:     $txt=~s/\D//g;
12696:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12697:     my $total;
12698:     foreach my $val (@txts) { $total+=$val; }
12699:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12700:     return int($total);
12701: }
12702: 
12703: sub numval3 {
12704:     use integer;
12705:     my $txt=shift;
12706:     $txt=~tr/A-J/0-9/;
12707:     $txt=~tr/a-j/0-9/;
12708:     $txt=~tr/K-T/0-9/;
12709:     $txt=~tr/k-t/0-9/;
12710:     $txt=~tr/U-Z/0-5/;
12711:     $txt=~tr/u-z/0-5/;
12712:     $txt=~s/\D//g;
12713:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12714:     my $total;
12715:     foreach my $val (@txts) { $total+=$val; }
12716:     if ($_64bit) { $total=(($total<<32)>>32); }
12717:     return $total;
12718: }
12719: 
12720: sub digest {
12721:     my ($data)=@_;
12722:     my $digest=&Digest::MD5::md5($data);
12723:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12724:     my ($e,$f);
12725:     {
12726:         use integer;
12727:         $e=($a+$b);
12728:         $f=($c+$d);
12729:         if ($_64bit) {
12730:             $e=(($e<<32)>>32);
12731:             $f=(($f<<32)>>32);
12732:         }
12733:     }
12734:     if (wantarray) {
12735: 	return ($e,$f);
12736:     } else {
12737: 	my $g;
12738: 	{
12739: 	    use integer;
12740: 	    $g=($e+$f);
12741: 	    if ($_64bit) {
12742: 		$g=(($g<<32)>>32);
12743: 	    }
12744: 	}
12745: 	return $g;
12746:     }
12747: }
12748: 
12749: sub latest_rnd_algorithm_id {
12750:     return '64bit5';
12751: }
12752: 
12753: sub get_rand_alg {
12754:     my ($courseid)=@_;
12755:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12756:     if ($courseid) {
12757: 	return $env{"course.$courseid.rndseed"};
12758:     }
12759:     return &latest_rnd_algorithm_id();
12760: }
12761: 
12762: sub validCODE {
12763:     my ($CODE)=@_;
12764:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12765:     return 0;
12766: }
12767: 
12768: sub getCODE {
12769:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12770:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12771: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12772: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12773: 	return $Apache::lonhomework::history{'resource.CODE'};
12774:     }
12775:     return undef;
12776: }
12777: #
12778: #  Determines the random seed for a specific context:
12779: #
12780: # parameters:
12781: #   symb      - in course context the symb for the seed.
12782: #   course_id - The course id of the form domain_coursenum.
12783: #   domain    - Domain for the user.
12784: #   course    - Course for the user.
12785: #   cenv      - environment of the course.
12786: #
12787: # NOTE:
12788: #   All parameters are picked out of the environment if missing
12789: #   or not defined.
12790: #   If a symb cannot be determined the current time is used instead.
12791: #
12792: #  For a given well defined symb, courside, domain, username,
12793: #  and course environment, the seed is reproducible.
12794: #
12795: sub rndseed {
12796:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12797:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12798:     if (!defined($symb)) {
12799: 	unless ($symb=$wsymb) { return time; }
12800:     }
12801:     if (!defined $courseid) { 
12802: 	$courseid=$wcourseid; 
12803:     }
12804:     if (!defined $domain) { $domain=$wdomain; }
12805:     if (!defined $username) { $username=$wusername }
12806: 
12807:     my $which;
12808:     if (defined($cenv->{'rndseed'})) {
12809: 	$which = $cenv->{'rndseed'};
12810:     } else {
12811: 	$which =&get_rand_alg($courseid);
12812:     }
12813:     if (defined(&getCODE())) {
12814: 
12815: 	if ($which eq '64bit5') {
12816: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12817: 	} elsif ($which eq '64bit4') {
12818: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12819: 	} else {
12820: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12821: 	}
12822:     } elsif ($which eq '64bit5') {
12823: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12824:     } elsif ($which eq '64bit4') {
12825: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12826:     } elsif ($which eq '64bit3') {
12827: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12828:     } elsif ($which eq '64bit2') {
12829: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12830:     } elsif ($which eq '64bit') {
12831: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12832:     }
12833:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12834: }
12835: 
12836: sub rndseed_32bit {
12837:     my ($symb,$courseid,$domain,$username)=@_;
12838:     {
12839: 	use integer;
12840: 	my $symbchck=unpack("%32C*",$symb) << 27;
12841: 	my $symbseed=numval($symb) << 22;
12842: 	my $namechck=unpack("%32C*",$username) << 17;
12843: 	my $nameseed=numval($username) << 12;
12844: 	my $domainseed=unpack("%32C*",$domain) << 7;
12845: 	my $courseseed=unpack("%32C*",$courseid);
12846: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12847: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12848: 	#&logthis("rndseed :$num:$symb");
12849: 	if ($_64bit) { $num=(($num<<32)>>32); }
12850: 	return $num;
12851:     }
12852: }
12853: 
12854: sub rndseed_64bit {
12855:     my ($symb,$courseid,$domain,$username)=@_;
12856:     {
12857: 	use integer;
12858: 	my $symbchck=unpack("%32S*",$symb) << 21;
12859: 	my $symbseed=numval($symb) << 10;
12860: 	my $namechck=unpack("%32S*",$username);
12861: 	
12862: 	my $nameseed=numval($username) << 21;
12863: 	my $domainseed=unpack("%32S*",$domain) << 10;
12864: 	my $courseseed=unpack("%32S*",$courseid);
12865: 	
12866: 	my $num1=$symbchck+$symbseed+$namechck;
12867: 	my $num2=$nameseed+$domainseed+$courseseed;
12868: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12869: 	#&logthis("rndseed :$num:$symb");
12870: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12871: 	return "$num1,$num2";
12872:     }
12873: }
12874: 
12875: sub rndseed_64bit2 {
12876:     my ($symb,$courseid,$domain,$username)=@_;
12877:     {
12878: 	use integer;
12879: 	# strings need to be an even # of cahracters long, it it is odd the
12880:         # last characters gets thrown away
12881: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12882: 	my $symbseed=numval($symb) << 10;
12883: 	my $namechck=unpack("%32S*",$username.' ');
12884: 	
12885: 	my $nameseed=numval($username) << 21;
12886: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12887: 	my $courseseed=unpack("%32S*",$courseid.' ');
12888: 	
12889: 	my $num1=$symbchck+$symbseed+$namechck;
12890: 	my $num2=$nameseed+$domainseed+$courseseed;
12891: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12892: 	#&logthis("rndseed :$num:$symb");
12893: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12894: 	return "$num1,$num2";
12895:     }
12896: }
12897: 
12898: sub rndseed_64bit3 {
12899:     my ($symb,$courseid,$domain,$username)=@_;
12900:     {
12901: 	use integer;
12902: 	# strings need to be an even # of cahracters long, it it is odd the
12903:         # last characters gets thrown away
12904: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12905: 	my $symbseed=numval2($symb) << 10;
12906: 	my $namechck=unpack("%32S*",$username.' ');
12907: 	
12908: 	my $nameseed=numval2($username) << 21;
12909: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12910: 	my $courseseed=unpack("%32S*",$courseid.' ');
12911: 	
12912: 	my $num1=$symbchck+$symbseed+$namechck;
12913: 	my $num2=$nameseed+$domainseed+$courseseed;
12914: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12915: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12916: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12917: 	
12918: 	return "$num1:$num2";
12919:     }
12920: }
12921: 
12922: sub rndseed_64bit4 {
12923:     my ($symb,$courseid,$domain,$username)=@_;
12924:     {
12925: 	use integer;
12926: 	# strings need to be an even # of cahracters long, it it is odd the
12927:         # last characters gets thrown away
12928: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12929: 	my $symbseed=numval3($symb) << 10;
12930: 	my $namechck=unpack("%32S*",$username.' ');
12931: 	
12932: 	my $nameseed=numval3($username) << 21;
12933: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12934: 	my $courseseed=unpack("%32S*",$courseid.' ');
12935: 	
12936: 	my $num1=$symbchck+$symbseed+$namechck;
12937: 	my $num2=$nameseed+$domainseed+$courseseed;
12938: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12939: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12940: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12941: 	
12942: 	return "$num1:$num2";
12943:     }
12944: }
12945: 
12946: sub rndseed_64bit5 {
12947:     my ($symb,$courseid,$domain,$username)=@_;
12948:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12949:     return "$num1:$num2";
12950: }
12951: 
12952: sub rndseed_CODE_64bit {
12953:     my ($symb,$courseid,$domain,$username)=@_;
12954:     {
12955: 	use integer;
12956: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12957: 	my $symbseed=numval2($symb);
12958: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12959: 	my $CODEseed=numval(&getCODE());
12960: 	my $courseseed=unpack("%32S*",$courseid.' ');
12961: 	my $num1=$symbseed+$CODEchck;
12962: 	my $num2=$CODEseed+$courseseed+$symbchck;
12963: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12964: 	#&logthis("rndseed :$num1:$num2:$symb");
12965: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12966: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12967: 	return "$num1:$num2";
12968:     }
12969: }
12970: 
12971: sub rndseed_CODE_64bit4 {
12972:     my ($symb,$courseid,$domain,$username)=@_;
12973:     {
12974: 	use integer;
12975: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12976: 	my $symbseed=numval3($symb);
12977: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12978: 	my $CODEseed=numval3(&getCODE());
12979: 	my $courseseed=unpack("%32S*",$courseid.' ');
12980: 	my $num1=$symbseed+$CODEchck;
12981: 	my $num2=$CODEseed+$courseseed+$symbchck;
12982: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12983: 	#&logthis("rndseed :$num1:$num2:$symb");
12984: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12985: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12986: 	return "$num1:$num2";
12987:     }
12988: }
12989: 
12990: sub rndseed_CODE_64bit5 {
12991:     my ($symb,$courseid,$domain,$username)=@_;
12992:     my $code = &getCODE();
12993:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
12994:     return "$num1:$num2";
12995: }
12996: 
12997: sub setup_random_from_rndseed {
12998:     my ($rndseed)=@_;
12999:     if ($rndseed =~/([,:])/) {
13000:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13001:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13002:             &Math::Random::random_set_seed_from_phrase($rndseed);
13003:         } else {
13004:             &Math::Random::random_set_seed($num1,$num2);
13005:         }
13006:     } else {
13007: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13008:     }
13009: }
13010: 
13011: sub latest_receipt_algorithm_id {
13012:     return 'receipt3';
13013: }
13014: 
13015: sub recunique {
13016:     my $fucourseid=shift;
13017:     my $unique;
13018:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13019: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13020: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13021:     } else {
13022: 	$unique=$perlvar{'lonReceipt'};
13023:     }
13024:     return unpack("%32C*",$unique);
13025: }
13026: 
13027: sub recprefix {
13028:     my $fucourseid=shift;
13029:     my $prefix;
13030:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13031: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13032: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13033:     } else {
13034: 	$prefix=$perlvar{'lonHostID'};
13035:     }
13036:     return unpack("%32C*",$prefix);
13037: }
13038: 
13039: sub ireceipt {
13040:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13041: 
13042:     my $return =&recprefix($fucourseid).'-';
13043: 
13044:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13045: 	$env{'request.state'} eq 'construct') {
13046: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13047: 	return $return;
13048:     }
13049: 
13050:     my $cuname=unpack("%32C*",$funame);
13051:     my $cudom=unpack("%32C*",$fudom);
13052:     my $cucourseid=unpack("%32C*",$fucourseid);
13053:     my $cusymb=unpack("%32C*",$fusymb);
13054:     my $cunique=&recunique($fucourseid);
13055:     my $cpart=unpack("%32S*",$part);
13056:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13057: 
13058: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13059: 			       
13060: 	$return.= ($cunique%$cuname+
13061: 		   $cunique%$cudom+
13062: 		   $cusymb%$cuname+
13063: 		   $cusymb%$cudom+
13064: 		   $cucourseid%$cuname+
13065: 		   $cucourseid%$cudom+
13066: 		   $cpart%$cuname+
13067: 		   $cpart%$cudom);
13068:     } else {
13069: 	$return.= ($cunique%$cuname+
13070: 		   $cunique%$cudom+
13071: 		   $cusymb%$cuname+
13072: 		   $cusymb%$cudom+
13073: 		   $cucourseid%$cuname+
13074: 		   $cucourseid%$cudom);
13075:     }
13076:     return $return;
13077: }
13078: 
13079: sub receipt {
13080:     my ($part)=@_;
13081:     my ($symb,$courseid,$domain,$name) = &whichuser();
13082:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13083: }
13084: 
13085: sub whichuser {
13086:     my ($passedsymb)=@_;
13087:     my ($symb,$courseid,$domain,$name,$publicuser);
13088:     if (defined($env{'form.grade_symb'})) {
13089: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13090: 	my $allowed=&allowed('vgr',$tmp_courseid);
13091: 	if (!$allowed &&
13092: 	    exists($env{'request.course.sec'}) &&
13093: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13094: 	    $allowed=&allowed('vgr',$tmp_courseid.
13095: 			      '/'.$env{'request.course.sec'});
13096: 	}
13097: 	if ($allowed) {
13098: 	    ($symb)=&get_env_multiple('form.grade_symb');
13099: 	    $courseid=$tmp_courseid;
13100: 	    ($domain)=&get_env_multiple('form.grade_domain');
13101: 	    ($name)=&get_env_multiple('form.grade_username');
13102: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13103: 	}
13104:     }
13105:     if (!$passedsymb) {
13106: 	$symb=&symbread();
13107:     } else {
13108: 	$symb=$passedsymb;
13109:     }
13110:     $courseid=$env{'request.course.id'};
13111:     $domain=$env{'user.domain'};
13112:     $name=$env{'user.name'};
13113:     if ($name eq 'public' && $domain eq 'public') {
13114: 	if (!defined($env{'form.username'})) {
13115: 	    $env{'form.username'}.=time.rand(10000000);
13116: 	}
13117: 	$name.=$env{'form.username'};
13118:     }
13119:     return ($symb,$courseid,$domain,$name,$publicuser);
13120: 
13121: }
13122: 
13123: # ------------------------------------------------------------ Serves up a file
13124: # returns either the contents of the file or 
13125: # -1 if the file doesn't exist
13126: #
13127: # if the target is a file that was uploaded via DOCS, 
13128: # a check will be made to see if a current copy exists on the local server,
13129: # if it does this will be served, otherwise a copy will be retrieved from
13130: # the home server for the course and stored in /home/httpd/html/userfiles on
13131: # the local server.   
13132: 
13133: sub getfile {
13134:     my ($file) = @_;
13135:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13136:     &repcopy($file);
13137:     return &readfile($file);
13138: }
13139: 
13140: sub repcopy_userfile {
13141:     my ($file)=@_;
13142:     my $londocroot = $perlvar{'lonDocRoot'};
13143:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13144:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13145:     my ($cdom,$cnum,$filename) = 
13146: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13147:     my $uri="/uploaded/$cdom/$cnum/$filename";
13148:     if (-e "$file") {
13149: # we already have a local copy, check it out
13150: 	my @fileinfo = stat($file);
13151: 	my $rtncode;
13152: 	my $info;
13153: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13154: 	if ($lwpresp ne 'ok') {
13155: # there is no such file anymore, even though we had a local copy
13156: 	    if ($rtncode eq '404') {
13157: 		unlink($file);
13158: 	    }
13159: 	    return -1;
13160: 	}
13161: 	if ($info < $fileinfo[9]) {
13162: # nice, the file we have is up-to-date, just say okay
13163: 	    return 'ok';
13164: 	} else {
13165: # the file is outdated, get rid of it
13166: 	    unlink($file);
13167: 	}
13168:     }
13169: # one way or the other, at this point, we don't have the file
13170: # construct the correct path for the file
13171:     my @parts = ($cdom,$cnum); 
13172:     if ($filename =~ m|^(.+)/[^/]+$|) {
13173: 	push @parts, split(/\//,$1);
13174:     }
13175:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13176:     foreach my $part (@parts) {
13177: 	$path .= '/'.$part;
13178: 	if (!-e $path) {
13179: 	    mkdir($path,0770);
13180: 	}
13181:     }
13182: # now the path exists for sure
13183: # get a user agent
13184:     my $transferfile=$file.'.in.transfer';
13185: # FIXME: this should flock
13186:     if (-e $transferfile) { return 'ok'; }
13187:     my $request;
13188:     $uri=~s/^\///;
13189:     my $homeserver = &homeserver($cnum,$cdom);
13190:     my $protocol = $protocol{$homeserver};
13191:     $protocol = 'http' if ($protocol ne 'https');
13192:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
13193:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13194: # did it work?
13195:     if ($response->is_error()) {
13196: 	unlink($transferfile);
13197: 	&logthis("Userfile repcopy failed for $uri");
13198: 	return -1;
13199:     }
13200: # worked, rename the transfer file
13201:     rename($transferfile,$file);
13202:     return 'ok';
13203: }
13204: 
13205: sub tokenwrapper {
13206:     my $uri=shift;
13207:     $uri=~s|^https?\://([^/]+)||;
13208:     $uri=~s|^/||;
13209:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13210:     my $token=$1;
13211:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13212:     if ($udom && $uname && $file) {
13213: 	$file=~s|(\?\.*)*$||;
13214:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13215:         my $homeserver = &homeserver($uname,$udom);
13216:         my $protocol = $protocol{$homeserver};
13217:         $protocol = 'http' if ($protocol ne 'https');
13218:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
13219:                (($uri=~/\?/)?'&':'?').'token='.$token.
13220:                                '&tokenissued='.$perlvar{'lonHostID'};
13221:     } else {
13222:         return '/adm/notfound.html';
13223:     }
13224: }
13225: 
13226: # call with reqtype HEAD: get last modification time
13227: # call with reqtype GET: get the file contents
13228: # Do not call this with reqtype GET for large files! It loads everything into memory
13229: #
13230: sub getuploaded {
13231:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13232:     $uri=~s/^\///;
13233:     my $homeserver = &homeserver($cnum,$cdom);
13234:     my $protocol = $protocol{$homeserver};
13235:     $protocol = 'http' if ($protocol ne 'https');
13236:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
13237:     my $request=new HTTP::Request($reqtype,$uri);
13238:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13239:     $$rtncode = $response->code;
13240:     if (! $response->is_success()) {
13241: 	return 'failed';
13242:     }      
13243:     if ($reqtype eq 'HEAD') {
13244: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13245:     } elsif ($reqtype eq 'GET') {
13246: 	$$info = $response->content;
13247:     }
13248:     return 'ok';
13249: }
13250: 
13251: sub readfile {
13252:     my $file = shift;
13253:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13254:     my $fh;
13255:     open($fh,"<",$file);
13256:     my $a='';
13257:     while (my $line = <$fh>) { $a .= $line; }
13258:     return $a;
13259: }
13260: 
13261: sub filelocation {
13262:     my ($dir,$file) = @_;
13263:     my $location;
13264:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13265: 
13266:     if ($file =~ m-^/adm/-) {
13267: 	$file=~s-^/adm/wrapper/-/-;
13268: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13269:     }
13270: 
13271:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13272:         $location = $file;
13273:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13274:         my ($udom,$uname,$filename)=
13275:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13276:         my $home=&homeserver($uname,$udom);
13277:         my $is_me=0;
13278:         my @ids=&current_machine_ids();
13279:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13280:         if ($is_me) {
13281:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13282:         } else {
13283:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13284:   	      $udom.'/'.$uname.'/'.$filename;
13285:         }
13286:     } elsif ($file =~ m-^/adm/-) {
13287: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13288:     } else {
13289:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13290:         $file=~s:^/(res|priv)/:/:;
13291:         my $space=$1;
13292:         if ( !( $file =~ m:^/:) ) {
13293:             $location = $dir. '/'.$file;
13294:         } else {
13295:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13296:         }
13297:     }
13298:     $location=~s://+:/:g; # remove duplicate /
13299:     while ($location=~m{/\.\./}) {
13300: 	if ($location =~ m{/[^/]+/\.\./}) {
13301: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13302: 	} else {
13303: 	    $location=~ s{/\.\./}{/}g;
13304: 	}
13305:     } #remove dir/..
13306:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13307:     return $location;
13308: }
13309: 
13310: sub hreflocation {
13311:     my ($dir,$file)=@_;
13312:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13313: 	$file=filelocation($dir,$file);
13314:     } elsif ($file=~m-^/adm/-) {
13315: 	$file=~s-^/adm/wrapper/-/-;
13316: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13317:     }
13318:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13319: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13320:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13321: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13322: 	        {/uploaded/$1/$2/}x;
13323:     }
13324:     if ($file=~ m{^/userfiles/}) {
13325: 	$file =~ s{^/userfiles/}{/uploaded/};
13326:     }
13327:     return $file;
13328: }
13329: 
13330: 
13331: 
13332: 
13333: 
13334: sub current_machine_domains {
13335:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13336: }
13337: 
13338: sub machine_domains {
13339:     my ($hostname) = @_;
13340:     my @domains;
13341:     my %hostname = &all_hostnames();
13342:     while( my($id, $name) = each(%hostname)) {
13343: #	&logthis("-$id-$name-$hostname-");
13344: 	if ($hostname eq $name) {
13345: 	    push(@domains,&host_domain($id));
13346: 	}
13347:     }
13348:     return @domains;
13349: }
13350: 
13351: sub current_machine_ids {
13352:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13353: }
13354: 
13355: sub machine_ids {
13356:     my ($hostname) = @_;
13357:     $hostname ||= &hostname($perlvar{'lonHostID'});
13358:     my @ids;
13359:     my %name_to_host = &all_names();
13360:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13361: 	return @{ $name_to_host{$hostname} };
13362:     }
13363:     return;
13364: }
13365: 
13366: sub additional_machine_domains {
13367:     my @domains;
13368:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13369:     while( my $line = <$fh>) {
13370:         $line =~ s/\s//g;
13371:         push(@domains,$line);
13372:     }
13373:     return @domains;
13374: }
13375: 
13376: sub default_login_domain {
13377:     my $domain = $perlvar{'lonDefDomain'};
13378:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13379:     foreach my $posdom (&current_machine_domains(),
13380:                         &additional_machine_domains()) {
13381:         if (lc($posdom) eq lc($testdomain)) {
13382:             $domain=$posdom;
13383:             last;
13384:         }
13385:     }
13386:     return $domain;
13387: }
13388: 
13389: # ------------------------------------------------------------- Declutters URLs
13390: 
13391: sub declutter {
13392:     my $thisfn=shift;
13393:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13394:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13395:         $thisfn=~s{^/home/httpd/html}{};
13396:     }
13397:     $thisfn=~s/^\///;
13398:     $thisfn=~s|^adm/wrapper/||;
13399:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13400:     $thisfn=~s/^res\///;
13401:     $thisfn=~s/^priv\///;
13402:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13403:         $thisfn=~s/\?.+$//;
13404:     }
13405:     return $thisfn;
13406: }
13407: 
13408: # ------------------------------------------------------------- Clutter up URLs
13409: 
13410: sub clutter {
13411:     my $thisfn='/'.&declutter(shift);
13412:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13413: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13414:        $thisfn='/res'.$thisfn; 
13415:     }
13416:     if ($thisfn !~m|^/adm|) {
13417: 	if ($thisfn =~ m|^/ext/|) {
13418: 	    $thisfn='/adm/wrapper'.$thisfn;
13419: 	} else {
13420: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13421: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13422: 	    if ($embstyle eq 'ssi'
13423: 		|| ($embstyle eq 'hdn')
13424: 		|| ($embstyle eq 'rat')
13425: 		|| ($embstyle eq 'prv')
13426: 		|| ($embstyle eq 'ign')) {
13427: 		#do nothing with these
13428: 	    } elsif (($embstyle eq 'img') 
13429: 		|| ($embstyle eq 'emb')
13430: 		|| ($embstyle eq 'wrp')) {
13431: 		$thisfn='/adm/wrapper'.$thisfn;
13432: 	    } elsif ($embstyle eq 'unk'
13433: 		     && $thisfn!~/\.(sequence|page)$/) {
13434: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13435: 	    } else {
13436: #		&logthis("Got a blank emb style");
13437: 	    }
13438: 	}
13439:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13440:         $thisfn='/adm/wrapper'.$thisfn;
13441:     }
13442:     return $thisfn;
13443: }
13444: 
13445: sub clutter_with_no_wrapper {
13446:     my $uri = &clutter(shift);
13447:     if ($uri =~ m-^/adm/-) {
13448: 	$uri =~ s-^/adm/wrapper/-/-;
13449: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13450:     }
13451:     return $uri;
13452: }
13453: 
13454: sub freeze_escape {
13455:     my ($value)=@_;
13456:     if (ref($value)) {
13457: 	$value=&nfreeze($value);
13458: 	return '__FROZEN__'.&escape($value);
13459:     }
13460:     return &escape($value);
13461: }
13462: 
13463: 
13464: sub thaw_unescape {
13465:     my ($value)=@_;
13466:     if ($value =~ /^__FROZEN__/) {
13467: 	substr($value,0,10,undef);
13468: 	$value=&unescape($value);
13469: 	return &thaw($value);
13470:     }
13471:     return &unescape($value);
13472: }
13473: 
13474: sub correct_line_ends {
13475:     my ($result)=@_;
13476:     $$result =~s/\r\n/\n/mg;
13477:     $$result =~s/\r/\n/mg;
13478: }
13479: # ================================================================ Main Program
13480: 
13481: sub goodbye {
13482:    &logthis("Starting Shut down");
13483: #not converted to using infrastruture and probably shouldn't be
13484:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13485: #converted
13486: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13487:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13488: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13489: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13490: #1.1 only
13491: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13492: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13493: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13494: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13495:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13496:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13497:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13498:    &flushcourselogs();
13499:    &logthis("Shutting down");
13500: }
13501: 
13502: sub get_dns {
13503:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13504:     if (!$ignore_cache) {
13505: 	my ($content,$cached)=
13506: 	    &Apache::lonnet::is_cached_new('dns',$url);
13507: 	if ($cached) {
13508: 	    &$func($content,$hashref);
13509: 	    return;
13510: 	}
13511:     }
13512: 
13513:     my %alldns;
13514:     open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13515:     foreach my $dns (<$config>) {
13516: 	next if ($dns !~ /^\^(\S*)/x);
13517:         my $line = $1;
13518:         my ($host,$protocol) = split(/:/,$line);
13519:         if ($protocol ne 'https') {
13520:             $protocol = 'http';
13521:         }
13522: 	$alldns{$host} = $protocol;
13523:     }
13524:     while (%alldns) {
13525: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13526: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13527:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13528:         delete($alldns{$dns});
13529: 	next if ($response->is_error());
13530: 	my @content = split("\n",$response->content);
13531: 	unless ($nocache) {
13532: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
13533: 	}
13534: 	&$func(\@content,$hashref);
13535: 	return;
13536:     }
13537:     close($config);
13538:     my $which = (split('/',$url))[3];
13539:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13540:     open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
13541:     my @content = <$config>;
13542:     &$func(\@content,$hashref);
13543:     return;
13544: }
13545: 
13546: # ------------------------------------------------------Get DNS checksums file
13547: sub parse_dns_checksums_tab {
13548:     my ($lines,$hashref) = @_;
13549:     my $lonhost = $perlvar{'lonHostID'};
13550:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13551:     my $loncaparev = &get_server_loncaparev($machine_dom);
13552:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13553:     my $webconfdir = '/etc/httpd/conf';
13554:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13555:         $webconfdir = '/etc/apache2';
13556:     } elsif ($distro =~ /^sles(\d+)$/) {
13557:         if ($1 >= 10) {
13558:             $webconfdir = '/etc/apache2';
13559:         }
13560:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13561:         if ($1 >= 10.0) {
13562:             $webconfdir = '/etc/apache2';
13563:         }
13564:     }
13565:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13566:     my (%chksum,%revnum);
13567:     if (ref($lines) eq 'ARRAY') {
13568:         chomp(@{$lines});
13569:         my $version = shift(@{$lines});
13570:         if ($version eq $release) {  
13571:             foreach my $line (@{$lines}) {
13572:                 my ($file,$version,$shasum) = split(/,/,$line);
13573:                 if ($file =~ m{^/etc/httpd/conf}) {
13574:                     if ($webconfdir eq '/etc/apache2') {
13575:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13576:                     }
13577:                 }
13578:                 $chksum{$file} = $shasum;
13579:                 $revnum{$file} = $version;
13580:             }
13581:             if (ref($hashref) eq 'HASH') {
13582:                 %{$hashref} = (
13583:                                 sums     => \%chksum,
13584:                                 versions => \%revnum,
13585:                               );
13586:             }
13587:         }
13588:     }
13589:     return;
13590: }
13591: 
13592: sub fetch_dns_checksums {
13593:     my %checksums;
13594:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13595:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13596:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13597:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13598:              \%checksums);
13599:     return \%checksums;
13600: }
13601: 
13602: # ------------------------------------------------------------ Read domain file
13603: {
13604:     my $loaded;
13605:     my %domain;
13606: 
13607:     sub parse_domain_tab {
13608: 	my ($lines) = @_;
13609: 	foreach my $line (@$lines) {
13610: 	    next if ($line =~ /^(\#|\s*$ )/x);
13611: 
13612: 	    chomp($line);
13613: 	    my ($name,@elements) = split(/:/,$line,9);
13614: 	    my %this_domain;
13615: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13616: 			       'lang_def', 'city', 'longi', 'lati',
13617: 			       'primary') {
13618: 		$this_domain{$field} = shift(@elements);
13619: 	    }
13620: 	    $domain{$name} = \%this_domain;
13621: 	}
13622:     }
13623: 
13624:     sub reset_domain_info {
13625: 	undef($loaded);
13626: 	undef(%domain);
13627:     }
13628: 
13629:     sub load_domain_tab {
13630: 	my ($ignore_cache,$nocache) = @_;
13631: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13632: 	my $fh;
13633: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13634: 	    my @lines = <$fh>;
13635: 	    &parse_domain_tab(\@lines);
13636: 	}
13637: 	close($fh);
13638: 	$loaded = 1;
13639:     }
13640: 
13641:     sub domain {
13642: 	&load_domain_tab() if (!$loaded);
13643: 
13644: 	my ($name,$what) = @_;
13645: 	return if ( !exists($domain{$name}) );
13646: 
13647: 	if (!$what) {
13648: 	    return $domain{$name}{'description'};
13649: 	}
13650: 	return $domain{$name}{$what};
13651:     }
13652: 
13653:     sub domain_info {
13654:         &load_domain_tab() if (!$loaded);
13655:         return %domain;
13656:     }
13657: 
13658: }
13659: 
13660: 
13661: # ------------------------------------------------------------- Read hosts file
13662: {
13663:     my %hostname;
13664:     my %hostdom;
13665:     my %libserv;
13666:     my $loaded;
13667:     my %name_to_host;
13668:     my %internetdom;
13669:     my %LC_dns_serv;
13670: 
13671:     sub parse_hosts_tab {
13672: 	my ($file) = @_;
13673: 	foreach my $configline (@$file) {
13674: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13675:             chomp($configline);
13676: 	    if ($configline =~ /^\^/) {
13677:                 if ($configline =~ /^\^([\w.\-]+)/) {
13678:                     $LC_dns_serv{$1} = 1;
13679:                 }
13680:                 next;
13681:             }
13682: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13683: 	    $name=~s/\s//g;
13684: 	    if ($id && $domain && $role && $name) {
13685:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13686:                     my $curr = $hostname{$id};
13687:                     my $skip;
13688:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13689:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13690:                             $skip = 1;
13691:                         } else {
13692:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13693:                         }
13694:                     }
13695:                     unless ($skip) {
13696:                         push(@{$name_to_host{$name}},$id);
13697:                     }
13698:                 } else {
13699:                     push(@{$name_to_host{$name}},$id);
13700:                 }
13701: 		$hostname{$id}=$name;
13702: 		$hostdom{$id}=$domain;
13703: 		if ($role eq 'library') { $libserv{$id}=$name; }
13704:                 if (defined($protocol)) {
13705:                     if ($protocol eq 'https') {
13706:                         $protocol{$id} = $protocol;
13707:                     } else {
13708:                         $protocol{$id} = 'http'; 
13709:                     }
13710:                 } else {
13711:                     $protocol{$id} = 'http';
13712:                 }
13713:                 if (defined($intdom)) {
13714:                     $internetdom{$id} = $intdom;
13715:                 }
13716: 	    }
13717: 	}
13718:     }
13719:     
13720:     sub reset_hosts_info {
13721: 	&purge_remembered();
13722: 	&reset_domain_info();
13723: 	&reset_hosts_ip_info();
13724:         undef(%internetdom);
13725: 	undef(%name_to_host);
13726: 	undef(%hostname);
13727: 	undef(%hostdom);
13728: 	undef(%libserv);
13729: 	undef($loaded);
13730:     }
13731: 
13732:     sub load_hosts_tab {
13733: 	my ($ignore_cache,$nocache) = @_;
13734: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13735: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13736: 	my @config = <$config>;
13737: 	&parse_hosts_tab(\@config);
13738: 	close($config);
13739: 	$loaded=1;
13740:     }
13741: 
13742:     sub hostname {
13743: 	&load_hosts_tab() if (!$loaded);
13744: 
13745: 	my ($lonid) = @_;
13746: 	return $hostname{$lonid};
13747:     }
13748: 
13749:     sub all_hostnames {
13750: 	&load_hosts_tab() if (!$loaded);
13751: 
13752: 	return %hostname;
13753:     }
13754: 
13755:     sub all_names {
13756:         my ($ignore_cache,$nocache) = @_;
13757: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13758: 
13759: 	return %name_to_host;
13760:     }
13761: 
13762:     sub all_host_domain {
13763:         &load_hosts_tab() if (!$loaded);
13764:         return %hostdom;
13765:     }
13766: 
13767:     sub all_host_intdom {
13768:         &load_hosts_tab() if (!$loaded);
13769:         return %internetdom;
13770:     }
13771: 
13772:     sub is_library {
13773: 	&load_hosts_tab() if (!$loaded);
13774: 
13775: 	return exists($libserv{$_[0]});
13776:     }
13777: 
13778:     sub all_library {
13779: 	&load_hosts_tab() if (!$loaded);
13780: 
13781: 	return %libserv;
13782:     }
13783: 
13784:     sub unique_library {
13785: 	#2x reverse removes all hostnames that appear more than once
13786:         my %unique = reverse &all_library();
13787:         return reverse %unique;
13788:     }
13789: 
13790:     sub get_servers {
13791: 	&load_hosts_tab() if (!$loaded);
13792: 
13793: 	my ($domain,$type) = @_;
13794: 	my %possible_hosts = ($type eq 'library') ? %libserv
13795: 	                                          : %hostname;
13796: 	my %result;
13797: 	if (ref($domain) eq 'ARRAY') {
13798: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13799: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13800: 		    $result{$host} = $hostname;
13801: 		}
13802: 	    }
13803: 	} else {
13804: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13805: 		if ($hostdom{$host} eq $domain) {
13806: 		    $result{$host} = $hostname;
13807: 		}
13808: 	    }
13809: 	}
13810: 	return %result;
13811:     }
13812: 
13813:     sub get_unique_servers {
13814:         my %unique = reverse &get_servers(@_);
13815: 	return reverse %unique;
13816:     }
13817: 
13818:     sub host_domain {
13819: 	&load_hosts_tab() if (!$loaded);
13820: 
13821: 	my ($lonid) = @_;
13822: 	return $hostdom{$lonid};
13823:     }
13824: 
13825:     sub all_domains {
13826: 	&load_hosts_tab() if (!$loaded);
13827: 
13828: 	my %seen;
13829: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13830: 	return @uniq;
13831:     }
13832: 
13833:     sub internet_dom {
13834:         &load_hosts_tab() if (!$loaded);
13835: 
13836:         my ($lonid) = @_;
13837:         return $internetdom{$lonid};
13838:     }
13839: 
13840:     sub is_LC_dns {
13841:         &load_hosts_tab() if (!$loaded);
13842: 
13843:         my ($hostname) = @_;
13844:         return exists($LC_dns_serv{$hostname});
13845:     }
13846: 
13847: }
13848: 
13849: { 
13850:     my %iphost;
13851:     my %name_to_ip;
13852:     my %lonid_to_ip;
13853: 
13854:     sub get_hosts_from_ip {
13855: 	my ($ip) = @_;
13856: 	my %iphosts = &get_iphost();
13857: 	if (ref($iphosts{$ip})) {
13858: 	    return @{$iphosts{$ip}};
13859: 	}
13860: 	return;
13861:     }
13862:     
13863:     sub reset_hosts_ip_info {
13864: 	undef(%iphost);
13865: 	undef(%name_to_ip);
13866: 	undef(%lonid_to_ip);
13867:     }
13868: 
13869:     sub get_host_ip {
13870: 	my ($lonid) = @_;
13871: 	if (exists($lonid_to_ip{$lonid})) {
13872: 	    return $lonid_to_ip{$lonid};
13873: 	}
13874: 	my $name=&hostname($lonid);
13875:    	my $ip = gethostbyname($name);
13876: 	return if (!$ip || length($ip) ne 4);
13877: 	$ip=inet_ntoa($ip);
13878: 	$name_to_ip{$name}   = $ip;
13879: 	$lonid_to_ip{$lonid} = $ip;
13880: 	return $ip;
13881:     }
13882:     
13883:     sub get_iphost {
13884: 	my ($ignore_cache,$nocache) = @_;
13885: 
13886: 	if (!$ignore_cache) {
13887: 	    if (%iphost) {
13888: 		return %iphost;
13889: 	    }
13890: 	    my ($ip_info,$cached)=
13891: 		&Apache::lonnet::is_cached_new('iphost','iphost');
13892: 	    if ($cached) {
13893: 		%iphost      = %{$ip_info->[0]};
13894: 		%name_to_ip  = %{$ip_info->[1]};
13895: 		%lonid_to_ip = %{$ip_info->[2]};
13896: 		return %iphost;
13897: 	    }
13898: 	}
13899: 
13900: 	# get yesterday's info for fallback
13901: 	my %old_name_to_ip;
13902: 	my ($ip_info,$cached)=
13903: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
13904: 	if ($cached) {
13905: 	    %old_name_to_ip = %{$ip_info->[1]};
13906: 	}
13907: 
13908: 	my %name_to_host = &all_names($ignore_cache,$nocache);
13909: 	foreach my $name (keys(%name_to_host)) {
13910: 	    my $ip;
13911: 	    if (!exists($name_to_ip{$name})) {
13912: 		$ip = gethostbyname($name);
13913: 		if (!$ip || length($ip) ne 4) {
13914: 		    if (defined($old_name_to_ip{$name})) {
13915: 			$ip = $old_name_to_ip{$name};
13916: 			&logthis("Can't find $name defaulting to old $ip");
13917: 		    } else {
13918: 			&logthis("Name $name no IP found");
13919: 			next;
13920: 		    }
13921: 		} else {
13922: 		    $ip=inet_ntoa($ip);
13923: 		}
13924: 		$name_to_ip{$name} = $ip;
13925: 	    } else {
13926: 		$ip = $name_to_ip{$name};
13927: 	    }
13928: 	    foreach my $id (@{ $name_to_host{$name} }) {
13929: 		$lonid_to_ip{$id} = $ip;
13930: 	    }
13931: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
13932: 	}
13933:         unless ($nocache) {
13934: 	    &do_cache_new('iphost','iphost',
13935: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
13936: 		          48*60*60);
13937:         }
13938: 
13939: 	return %iphost;
13940:     }
13941: 
13942:     #
13943:     #  Given a DNS returns the loncapa host name for that DNS 
13944:     # 
13945:     sub host_from_dns {
13946:         my ($dns) = @_;
13947:         my @hosts;
13948:         my $ip;
13949: 
13950:         if (exists($name_to_ip{$dns})) {
13951:             $ip = $name_to_ip{$dns};
13952:         }
13953:         if (!$ip) {
13954:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13955:             if (length($ip) == 4) { 
13956: 	        $ip   = &IO::Socket::inet_ntoa($ip);
13957:             }
13958:         }
13959:         if ($ip) {
13960: 	    @hosts = get_hosts_from_ip($ip);
13961: 	    return $hosts[0];
13962:         }
13963:         return undef;
13964:     }
13965: 
13966:     sub get_internet_names {
13967:         my ($lonid) = @_;
13968:         return if ($lonid eq '');
13969:         my ($idnref,$cached)=
13970:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
13971:         if ($cached) {
13972:             return $idnref;
13973:         }
13974:         my $ip = &get_host_ip($lonid);
13975:         my @hosts = &get_hosts_from_ip($ip);
13976:         my %iphost = &get_iphost();
13977:         my (@idns,%seen);
13978:         foreach my $id (@hosts) {
13979:             my $dom = &host_domain($id);
13980:             my $prim_id = &domain($dom,'primary');
13981:             my $prim_ip = &get_host_ip($prim_id);
13982:             next if ($seen{$prim_ip});
13983:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13984:                 foreach my $id (@{$iphost{$prim_ip}}) {
13985:                     my $intdom = &internet_dom($id);
13986:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
13987:                         push(@idns,$intdom);
13988:                     }
13989:                 }
13990:             }
13991:             $seen{$prim_ip} = 1;
13992:         }
13993:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
13994:     }
13995: 
13996: }
13997: 
13998: sub all_loncaparevs {
13999:     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);
14000: }
14001: 
14002: # ---------------------------------------------------------- Read loncaparev table
14003: {
14004:     sub load_loncaparevs { 
14005:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14006:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14007:                 while (my $configline=<$config>) {
14008:                     chomp($configline);
14009:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14010:                     $loncaparevs{$hostid}=$loncaparev;
14011:                 }
14012:                 close($config);
14013:             }
14014:         }
14015:     }
14016: }
14017: 
14018: # ---------------------------------------------------------- Read serverhostID table
14019: {
14020:     sub load_serverhomeIDs {
14021:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14022:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14023:                 while (my $configline=<$config>) {
14024:                     chomp($configline);
14025:                     my ($name,$id)=split(/:/,$configline);
14026:                     $serverhomeIDs{$name}=$id;
14027:                 }
14028:                 close($config);
14029:             }
14030:         }
14031:     }
14032: }
14033: 
14034: 
14035: BEGIN {
14036: 
14037: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14038:     unless ($readit) {
14039: {
14040:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14041:     %perlvar = (%perlvar,%{$configvars});
14042: }
14043: 
14044: 
14045: # ------------------------------------------------------ Read spare server file
14046: {
14047:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14048: 
14049:     while (my $configline=<$config>) {
14050:        chomp($configline);
14051:        if ($configline) {
14052: 	   my ($host,$type) = split(':',$configline,2);
14053: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14054: 	   push(@{ $spareid{$type} }, $host);
14055:        }
14056:     }
14057:     close($config);
14058: }
14059: # ------------------------------------------------------------ Read permissions
14060: {
14061:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14062: 
14063:     while (my $configline=<$config>) {
14064: 	chomp($configline);
14065: 	if ($configline) {
14066: 	    my ($role,$perm)=split(/ /,$configline);
14067: 	    if ($perm ne '') { $pr{$role}=$perm; }
14068: 	}
14069:     }
14070:     close($config);
14071: }
14072: 
14073: # -------------------------------------------- Read plain texts for permissions
14074: {
14075:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14076: 
14077:     while (my $configline=<$config>) {
14078: 	chomp($configline);
14079: 	if ($configline) {
14080: 	    my ($short,@plain)=split(/:/,$configline);
14081:             %{$prp{$short}} = ();
14082: 	    if (@plain > 0) {
14083:                 $prp{$short}{'std'} = $plain[0];
14084:                 for (my $i=1; $i<@plain; $i++) {
14085:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14086:                 }
14087:             }
14088: 	}
14089:     }
14090:     close($config);
14091: }
14092: 
14093: # ---------------------------------------------------------- Read package table
14094: {
14095:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14096: 
14097:     while (my $configline=<$config>) {
14098: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14099: 	chomp($configline);
14100: 	my ($short,$plain)=split(/:/,$configline);
14101: 	my ($pack,$name)=split(/\&/,$short);
14102: 	if ($plain ne '') {
14103: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14104: 	    $packagetab{$short}=$plain; 
14105: 	}
14106:     }
14107:     close($config);
14108: }
14109: 
14110: # ---------------------------------------------------------- Read loncaparev table
14111: 
14112: &load_loncaparevs();
14113: 
14114: # ---------------------------------------------------------- Read serverhostID table
14115: 
14116: &load_serverhomeIDs();
14117: 
14118: # ---------------------------------------------------------- Read releaseslist XML
14119: {
14120:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14121:     if (-e $file) {
14122:         my $parser = HTML::LCParser->new($file);
14123:         while (my $token = $parser->get_token()) {
14124:             if ($token->[0] eq 'S') {
14125:                 my $item = $token->[1];
14126:                 my $name = $token->[2]{'name'};
14127:                 my $value = $token->[2]{'value'};
14128:                 my $valuematch = $token->[2]{'valuematch'};
14129:                 my $namematch = $token->[2]{'namematch'};
14130:                 if ($item eq 'parameter') {
14131:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14132:                         my $release = $parser->get_text();
14133:                         $release =~ s/(^\s*|\s*$ )//gx;
14134:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14135:                     }
14136:                 } elsif ($item ne '' && $name ne '') {
14137:                     my $release = $parser->get_text();
14138:                     $release =~ s/(^\s*|\s*$ )//gx;
14139:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14140:                 }
14141:             }
14142:         }
14143:     }
14144: }
14145: 
14146: # ---------------------------------------------------------- Read managers table
14147: {
14148:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14149:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14150:             while (my $configline=<$config>) {
14151:                 chomp($configline);
14152:                 next if ($configline =~ /^\#/);
14153:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14154:                     $managerstab{$configline} = 1;
14155:                 }
14156:             }
14157:             close($config);
14158:         }
14159:     }
14160: }
14161: 
14162: # ------------- set up temporary directory
14163: {
14164:     $tmpdir = LONCAPA::tempdir();
14165: 
14166: }
14167: 
14168: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14169: 				'compress_threshold'=> 20_000,
14170:  			        });
14171: 
14172: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14173: $dumpcount=0;
14174: $locknum=0;
14175: 
14176: &logtouch();
14177: &logthis('<font color="yellow">INFO: Read configuration</font>');
14178: $readit=1;
14179:     {
14180: 	use integer;
14181: 	my $test=(2**32)+1;
14182: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14183: 	&logthis(" Detected 64bit platform ($_64bit)");
14184:     }
14185: }
14186: }
14187: 
14188: 1;
14189: __END__
14190: 
14191: =pod
14192: 
14193: =head1 NAME
14194: 
14195: Apache::lonnet - Subroutines to ask questions about things in the network.
14196: 
14197: =head1 SYNOPSIS
14198: 
14199: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14200: 
14201:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14202: 
14203: Common parameters:
14204: 
14205: =over 4
14206: 
14207: =item *
14208: 
14209: $uname : an internal username (if $cname expecting a course Id specifically)
14210: 
14211: =item *
14212: 
14213: $udom : a domain (if $cdom expecting a course's domain specifically)
14214: 
14215: =item *
14216: 
14217: $symb : a resource instance identifier
14218: 
14219: =item *
14220: 
14221: $namespace : the name of a .db file that contains the data needed or
14222: being set.
14223: 
14224: =back
14225: 
14226: =head1 OVERVIEW
14227: 
14228: lonnet provides subroutines which interact with the
14229: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14230: about classes, users, and resources.
14231: 
14232: For many of these objects you can also use this to store data about
14233: them or modify them in various ways.
14234: 
14235: =head2 Symbs
14236: 
14237: To identify a specific instance of a resource, LON-CAPA uses symbols
14238: or "symbs"X<symb>. These identifiers are built from the URL of the
14239: map, the resource number of the resource in the map, and the URL of
14240: the resource itself. The latter is somewhat redundant, but might help
14241: if maps change.
14242: 
14243: An example is
14244: 
14245:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14246: 
14247: The respective map entry is
14248: 
14249:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14250:   title="Problem 2">
14251:  </resource>
14252: 
14253: Symbs are used by the random number generator, as well as to store and
14254: restore data specific to a certain instance of for example a problem.
14255: 
14256: =head2 Storing And Retrieving Data
14257: 
14258: X<store()>X<cstore()>X<restore()>Three of the most important functions
14259: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14260: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14261: is is the non-critical message twin of cstore. These functions are for
14262: handlers to store a perl hash to a user's permanent data space in an
14263: easy manner, and to retrieve it again on another call. It is expected
14264: that a handler would use this once at the beginning to retrieve data,
14265: and then again once at the end to send only the new data back.
14266: 
14267: The data is stored in the user's data directory on the user's
14268: homeserver under the ID of the course.
14269: 
14270: The hash that is returned by restore will have all of the previous
14271: value for all of the elements of the hash.
14272: 
14273: Example:
14274: 
14275:  #creating a hash
14276:  my %hash;
14277:  $hash{'foo'}='bar';
14278: 
14279:  #storing it
14280:  &Apache::lonnet::cstore(\%hash);
14281: 
14282:  #changing a value
14283:  $hash{'foo'}='notbar';
14284: 
14285:  #adding a new value
14286:  $hash{'bar'}='foo';
14287:  &Apache::lonnet::cstore(\%hash);
14288: 
14289:  #retrieving the hash
14290:  my %history=&Apache::lonnet::restore();
14291: 
14292:  #print the hash
14293:  foreach my $key (sort(keys(%history))) {
14294:    print("\%history{$key} = $history{$key}");
14295:  }
14296: 
14297: Will print out:
14298: 
14299:  %history{1:foo} = bar
14300:  %history{1:keys} = foo:timestamp
14301:  %history{1:timestamp} = 990455579
14302:  %history{2:bar} = foo
14303:  %history{2:foo} = notbar
14304:  %history{2:keys} = foo:bar:timestamp
14305:  %history{2:timestamp} = 990455580
14306:  %history{bar} = foo
14307:  %history{foo} = notbar
14308:  %history{timestamp} = 990455580
14309:  %history{version} = 2
14310: 
14311: Note that the special hash entries C<keys>, C<version> and
14312: C<timestamp> were added to the hash. C<version> will be equal to the
14313: total number of versions of the data that have been stored. The
14314: C<timestamp> attribute will be the UNIX time the hash was
14315: stored. C<keys> is available in every historical section to list which
14316: keys were added or changed at a specific historical revision of a
14317: hash.
14318: 
14319: B<Warning>: do not store the hash that restore returns directly. This
14320: will cause a mess since it will restore the historical keys as if the
14321: were new keys. I.E. 1:foo will become 1:1:foo etc.
14322: 
14323: Calling convention:
14324: 
14325:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14326:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14327: 
14328: For more detailed information, see lonnet specific documentation.
14329: 
14330: =head1 RETURN MESSAGES
14331: 
14332: =over 4
14333: 
14334: =item * B<con_lost>: unable to contact remote host
14335: 
14336: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14337: when the connection is brought back up
14338: 
14339: =item * B<con_failed>: unable to contact remote host and unable to save message
14340: for later delivery
14341: 
14342: =item * B<error:>: an error a occurred, a description of the error follows the :
14343: 
14344: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14345: that was requested
14346: 
14347: =back
14348: 
14349: =head1 PUBLIC SUBROUTINES
14350: 
14351: =head2 Session Environment Functions
14352: 
14353: =over 4
14354: 
14355: =item * 
14356: X<appenv()>
14357: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14358: the user envirnoment file, and will be restored for each access this
14359: user makes during this session, also modifies the %env for the current
14360: process. Optional rolesarrayref - if defined contains a reference to an array
14361: of roles which are exempt from the restriction on modifying user.role entries 
14362: in the user's environment.db and in %env.    
14363: 
14364: =item *
14365: X<delenv()>
14366: B<delenv($delthis,$regexp)>: removes all items from the session
14367: environment file that begin with $delthis. If the 
14368: optional second arg - $regexp - is true, $delthis is treated as a 
14369: regular expression, otherwise \Q$delthis\E is used. 
14370: The values are also deleted from the current processes %env.
14371: 
14372: =item * get_env_multiple($name) 
14373: 
14374: gets $name from the %env hash, it seemlessly handles the cases where multiple
14375: values may be defined and end up as an array ref.
14376: 
14377: returns an array of values
14378: 
14379: =back
14380: 
14381: =head2 User Information
14382: 
14383: =over 4
14384: 
14385: =item *
14386: X<queryauthenticate()>
14387: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14388: authentication scheme
14389: 
14390: =item *
14391: X<authenticate()>
14392: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14393: authenticate user from domain's lib servers (first use the current
14394: one). C<$upass> should be the users password.
14395: $checkdefauth is optional (value is 1 if a check should be made to
14396:    authenticate user using default authentication method, and allow
14397:    account creation if username does not have account in the domain).
14398: $clientcancheckhost is optional (value is 1 if checking whether the
14399:    server can host will occur on the client side in lonauth.pm).   
14400: 
14401: =item *
14402: X<homeserver()>
14403: B<homeserver($uname,$udom)>: find the server which has
14404: the user's directory and files (there must be only one), this caches
14405: the answer, and also caches if there is a borken connection.
14406: 
14407: =item *
14408: X<idget()>
14409: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14410: a list of student/employee IDs or clicker IDs
14411: (student/employee IDs are a unique resource in a domain, there must be 
14412: only 1 ID per username, and only 1 username per ID in a specific domain).
14413: clickerIDs are not necessarily unique, as students might share clickers.
14414: (returns hash: id=>name,id=>name)
14415: 
14416: =item *
14417: X<idrget()>
14418: B<idrget($udom,@unames)>: find the IDs behind a list of
14419: usernames (returns hash: name=>id,name=>id)
14420: 
14421: =item *
14422: X<idput()>
14423: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14424: names and associated student/employee IDs or clicker IDs.
14425: 
14426: =item *
14427: X<iddel()>
14428: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14429: student/employee ID or clicker ID username look-ups from domain.
14430: The homeserver ($uhome) and namespace ($namespace) are optional.
14431: If no $uhome is provided, it will be determined usig &homeserver()
14432: for each user.  If no $namespace is provided, the default is ids.
14433: 
14434: =item *
14435: X<updateclickers()>
14436: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14437: clicker ID-to-username look-ups in clickers.db on library server.
14438: Permitted actions are add or del (i.e., add or delete). The 
14439: clickers.db contains clickerID as keys (escaped), and each corresponding
14440: value is an escaped comma-separated list of usernames (for whom the
14441: library server is the homeserver), who registered that particular ID.
14442: If $critical is true, the update will be sent via &critical, otherwise
14443: &reply() will be used.
14444: 
14445: =item *
14446: X<rolesinit()>
14447: B<rolesinit($udom,$username)>: get user privileges.
14448: returns user role, first access and timer interval hashes
14449: 
14450: =item *
14451: X<privileged()>
14452: B<privileged($username,$domain)>: returns a true if user has a
14453: privileged and active role (i.e. su or dc), false otherwise.
14454: 
14455: =item *
14456: X<getsection()>
14457: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14458: course $cname, return section name/number or '' for "not in course"
14459: and '-1' for "no section"
14460: 
14461: =item *
14462: X<userenvironment()>
14463: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14464: passed in @what from the requested user's environment, returns a hash
14465: 
14466: =item * 
14467: X<userlog_query()>
14468: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14469: activity.log file. %filters defines filters applied when parsing the
14470: log file. These can be start or end timestamps, or the type of action
14471: - log to look for Login or Logout events, check for Checkin or
14472: Checkout, role for role selection. The response is in the form
14473: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14474: escaped strings of the action recorded in the activity.log file.
14475: 
14476: =back
14477: 
14478: =head2 User Roles
14479: 
14480: =over 4
14481: 
14482: =item *
14483: 
14484: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14485: returns codes for allowed actions.
14486: 
14487: The first argument is required, all others are optional.
14488: 
14489: $priv is the privilege being checked.
14490: $uri contains additional information about what is being checked for access (e.g.,
14491: URL, course ID etc.). 
14492: $symb is the unique resource instance identifier in a course; if needed,
14493: but not provided, it will be retrieved via a call to &symbread(). 
14494: $role is the role for which a priv is being checked (only used if priv is evb). 
14495: $clientip is the user's IP address (only used when checking for access to portfolio 
14496: files).
14497: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14498: prevents recursive calls to &allowed.
14499: 
14500:  F: full access
14501:  U,I,K: authentication modes (cxx only)
14502:  '': forbidden
14503:  1: user needs to choose course
14504:  2: browse allowed
14505:  A: passphrase authentication needed
14506:  B: access temporarily blocked because of a blocking event in a course.
14507: 
14508: =item *
14509: 
14510: constructaccess($url,$setpriv) : check for access to construction space URL
14511: 
14512: See if the owner domain and name in the URL match those in the
14513: expected environment.  If so, return three element list
14514: ($ownername,$ownerdomain,$ownerhome).
14515: 
14516: Otherwise return the null string.
14517: 
14518: If second argument 'setpriv' is true, it assigns the privileges,
14519: and returns the same three element list, unless the owner has
14520: blocked "ad hoc" Domain Coordinator access to the Author Space,
14521: in which case the null string is returned.
14522: 
14523: =item *
14524: 
14525: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14526: define a custom role rolename set privileges in format of lonTabs/roles.tab
14527: for system, domain, and course level. $uname and $udom are optional (current
14528: user's username and domain will be used when either of $uname or $udom are absent.
14529: 
14530: =item *
14531: 
14532: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14533: (rolesplain.tab); plain text explanation of a user role term.
14534: $type is Course (default) or Community.
14535: If $forcedefault evaluates to true, text returned will be default 
14536: text for $type. Otherwise, if this is a course, the text returned 
14537: will be a custom name for the role (if defined in the course's 
14538: environment).  If no custom name is defined the default is returned.
14539:    
14540: =item *
14541: 
14542: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14543: All arguments are optional. Returns a hash of a roles, either for
14544: co-author/assistant author roles for a user's Construction Space
14545: (default), or if $context is 'userroles', roles for the user himself,
14546: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14547: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14548: For each key, value is set to colon-separated start and end times for
14549: the role.  If no username and domain are specified, will default to
14550: current user/domain. Types, roles, and roledoms are references to arrays
14551: of role statuses (active, future or previous), roles 
14552: (e.g., cc,in, st etc.) and domains of the roles which can be used
14553: to restrict the list of roles reported. If no array ref is 
14554: provided for types, will default to return only active roles.
14555: 
14556: =item *
14557: 
14558: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14559: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14560: 
14561: Additional optional arguments are: $type (if role checking is to be restricted 
14562: to certain user status types -- previous (expired roles), active (currently
14563: available roles) or future (roles available in the future), and
14564: $hideprivileged -- if true will not report course roles for users who
14565: have active Domain Coordinator role in course's domain or in additional
14566: domains (specified in 'Domains to check for privileged users' in course
14567: environment -- set via:  Course Settings -> Classlists and staff listing).
14568: 
14569: =item *
14570: 
14571: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14572: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14573: $possdomains and $possroles are optional array refs -- to domains to check and
14574: roles to check.  If $possdomains is not specified, a dump will be done of the
14575: users' roles.db to check for a dc or su role in any domain. This can be
14576: time consuming if &privileged is called repeatedly (e.g., when displaying a
14577: classlist), so in such cases, supplying a $possdomains array is preferred, as
14578: this then allows &privileged_by_domain() to be used, which caches the identity
14579: of privileged users, eliminating the need for repeated calls to &dump().
14580: 
14581: =item *
14582: 
14583: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14584: where the outer hash keys are domains specified in the $possdomains array ref,
14585: next inner hash keys are privileged roles specified in the $roles array ref,
14586: and the innermost hash contains key = value pairs for username:domain = end:start
14587: for active or future "privileged" users with that role in that domain. To avoid
14588: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14589: innerhash are cached using priv_$role and $dom as the identifiers.
14590: 
14591: =back
14592: 
14593: =head2 User Modification
14594: 
14595: =over 4
14596: 
14597: =item *
14598: 
14599: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14600: user for the level given by URL.  Optional start and end dates (leave empty
14601: string or zero for "no date")
14602: 
14603: =item *
14604: 
14605: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14606: change a users, password, possible return values are: ok,
14607: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14608: refused
14609: 
14610: =item *
14611: 
14612: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14613: 
14614: =item *
14615: 
14616: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14617:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14618: 
14619: will update user information (firstname,middlename,lastname,generation,
14620: permanentemail), and if forceid is true, student/employee ID also.
14621: A user's institutional affiliation(s) can also be updated.
14622: User information fields will not be overwritten with empty entries 
14623: unless the field is included in the $candelete array reference.
14624: This array is included when a single user is modified via "Manage Users",
14625: or when Autoupdate.pl is run by cron in a domain.
14626: 
14627: =item *
14628: 
14629: modifystudent
14630: 
14631: modify a student's enrollment and identification information.
14632: The course id is resolved based on the current user's environment.  
14633: This means the invoking user must be a course coordinator or otherwise
14634: associated with a course.
14635: 
14636: This call is essentially a wrapper for lonnet::modifyuser and
14637: lonnet::modify_student_enrollment
14638: 
14639: Inputs: 
14640: 
14641: =over 4
14642: 
14643: =item B<$udom> Student's loncapa domain
14644: 
14645: =item B<$uname> Student's loncapa login name
14646: 
14647: =item B<$uid> Student/Employee ID
14648: 
14649: =item B<$umode> Student's authentication mode
14650: 
14651: =item B<$upass> Student's password
14652: 
14653: =item B<$first> Student's first name
14654: 
14655: =item B<$middle> Student's middle name
14656: 
14657: =item B<$last> Student's last name
14658: 
14659: =item B<$gene> Student's generation
14660: 
14661: =item B<$usec> Student's section in course
14662: 
14663: =item B<$end> Unix time of the roles expiration
14664: 
14665: =item B<$start> Unix time of the roles start date
14666: 
14667: =item B<$forceid> If defined, allow $uid to be changed
14668: 
14669: =item B<$desiredhome> server to use as home server for student
14670: 
14671: =item B<$email> Student's permanent e-mail address
14672: 
14673: =item B<$type> Type of enrollment (auto or manual)
14674: 
14675: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14676: 
14677: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14678: 
14679: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14680: 
14681: =item B<$context> role change context (shown in User Management Logs display in a course)
14682: 
14683: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14684: 
14685: =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.
14686: 
14687: =back
14688: 
14689: =item *
14690: 
14691: modify_student_enrollment
14692: 
14693: Change a student's enrollment status in a class.  The environment variable
14694: 'role.request.course' must be defined for this function to proceed.
14695: 
14696: Inputs:
14697: 
14698: =over 4
14699: 
14700: =item $udom, student's domain
14701: 
14702: =item $uname, student's name
14703: 
14704: =item $uid, student's user id
14705: 
14706: =item $first, student's first name
14707: 
14708: =item $middle
14709: 
14710: =item $last
14711: 
14712: =item $gene
14713: 
14714: =item $usec
14715: 
14716: =item $end
14717: 
14718: =item $start
14719: 
14720: =item $type
14721: 
14722: =item $locktype
14723: 
14724: =item $cid
14725: 
14726: =item $selfenroll
14727: 
14728: =item $context
14729: 
14730: =item $credits, number of credits student will earn from this class
14731: 
14732: =item $instsec, institutional course section code for student
14733: 
14734: =back
14735: 
14736: 
14737: =item *
14738: 
14739: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14740: custom role; give a custom role to a user for the level given by URL.  Specify
14741: name and domain of role author, and role name
14742: 
14743: =item *
14744: 
14745: revokerole($udom,$uname,$url,$role) : revoke a role for url
14746: 
14747: =item *
14748: 
14749: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14750: 
14751: =back
14752: 
14753: =head2 Course Infomation
14754: 
14755: =over 4
14756: 
14757: =item *
14758: 
14759: coursedescription($courseid,$options) : returns a hash of information about the
14760: specified course id, including all environment settings for the
14761: course, the description of the course will be in the hash under the
14762: key 'description'
14763: 
14764: $options is an optional parameter that if supplied is a hash reference that controls
14765: what how this function works.  It has the following key/values:
14766: 
14767: =over 4
14768: 
14769: =item freshen_cache
14770: 
14771: If defined, and the environment cache for the course is valid, it is 
14772: returned in the returned hash.
14773: 
14774: =item one_time
14775: 
14776: If defined, the last cache time is set to _now_
14777: 
14778: =item user
14779: 
14780: If defined, the supplied username is used instead of the current user.
14781: 
14782: 
14783: =back
14784: 
14785: =item *
14786: 
14787: resdata($name,$domain,$type,@which) : request for current parameter
14788: setting for a specific $type, where $type is either 'course' or 'user',
14789: @what should be a list of parameters to ask about. This routine caches
14790: answers for 10 minutes.
14791: 
14792: =item *
14793: 
14794: get_courseresdata($courseid, $domain) : dump the entire course resource
14795: data base, returning a hash that is keyed by the resource name and has
14796: values that are the resource value.  I believe that the timestamps and
14797: versions are also returned.
14798: 
14799: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14800: supplemental content area. This routine caches the number of files for 
14801: 10 minutes.
14802: 
14803: =back
14804: 
14805: =head2 Course Modification
14806: 
14807: =over 4
14808: 
14809: =item *
14810: 
14811: writecoursepref($courseid,%prefs) : write preferences (environment
14812: database) for a course
14813: 
14814: =item *
14815: 
14816: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14817: 
14818: =item *
14819: 
14820: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14821: 
14822: =item *
14823: 
14824: is_course($courseid), is_course($cdom, $cnum)
14825: 
14826: Accepts either a combined $courseid (in the form of domain_courseid) or the
14827: two component version $cdom, $cnum. It checks if the specified course exists.
14828: 
14829: Returns:
14830:     undef if the course doesn't exist, otherwise
14831:     in scalar context the combined courseid.
14832:     in list context the two components of the course identifier, domain and 
14833:     courseid.    
14834: 
14835: =back
14836: 
14837: =head2 Resource Subroutines
14838: 
14839: =over 4
14840: 
14841: =item *
14842: 
14843: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14844: 
14845: =item *
14846: 
14847: repcopy($filename) : subscribes to the requested file, and attempts to
14848: replicate from the owning library server, Might return
14849: 'unavailable', 'not_found', 'forbidden', 'ok', or
14850: 'bad_request', also attempts to grab the metadata for the
14851: resource. Expects the local filesystem pathname
14852: (/home/httpd/html/res/....)
14853: 
14854: =back
14855: 
14856: =head2 Resource Information
14857: 
14858: =over 4
14859: 
14860: =item *
14861: 
14862: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14863: and returns the value of a variety of different possible values,
14864: $varname should be a request string, and the other parameters can be
14865: used to specify who and what one is asking about. Ordinarily, $cid 
14866: does not need to be specified, as it is retrived from 
14867: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14868: within lonuserstate::loadmap() when initializing a course, before
14869: $env{'request.course.id'} has been set, so it needs to be provided
14870: in that one case.
14871: 
14872: Possible values for $varname are environment.lastname (or other item
14873: from the envirnment hash), user.name (or someother aspect about the
14874: user), resource.0.maxtries (or some other part and parameter of a
14875: resource)
14876: 
14877: =item *
14878: 
14879: directcondval($number) : get current value of a condition; reads from a state
14880: string
14881: 
14882: =item *
14883: 
14884: condval($condidx) : value of condition index based on state
14885: 
14886: =item *
14887: 
14888: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
14889: resource's metadata, $what should be either a specific key, or either
14890: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14891: packages that this resource currently uses, the last 3 arguments are 
14892: only used internally for recursive metadata.
14893: 
14894: the toolsymb is only used where the uri is for an external tool (for which
14895: the uri as well as the symb are guaranteed to be unique).
14896: 
14897: this function automatically caches all requests except any made recursively
14898: to retrieve a list of metadata keys for an imported library file ($liburi is 
14899: defined).
14900: 
14901: =item *
14902: 
14903: metadata_query($query,$custom,$customshow) : make a metadata query against the
14904: network of library servers; returns file handle of where SQL and regex results
14905: will be stored for query
14906: 
14907: =item *
14908: 
14909: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
14910: return symbolic list entry (all arguments optional). 
14911: 
14912: Args: filename is the filename (including path) for the file for which a symb 
14913: is required; donotrecurse, if true will prevent calls to allowed() being made 
14914: to check access status if more than one resource was found in the bighash 
14915: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
14916: a randompick); ignorecachednull, if true will prevent a symb of '' being 
14917: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14918: cause possible symbs to be checked to determine if they are subject to content
14919: blocking, if so they will not be included as possible symbs; possibles is a
14920: ref to a hash, which, as a side effect, will be populated with all possible 
14921: symbs (content blocking not tested).
14922:  
14923: returns the data handle
14924: 
14925: =item *
14926: 
14927: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14928: and is a possible symb for the URL in $thisfn, and if is an encrypted
14929: resource that the user accessed using /enc/ returns a 1 on success, 0
14930: on failure, user must be in a course, as it assumes the existence of
14931: the course initial hash, and uses $env('request.course.id'}.  The third
14932: arg is an optional reference to a scalar.  If this arg is passed in the 
14933: call to symbverify, it will be set to 1 if the symb has been set to be 
14934: encrypted; otherwise it will be null.  
14935: 
14936: =item *
14937: 
14938: symbclean($symb) : removes versions numbers from a symb, returns the
14939: cleaned symb
14940: 
14941: =item *
14942: 
14943: is_on_map($uri) : checks if the $uri is somewhere on the current
14944: course map, user must be in a course for it to work.
14945: 
14946: =item *
14947: 
14948: numval($salt) : return random seed value (addend for rndseed)
14949: 
14950: =item *
14951: 
14952: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14953: a random seed, all arguments are optional, if they aren't sent it uses the
14954: environment to derive them. Note: if symb isn't sent and it can't get one
14955: from &symbread it will use the current time as its return value
14956: 
14957: =item *
14958: 
14959: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14960: unfakeable, receipt
14961: 
14962: =item *
14963: 
14964: receipt() : API to ireceipt working off of env values; given out to users
14965: 
14966: =item *
14967: 
14968: countacc($url) : count the number of accesses to a given URL
14969: 
14970: =item *
14971: 
14972: 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
14973: 
14974: =item *
14975: 
14976: 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)
14977: 
14978: =item *
14979: 
14980: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
14981: 
14982: =item *
14983: 
14984: devalidate($symb) : devalidate temporary spreadsheet calculations,
14985: forcing spreadsheet to reevaluate the resource scores next time.
14986: 
14987: =item * 
14988: 
14989: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14990: when viewing in course context.
14991: 
14992:  input: six args -- filename (decluttered), course number, course domain,
14993:                     url, symb (if registered) and group (if this is a 
14994:                     group item -- e.g., bulletin board, group page etc.).
14995: 
14996:  output: array of five scalars --
14997:          $cfile -- url for file editing if editable on current server
14998:          $home -- homeserver of resource (i.e., for author if published,
14999:                                           or course if uploaded.).
15000:          $switchserver --  1 if server switch will be needed.
15001:          $forceedit -- 1 if icon/link should be to go to edit mode 
15002:          $forceview -- 1 if icon/link should be to go to view mode
15003: 
15004: =item *
15005: 
15006: is_course_upload($file,$cnum,$cdom)
15007: 
15008: Used in course context to determine if current file was uploaded to 
15009: the course (i.e., would be found in /userfiles/docs on the course's 
15010: homeserver.
15011: 
15012:   input: 3 args -- filename (decluttered), course number and course domain.
15013:   output: boolean -- 1 if file was uploaded.
15014: 
15015: =back
15016: 
15017: =head2 Storing/Retreiving Data
15018: 
15019: =over 4
15020: 
15021: =item *
15022: 
15023: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15024: permanently for this url; hashref needs to be given and should be a \%hashname;
15025: the remaining args aren't required and if they aren't passed or are '' they will
15026: be derived from the env (with the exception of $laststore, which is an 
15027: optional arg used when a user's submission is stored in grading).
15028: $laststore is $version=$timestamp, where $version is the most recent version
15029: number retrieved for the corresponding $symb in the $namespace db file, and
15030: $timestamp is the timestamp for that transaction (UNIX time).
15031: $laststore is currently only passed when cstore() is called by 
15032: structuretags::finalize_storage().
15033: 
15034: =item *
15035: 
15036: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15037: but uses critical subroutine
15038: 
15039: =item *
15040: 
15041: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15042: all args are optional
15043: 
15044: =item *
15045: 
15046: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15047: dumps the complete (or key matching regexp) namespace into a hash
15048: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15049: normally &store()ed into
15050: 
15051: $range should be either an integer '100' (give me the first 100
15052:                                            matching records)
15053:               or be  two integers sperated by a - with no spaces
15054:                  '30-50' (give me the 30th through the 50th matching
15055:                           records)
15056: 
15057: 
15058: =item *
15059: 
15060: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15061: replaces a &store() version of data with a replacement set of data
15062: for a particular resource in a namespace passed in the $storehash hash 
15063: reference. If $tolog is true, the transaction is logged in the courselog
15064: with an action=PUTSTORE.
15065: 
15066: =item *
15067: 
15068: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15069: works very similar to store/cstore, but all data is stored in a
15070: temporary location and can be reset using tmpreset, $storehash should
15071: be a hash reference, returns nothing on success
15072: 
15073: =item *
15074: 
15075: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15076: similar to restore, but all data is stored in a temporary location and
15077: can be reset using tmpreset. Returns a hash of values on success,
15078: error string otherwise.
15079: 
15080: =item *
15081: 
15082: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15083: deltes all keys for $symb form the temporary storage hash.
15084: 
15085: =item *
15086: 
15087: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15088: reference filled in from namesp ($udom and $uname are optional)
15089: 
15090: =item *
15091: 
15092: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15093: namesp ($udom and $uname are optional)
15094: 
15095: =item *
15096: 
15097: dump($namespace,$udom,$uname,$regexp,$range) : 
15098: dumps the complete (or key matching regexp) namespace into a hash
15099: ($udom, $uname, $regexp, $range are optional)
15100: 
15101: $range should be either an integer '100' (give me the first 100
15102:                                            matching records)
15103:               or be  two integers sperated by a - with no spaces
15104:                  '30-50' (give me the 30th through the 50th matching
15105:                           records)
15106: =item *
15107: 
15108: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15109: $store can be a scalar, an array reference, or if the amount to be 
15110: incremented is > 1, a hash reference.
15111: 
15112: ($udom and $uname are optional)
15113: 
15114: =item *
15115: 
15116: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15117: ($udom and $uname are optional)
15118: 
15119: =item *
15120: 
15121: cput($namespace,$storehash,$udom,$uname) : critical put
15122: ($udom and $uname are optional)
15123: 
15124: =item *
15125: 
15126: newput($namespace,$storehash,$udom,$uname) :
15127: 
15128: Attempts to store the items in the $storehash, but only if they don't
15129: currently exist, if this succeeds you can be certain that you have 
15130: successfully created a new key value pair in the $namespace db.
15131: 
15132: 
15133: Args:
15134:  $namespace: name of database to store values to
15135:  $storehash: hashref to store to the db
15136:  $udom: (optional) domain of user containing the db
15137:  $uname: (optional) name of user caontaining the db
15138: 
15139: Returns:
15140:  'ok' -> succeeded in storing all keys of $storehash
15141:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15142:                         least <key> already existed in the db (other
15143:                         requested keys may also already exist)
15144:  'error: <msg>' -> unable to tie the DB or other error occurred
15145:  'con_lost' -> unable to contact request server
15146:  'refused' -> action was not allowed by remote machine
15147: 
15148: 
15149: =item *
15150: 
15151: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15152: reference filled in from namesp (encrypts the return communication)
15153: ($udom and $uname are optional)
15154: 
15155: =item *
15156: 
15157: log($udom,$name,$home,$message) : write to permanent log for user; use
15158: critical subroutine
15159: 
15160: =item *
15161: 
15162: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15163: array reference filled in from namespace found in domain level on either
15164: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15165: 
15166: =item *
15167: 
15168: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15169: domain level either on specified domain server ($uhome) or primary domain 
15170: server ($udom and $uhome are optional)
15171: 
15172: =item * 
15173: 
15174: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15175: for: authentication, language, quotas, timezone, date locale, and portal URL in
15176: the target domain.
15177: 
15178: May also include additional key => value pairs for the following groups:
15179: 
15180: =over
15181: 
15182: =item
15183: disk quotas (MB allocated by default to portfolios and authoring spaces).
15184: 
15185: =over
15186: 
15187: =item defaultquota, authorquota
15188: 
15189: =back
15190: 
15191: =item
15192: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15193: portfolio for users).
15194: 
15195: =over
15196: 
15197: =item
15198: aboutme, blog, webdav, portfolio
15199: 
15200: =back
15201: 
15202: =item
15203: requestcourses: ability to request courses, and how requests are processed.
15204: 
15205: =over
15206: 
15207: =item
15208: official, unofficial, community, textbook, placement
15209: 
15210: =back
15211: 
15212: =item
15213: inststatus: types of institutional affiliation, and order in which they are displayed.
15214: 
15215: =over
15216: 
15217: =item
15218: inststatustypes, inststatusorder, inststatusguest
15219: 
15220: =back
15221: 
15222: =item
15223: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15224: for course's uploaded content.
15225: 
15226: =over
15227: 
15228: =item
15229: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15230: communityquota, textbookquota, placementquota
15231: 
15232: =back
15233: 
15234: =item
15235: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15236: on your servers.
15237: 
15238: =over
15239: 
15240: =item 
15241: remotesessions, hostedsessions
15242: 
15243: =back
15244: 
15245: =back
15246: 
15247: In cases where a domain coordinator has never used the "Set Domain Configuration"
15248: utility to create a configuration.db file on a domain's primary library server 
15249: only the following domain defaults: auth_def, auth_arg_def, lang_def
15250: -- corresponding values are authentication type (internal, krb4, krb5,
15251: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15252: will be available. Values are retrieved from cache (if current), unless the
15253: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15254: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15255: 
15256: Typical usage:
15257: 
15258: %domdefaults = &get_domain_defaults($target_domain);
15259: 
15260: =back
15261: 
15262: =head2 Network Status Functions
15263: 
15264: =over 4
15265: 
15266: =item *
15267: 
15268: dirlist() : return directory list based on URI (first arg).
15269: 
15270: Inputs: 1 required, 5 optional.
15271: 
15272: =over
15273: 
15274: =item 
15275: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15276: 
15277: =item
15278: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15279: 
15280: =item
15281: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15282: 
15283: =item
15284: $getpropath - boolean: 1 if prepend path using &propath(). 
15285: 
15286: =item
15287: $getuserdir - boolean: 1 if prepend path for "userfiles".
15288: 
15289: =item 
15290: $alternateRoot - path to prepend in place of path from $uri.
15291: 
15292: =back
15293: 
15294: Returns: Array of up to two items.
15295: 
15296: =over
15297: 
15298: a reference to an array of files/subdirectories
15299: 
15300: =over
15301: 
15302: Each element in the array of files/subdirectories is a & separated list of
15303: item name and the result of running stat on the item.  If dirlist was requested
15304: for a file instead of a directory, the item name will be ''. For a directory 
15305: listing, if the item is a metadata file, the element will end &N&M 
15306: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15307: default copyright set (1).  
15308: 
15309: =back
15310: 
15311: a scalar containing error condition (if encountered).
15312: 
15313: =over
15314: 
15315: =item 
15316: no_host (no homeserver identified for $username:$domain).
15317: 
15318: =item 
15319: no_such_host (server contacted for listing not identified as valid host).
15320: 
15321: =item 
15322: con_lost (connection to remote server failed).
15323: 
15324: =item 
15325: refused (invalid $username:$domain received on lond side).
15326: 
15327: =item 
15328: no_such_dir (directory at specified path on lond side does not exist). 
15329: 
15330: =item 
15331: empty (directory at specified path on lond side is empty).
15332: 
15333: =over
15334: 
15335: This is currently not encountered because the &ls3, &ls2, 
15336: &ls (_handler) routines on the lond side do not filter out
15337: . and .. from a directory listing. 
15338: 
15339: =back
15340: 
15341: =back
15342: 
15343: =back
15344: 
15345: =item *
15346: 
15347: spareserver() : find server with least workload from spare.tab
15348: 
15349: 
15350: =item *
15351: 
15352: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15353: if there is no corresponding loncapa host.
15354: 
15355: =back
15356: 
15357: 
15358: =head2 Apache Request
15359: 
15360: =over 4
15361: 
15362: =item *
15363: 
15364: ssi($url,%hash) : server side include, does a complete request cycle on url to
15365: localhost, posts hash
15366: 
15367: =back
15368: 
15369: =head2 Data to String to Data
15370: 
15371: =over 4
15372: 
15373: =item *
15374: 
15375: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15376: and '&' separators, supports elements that are arrayrefs and hashrefs
15377: 
15378: =item *
15379: 
15380: hashref2str($hashref) : convert a hashref into a string complete with
15381: escaping and '=' and '&' separators, supports elements that are
15382: arrayrefs and hashrefs
15383: 
15384: =item *
15385: 
15386: arrayref2str($arrayref) : convert an arrayref into a string complete
15387: with escaping and '&' separators, supports elements that are arrayrefs
15388: and hashrefs
15389: 
15390: =item *
15391: 
15392: str2hash($string) : convert string to hash using unescaping and
15393: splitting on '=' and '&', supports elements that are arrayrefs and
15394: hashrefs
15395: 
15396: =item *
15397: 
15398: str2array($string) : convert string to hash using unescaping and
15399: splitting on '&', supports elements that are arrayrefs and hashrefs
15400: 
15401: =back
15402: 
15403: =head2 Logging Routines
15404: 
15405: 
15406: These routines allow one to make log messages in the lonnet.log and
15407: lonnet.perm logfiles.
15408: 
15409: =over 4
15410: 
15411: =item *
15412: 
15413: logtouch() : make sure the logfile, lonnet.log, exists
15414: 
15415: =item *
15416: 
15417: logthis() : append message to the normal lonnet.log file, it gets
15418: preiodically rolled over and deleted.
15419: 
15420: =item *
15421: 
15422: logperm() : append a permanent message to lonnet.perm.log, this log
15423: file never gets deleted by any automated portion of the system, only
15424: messages of critical importance should go in here.
15425: 
15426: 
15427: =back
15428: 
15429: =head2 General File Helper Routines
15430: 
15431: =over 4
15432: 
15433: =item *
15434: 
15435: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15436: (a) files in /uploaded
15437:   (i) If a local copy of the file exists - 
15438:       compares modification date of local copy with last-modified date for 
15439:       definitive version stored on home server for course. If local copy is 
15440:       stale, requests a new version from the home server and stores it. 
15441:       If the original has been removed from the home server, then local copy 
15442:       is unlinked.
15443:   (ii) If local copy does not exist -
15444:       requests the file from the home server and stores it. 
15445:   
15446:   If $caller is 'uploadrep':  
15447:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15448:     for request for files originally uploaded via DOCS. 
15449:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15450:   
15451:   Otherwise:
15452:      This indicates a call from the content generation phase of the request.
15453:      -  returns the entire contents of the file or -1.
15454:      
15455: (b) files in /res
15456:    - returns the entire contents of a file or -1; 
15457:    it properly subscribes to and replicates the file if neccessary.
15458: 
15459: 
15460: =item *
15461: 
15462: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15463:                   reference
15464: 
15465: returns either a stat() list of data about the file or an empty list
15466: if the file doesn't exist or couldn't find out about it (connection
15467: problems or user unknown)
15468: 
15469: =item *
15470: 
15471: filelocation($dir,$file) : returns file system location of a file
15472: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15473: directory that relative $file lookups are to looked in ($dir of /a/dir
15474: and a file of ../bob will become /a/bob)
15475: 
15476: =item *
15477: 
15478: hreflocation($dir,$file) : returns file system location or a URL; same as
15479: filelocation except for hrefs
15480: 
15481: =item *
15482: 
15483: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15484: also removes beginning /home/httpd/html unless /priv/ follows it.
15485: 
15486: =back
15487: 
15488: =head2 Usererfile file routines (/uploaded*)
15489: 
15490: =over 4
15491: 
15492: =item *
15493: 
15494: userfileupload(): main rotine for putting a file in a user or course's
15495:                   filespace, arguments are,
15496: 
15497:  formname - required - this is the name of the element in $env where the
15498:            filename, and the contents of the file to create/modifed exist
15499:            the filename is in $env{'form.'.$formname.'.filename'} and the
15500:            contents of the file is located in $env{'form.'.$formname}
15501:  context - if coursedoc, store the file in the course of the active role
15502:              of the current user; 
15503:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15504:            if 'canceloverwrite': delete file in tmp/overwrites directory
15505:  subdir - required - subdirectory to put the file in under ../userfiles/
15506:          if undefined, it will be placed in "unknown"
15507: 
15508:  (This routine calls clean_filename() to remove any dangerous
15509:  characters from the filename, and then calls finuserfileupload() to
15510:  complete the transaction)
15511: 
15512:  returns either the url of the uploaded file (/uploaded/....) if successful
15513:  and /adm/notfound.html if unsuccessful
15514: 
15515: =item *
15516: 
15517: clean_filename(): routine for cleaing a filename up for storage in
15518:                  userfile space, argument is:
15519: 
15520:  filename - proposed filename
15521: 
15522: returns: the new clean filename
15523: 
15524: =item *
15525: 
15526: finishuserfileupload(): routine that creates and sends the file to
15527: userspace, probably shouldn't be called directly
15528: 
15529:   docuname: username or courseid of destination for the file
15530:   docudom: domain of user/course of destination for the file
15531:   formname: same as for userfileupload()
15532:   fname: filename (including subdirectories) for the file
15533:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15534:   allfiles: reference to hash used to store objects found by parser
15535:   codebase: reference to hash used for codebases of java objects found by parser
15536:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15537:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15538:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15539:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15540:   context: if 'overwrite', will move the uploaded file from its temporary location to
15541:             userfiles to facilitate overwriting a previously uploaded file with same name.
15542:   mimetype: reference to scalar to accommodate mime type determined
15543:             from File::MMagic if $parser = parse.
15544: 
15545:  returns either the url of the uploaded file (/uploaded/....) if successful
15546:  and /adm/notfound.html if unsuccessful (or an error message if context 
15547:  was 'overwrite').
15548:  
15549: 
15550: =item *
15551: 
15552: renameuserfile(): renames an existing userfile to a new name
15553: 
15554:   Args:
15555:    docuname: username or courseid of destination for the file
15556:    docudom: domain of user/course of destination for the file
15557:    old: current file name (including any subdirs under userfiles)
15558:    new: desired file name (including any subdirs under userfiles)
15559: 
15560: =item *
15561: 
15562: mkdiruserfile(): creates a directory is a userfiles dir
15563: 
15564:   Args:
15565:    docuname: username or courseid of destination for the file
15566:    docudom: domain of user/course of destination for the file
15567:    dir: dir to create (including any subdirs under userfiles)
15568: 
15569: =item *
15570: 
15571: removeuserfile(): removes a file that exists in userfiles
15572: 
15573:   Args:
15574:    docuname: username or courseid of destination for the file
15575:    docudom: domain of user/course of destination for the file
15576:    fname: filname to delete (including any subdirs under userfiles)
15577: 
15578: =item *
15579: 
15580: removeuploadedurl(): convience function for removeuserfile()
15581: 
15582:   Args:
15583:    url:  a full /uploaded/... url to delete
15584: 
15585: =item * 
15586: 
15587: get_portfile_permissions():
15588:   Args:
15589:     domain: domain of user or course contain the portfolio files
15590:     user: name of user or num of course contain the portfolio files
15591:   Returns:
15592:     hashref of a dump of the proper file_permissions.db
15593:    
15594: 
15595: =item * 
15596: 
15597: get_access_controls():
15598: 
15599: Args:
15600:   current_permissions: the hash ref returned from get_portfile_permissions()
15601:   group: (optional) the group you want the files associated with
15602:   file: (optional) the file you want access info on
15603: 
15604: Returns:
15605:     a hash (keys are file names) of hashes containing
15606:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15607:         values are XML containing access control settings (see below) 
15608: 
15609: Internal notes:
15610: 
15611:  access controls are stored in file_permissions.db as key=value pairs.
15612:     key -> path to file/file_name\0uniqueID:scope_end_start
15613:         where scope -> public,guest,course,group,domains or users.
15614:               end -> UNIX time for end of access (0 -> no end date)
15615:               start -> UNIX time for start of access
15616: 
15617:     value -> XML description of access control
15618:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15619:             <start></start>
15620:             <end></end>
15621: 
15622:             <password></password>  for scope type = guest
15623: 
15624:             <domain></domain>     for scope type = course or group
15625:             <number></number>
15626:             <roles id="">
15627:              <role></role>
15628:              <access></access>
15629:              <section></section>
15630:              <group></group>
15631:             </roles>
15632: 
15633:             <dom></dom>         for scope type = domains
15634: 
15635:             <users>             for scope type = users
15636:              <user>
15637:               <uname></uname>
15638:               <udom></udom>
15639:              </user>
15640:             </users>
15641:            </scope> 
15642:               
15643:  Access data is also aggregated for each file in an additional key=value pair:
15644:  key -> path to file/file_name\0accesscontrol 
15645:  value -> reference to hash
15646:           hash contains key = value pairs
15647:           where key = uniqueID:scope_end_start
15648:                 value = UNIX time record was last updated
15649: 
15650:           Used to improve speed of look-ups of access controls for each file.  
15651:  
15652:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15653: 
15654: =item *
15655: 
15656: modify_access_controls():
15657: 
15658: Modifies access controls for a portfolio file
15659: Args
15660: 1. file name
15661: 2. reference to hash of required changes,
15662: 3. domain
15663: 4. username
15664:   where domain,username are the domain of the portfolio owner 
15665:   (either a user or a course) 
15666: 
15667: Returns:
15668: 1. result of additions or updates ('ok' or 'error', with error message). 
15669: 2. result of deletions ('ok' or 'error', with error message).
15670: 3. reference to hash of any new or updated access controls.
15671: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15672:    key = integer (inbound ID)
15673:    value = uniqueID
15674: 
15675: =item *
15676: 
15677: get_timebased_id():
15678: 
15679: Attempts to get a unique timestamp-based suffix for use with items added to a 
15680: course via the Course Editor (e.g., folders, composite pages, 
15681: group bulletin boards).
15682: 
15683: Args: (first three required; six others optional)
15684: 
15685: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15686:    docssequence, or name of group
15687: 
15688: 2. keyid (alphanumeric): name of temporary locking key in hash,
15689:    e.g., num, boardids
15690: 
15691: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15692:    file will be named nohist_namespace.db
15693: 
15694: 4. cdom: domain of course; default is current course domain from %env
15695: 
15696: 5. cnum: course number; default is current course number from %env
15697: 
15698: 6. idtype: set to concat if an additional digit is to be appended to the 
15699:    unix timestamp to form the suffix, if the plain timestamp is already
15700:    in use.  Default is to not do this, but simply increment the unix 
15701:    timestamp by 1 until a unique key is obtained.
15702: 
15703: 7. who: holder of locking key; defaults to user:domain for user.
15704: 
15705: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15706:    retrying); default is 3.
15707: 
15708: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15709: 
15710: Returns:
15711: 
15712: 1. suffix obtained (numeric)
15713: 
15714: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15715: 
15716: 3. error: contains (localized) error message if an error occurred.
15717: 
15718: 
15719: =back
15720: 
15721: =head2 HTTP Helper Routines
15722: 
15723: =over 4
15724: 
15725: =item *
15726: 
15727: escape() : unpack non-word characters into CGI-compatible hex codes
15728: 
15729: =item *
15730: 
15731: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15732: 
15733: =back
15734: 
15735: =head1 PRIVATE SUBROUTINES
15736: 
15737: =head2 Underlying communication routines (Shouldn't call)
15738: 
15739: =over 4
15740: 
15741: =item *
15742: 
15743: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15744: 
15745: =item *
15746: 
15747: reply() : uses subreply to send a message to remote machine, logs all failures
15748: 
15749: =item *
15750: 
15751: critical() : passes a critical message to another server; if cannot
15752: get through then place message in connection buffer directory and
15753: returns con_delayed, if incapable of saving message, returns
15754: con_failed
15755: 
15756: =item *
15757: 
15758: reconlonc() : tries to reconnect lonc client processes.
15759: 
15760: =back
15761: 
15762: =head2 Resource Access Logging
15763: 
15764: =over 4
15765: 
15766: =item *
15767: 
15768: flushcourselogs() : flush (save) buffer logs and access logs
15769: 
15770: =item *
15771: 
15772: courselog($what) : save message for course in hash
15773: 
15774: =item *
15775: 
15776: courseacclog($what) : save message for course using &courselog().  Perform
15777: special processing for specific resource types (problems, exams, quizzes, etc).
15778: 
15779: =item *
15780: 
15781: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15782: as a PerlChildExitHandler
15783: 
15784: =back
15785: 
15786: =head2 Other
15787: 
15788: =over 4
15789: 
15790: =item *
15791: 
15792: symblist($mapname,%newhash) : update symbolic storage links
15793: 
15794: =back
15795: 
15796: =cut
15797: 

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