File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1384: download - view: text, annotated - select for diffs
Thu Sep 20 14:17:11 2018 UTC (5 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Slot status ignored when rendering content in grading interface for
  "View of the problem for user" and "Correct answer for user" boxes.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1384 2018/09/20 14:17:11 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: 
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 20;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_servercerts_info {
  233:     my ($lonhost,$hostname,$context) = @_;
  234:     return if ($lonhost eq '');
  235:     if ($hostname eq '') {
  236:         $hostname = &hostname($lonhost);
  237:     }
  238:     return if ($hostname eq '');
  239:     my ($rep,$uselocal);
  240:     if (grep { $_ eq $lonhost } &current_machine_ids()) {
  241:         $uselocal = 1;
  242:     }
  243:     if (($context ne 'cgi') && ($uselocal)) {
  244:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  245:         if ($distro eq '') {
  246:             $uselocal = 0;
  247:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  248:             if ($1 < 6) {
  249:                 $uselocal = 0;
  250:             }
  251:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  252:             if ($1 < 12) {
  253:                 $uselocal = 0;
  254:             }
  255:         }
  256:     }
  257:     if ($uselocal) {
  258:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  259:     } else {
  260:         $rep=&reply('servercerts',$lonhost);
  261:     }
  262:     my ($result,%returnhash);
  263:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  264:         ($rep eq 'unknown_cmd')) {
  265:         $result = $rep;
  266:     } else {
  267:         $result = 'ok';
  268:         my @pairs=split(/\&/,$rep);
  269:         foreach my $item (@pairs) {
  270:             my ($key,$value)=split(/=/,$item,2);
  271:             my $what = &unescape($key);
  272:             $returnhash{$what}=&thaw_unescape($value);
  273:         }
  274:     }
  275:     return ($result,\%returnhash);
  276: }
  277: 
  278: sub get_server_loncaparev {
  279:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  280:     if (defined($lonhost)) {
  281:         if (!defined(&hostname($lonhost))) {
  282:             undef($lonhost);
  283:         }
  284:     }
  285:     if (!defined($lonhost)) {
  286:         if (defined(&domain($dom,'primary'))) {
  287:             $lonhost=&domain($dom,'primary');
  288:             if ($lonhost eq 'no_host') {
  289:                 undef($lonhost);
  290:             }
  291:         }
  292:     }
  293:     if (defined($lonhost)) {
  294:         my $cachetime = 12*3600;
  295:         if (!$ignore_cache) {
  296:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  297:             if (defined($cached)) {
  298:                 return $loncaparev;
  299:             }
  300:         }
  301:         my ($answer,$loncaparev);
  302:         my @ids=&current_machine_ids();
  303:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  304:             $answer = $perlvar{'lonVersion'};
  305:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  306:                 $loncaparev = $1;
  307:             }
  308:         } else {
  309:             $answer = &reply('serverloncaparev',$lonhost);
  310:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  311:                 if ($caller eq 'loncron') {
  312:                     my $protocol = $protocol{$lonhost};
  313:                     $protocol = 'http' if ($protocol ne 'https');
  314:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  315:                     my $request=new HTTP::Request('GET',$url);
  316:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  317:                     unless ($response->is_error()) {
  318:                         my $content = $response->content;
  319:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  320:                             $loncaparev = $1;
  321:                         }
  322:                     }
  323:                 } else {
  324:                     $loncaparev = $loncaparevs{$lonhost};
  325:                 }
  326:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  327:                 $loncaparev = $1;
  328:             }
  329:         }
  330:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  331:     }
  332: }
  333: 
  334: sub get_server_homeID {
  335:     my ($hostname,$ignore_cache,$caller) = @_;
  336:     unless ($ignore_cache) {
  337:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  338:         if (defined($cached)) {
  339:             return $serverhomeID;
  340:         }
  341:     }
  342:     my $cachetime = 12*3600;
  343:     my $serverhomeID;
  344:     if ($caller eq 'loncron') { 
  345:         my @machine_ids = &machine_ids($hostname);
  346:         foreach my $id (@machine_ids) {
  347:             my $response = &reply('serverhomeID',$id);
  348:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  349:                 $serverhomeID = $response;
  350:                 last;
  351:             }
  352:         }
  353:         if ($serverhomeID eq '') {
  354:             $serverhomeID = $machine_ids[-1];
  355:         }
  356:     } else {
  357:         $serverhomeID = $serverhomeIDs{$hostname};
  358:     }
  359:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  360: }
  361: 
  362: sub get_remote_globals {
  363:     my ($lonhost,$whathash,$ignore_cache) = @_;
  364:     my ($result,%returnhash,%whatneeded);
  365:     if (ref($whathash) eq 'HASH') {
  366:         foreach my $what (sort(keys(%{$whathash}))) {
  367:             my $hashid = $lonhost.'-'.$what;
  368:             my ($response,$cached);
  369:             unless ($ignore_cache) {
  370:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  371:             }
  372:             if (defined($cached)) {
  373:                 $returnhash{$what} = $response;
  374:             } else {
  375:                 $whatneeded{$what} = 1;
  376:             }
  377:         }
  378:         if (keys(%whatneeded) == 0) {
  379:             $result = 'ok';
  380:         } else {
  381:             my $requested = &freeze_escape(\%whatneeded);
  382:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  383:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  384:                 ($rep eq 'unknown_cmd')) {
  385:                 $result = $rep;
  386:             } else {
  387:                 $result = 'ok';
  388:                 my @pairs=split(/\&/,$rep);
  389:                 foreach my $item (@pairs) {
  390:                     my ($key,$value)=split(/=/,$item,2);
  391:                     my $what = &unescape($key);
  392:                     my $hashid = $lonhost.'-'.$what;
  393:                     $returnhash{$what}=&thaw_unescape($value);
  394:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  395:                 }
  396:             }
  397:         }
  398:     }
  399:     return ($result,\%returnhash);
  400: }
  401: 
  402: sub remote_devalidate_cache {
  403:     my ($lonhost,$cachekeys) = @_;
  404:     my $items;
  405:     return unless (ref($cachekeys) eq 'ARRAY');
  406:     my $cachestr = join('&',@{$cachekeys});
  407:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  408:     return $response;
  409: }
  410: 
  411: # -------------------------------------------------- Non-critical communication
  412: sub subreply {
  413:     my ($cmd,$server)=@_;
  414:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  415:     #
  416:     #  With loncnew process trimming, there's a timing hole between lonc server
  417:     #  process exit and the master server picking up the listen on the AF_UNIX
  418:     #  socket.  In that time interval, a lock file will exist:
  419: 
  420:     my $lockfile=$peerfile.".lock";
  421:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  422: 	sleep(0.1);
  423:     }
  424:     # At this point, either a loncnew parent is listening or an old lonc
  425:     # or loncnew child is listening so we can connect or everything's dead.
  426:     #
  427:     #   We'll give the connection a few tries before abandoning it.  If
  428:     #   connection is not possible, we'll con_lost back to the client.
  429:     #   
  430:     my $client;
  431:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  432: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  433: 				      Type    => SOCK_STREAM,
  434: 				      Timeout => 10);
  435: 	if ($client) {
  436: 	    last;		# Connected!
  437: 	} else {
  438: 	    &create_connection(&hostname($server),$server);
  439: 	}
  440:         sleep(0.1);	# Try again later if failed connection.
  441:     }
  442:     my $answer;
  443:     if ($client) {
  444: 	print $client "sethost:$server:$cmd\n";
  445: 	$answer=<$client>;
  446: 	if (!$answer) { $answer="con_lost"; }
  447: 	chomp($answer);
  448:     } else {
  449: 	$answer = 'con_lost';	# Failed connection.
  450:     }
  451:     return $answer;
  452: }
  453: 
  454: sub reply {
  455:     my ($cmd,$server)=@_;
  456:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  457:     my $answer=subreply($cmd,$server);
  458:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  459:        &logthis("<font color=\"blue\">WARNING:".
  460:                 " $cmd to $server returned $answer</font>");
  461:     }
  462:     return $answer;
  463: }
  464: 
  465: # ----------------------------------------------------------- Send USR1 to lonc
  466: 
  467: sub reconlonc {
  468:     my ($lonid) = @_;
  469:     if ($lonid) {
  470:         my $hostname = &hostname($lonid);
  471: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  472: 	if ($hostname && -e $peerfile) {
  473: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  474: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  475: 					     Type    => SOCK_STREAM,
  476: 					     Timeout => 10);
  477: 	    if ($client) {
  478: 		print $client ("reset_retries\n");
  479: 		my $answer=<$client>;
  480: 		#reset just this one.
  481: 	    }
  482: 	}
  483: 	return;
  484:     }
  485: 
  486:     &logthis("Trying to reconnect lonc");
  487:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  488:     if (open(my $fh,"<",$loncfile)) {
  489: 	my $loncpid=<$fh>;
  490:         chomp($loncpid);
  491:         if (kill 0 => $loncpid) {
  492: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  493:             kill USR1 => $loncpid;
  494:             sleep 1;
  495:         } else {
  496: 	    &logthis(
  497:                "<font color=\"blue\">WARNING:".
  498:                " lonc at pid $loncpid not responding, giving up</font>");
  499:         }
  500:     } else {
  501: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  502:     }
  503: }
  504: 
  505: # ------------------------------------------------------ Critical communication
  506: 
  507: sub critical {
  508:     my ($cmd,$server)=@_;
  509:     unless (&hostname($server)) {
  510:         &logthis("<font color=\"blue\">WARNING:".
  511:                " Critical message to unknown server ($server)</font>");
  512:         return 'no_such_host';
  513:     }
  514:     my $answer=reply($cmd,$server);
  515:     if ($answer eq 'con_lost') {
  516: 	&reconlonc($server);
  517: 	my $answer=reply($cmd,$server);
  518:         if ($answer eq 'con_lost') {
  519:             my $now=time;
  520:             my $middlename=$cmd;
  521:             $middlename=substr($middlename,0,16);
  522:             $middlename=~s/\W//g;
  523:             my $dfilename=
  524:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  525:             $dumpcount++;
  526:             {
  527: 		my $dfh;
  528: 		if (open($dfh,">",$dfilename)) {
  529: 		    print $dfh "$cmd\n"; 
  530: 		    close($dfh);
  531: 		}
  532:             }
  533:             sleep 1;
  534:             my $wcmd='';
  535:             {
  536: 		my $dfh;
  537: 		if (open($dfh,"<",$dfilename)) {
  538: 		    $wcmd=<$dfh>; 
  539: 		    close($dfh);
  540: 		}
  541:             }
  542:             chomp($wcmd);
  543:             if ($wcmd eq $cmd) {
  544: 		&logthis("<font color=\"blue\">WARNING: ".
  545:                          "Connection buffer $dfilename: $cmd</font>");
  546:                 &logperm("D:$server:$cmd");
  547: 	        return 'con_delayed';
  548:             } else {
  549:                 &logthis("<font color=\"red\">CRITICAL:"
  550:                         ." Critical connection failed: $server $cmd</font>");
  551:                 &logperm("F:$server:$cmd");
  552:                 return 'con_failed';
  553:             }
  554:         }
  555:     }
  556:     return $answer;
  557: }
  558: 
  559: # ------------------------------------------- check if return value is an error
  560: 
  561: sub error {
  562:     my ($result) = @_;
  563:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  564: 	if ($2 == 2) { return undef; }
  565: 	return $1;
  566:     }
  567:     return undef;
  568: }
  569: 
  570: sub convert_and_load_session_env {
  571:     my ($lonidsdir,$handle)=@_;
  572:     my @profile;
  573:     {
  574: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  575: 	if (!$opened) {
  576: 	    return 0;
  577: 	}
  578: 	flock($idf,LOCK_SH);
  579: 	@profile=<$idf>;
  580: 	close($idf);
  581:     }
  582:     my %temp_env;
  583:     foreach my $line (@profile) {
  584: 	if ($line !~ m/=/) {
  585: 	    return 0;
  586: 	}
  587: 	chomp($line);
  588: 	my ($envname,$envvalue)=split(/=/,$line,2);
  589: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  590:     }
  591:     unlink("$lonidsdir/$handle.id");
  592:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  593: 	    0640)) {
  594: 	%disk_env = %temp_env;
  595: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  596: 	untie(%disk_env);
  597:     }
  598:     return 1;
  599: }
  600: 
  601: # ------------------------------------------- Transfer profile into environment
  602: my $env_loaded;
  603: sub transfer_profile_to_env {
  604:     my ($lonidsdir,$handle,$force_transfer) = @_;
  605:     if (!$force_transfer && $env_loaded) { return; } 
  606: 
  607:     if (!defined($lonidsdir)) {
  608: 	$lonidsdir = $perlvar{'lonIDsDir'};
  609:     }
  610:     if (!defined($handle)) {
  611:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  612:     }
  613: 
  614:     my $convert;
  615:     {
  616:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  617: 	if (!$opened) {
  618: 	    return;
  619: 	}
  620: 	flock($idf,LOCK_SH);
  621: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  622: 		&GDBM_READER(),0640)) {
  623: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  624: 	    untie(%disk_env);
  625: 	} else {
  626: 	    $convert = 1;
  627: 	}
  628:     }
  629:     if ($convert) {
  630: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  631: 	    &logthis("Failed to load session, or convert session.");
  632: 	}
  633:     }
  634: 
  635:     my %remove;
  636:     while ( my $envname = each(%env) ) {
  637:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  638:             if ($time < time-300) {
  639:                 $remove{$key}++;
  640:             }
  641:         }
  642:     }
  643: 
  644:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  645:     $env_loaded=1;
  646:     foreach my $expired_key (keys(%remove)) {
  647:         &delenv($expired_key);
  648:     }
  649: }
  650: 
  651: # ---------------------------------------------------- Check for valid session 
  652: sub check_for_valid_session {
  653:     my ($r,$name,$userhashref,$domref) = @_;
  654:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  655:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  656:     if ($name eq 'lonDAV') {
  657:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  658:     } else {
  659:         $lonidsdir=$r->dir_config('lonIDsDir');
  660:         if ($name eq '') {
  661:             $name = 'lonID';
  662:         }
  663:     }
  664:     if ($name eq 'lonID') {
  665:         $secure = 'lonSID';
  666:         $linkname = 'lonLinkID';
  667:         $pubname = 'lonPubID';
  668:         if (exists($cookies{$secure})) {
  669:             $lonid=$cookies{$secure};
  670:         } elsif (exists($cookies{$name})) {
  671:             $lonid=$cookies{$name};
  672:         } elsif (exists($cookies{$linkname})) {
  673:             $lonid=$cookies{$linkname};
  674:         } elsif (exists($cookies{$pubname})) {
  675:             $lonid=$cookies{$pubname};
  676:         }
  677:     } else {
  678:         $lonid=$cookies{$name};
  679:     }
  680:     return undef if (!$lonid);
  681: 
  682:     my $handle=&LONCAPA::clean_handle($lonid->value);
  683:     if (-l "$lonidsdir/$handle.id") {
  684:         my $link = readlink("$lonidsdir/$handle.id");
  685:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  686:             $handle = $1;
  687:         }
  688:     }
  689:     if (!-e "$lonidsdir/$handle.id") {
  690:         if ((ref($domref)) && ($name eq 'lonID') && 
  691:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  692:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  693:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  694:                 $$domref = $possudom;
  695:             }
  696:         }
  697:         return undef;
  698:     }
  699: 
  700:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  701:     return undef if (!$opened);
  702: 
  703:     flock($idf,LOCK_SH);
  704:     my %disk_env;
  705:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  706: 	    &GDBM_READER(),0640)) {
  707: 	return undef;	
  708:     }
  709: 
  710:     if (!defined($disk_env{'user.name'})
  711: 	|| !defined($disk_env{'user.domain'})) {
  712: 	return undef;
  713:     }
  714: 
  715:     if (ref($userhashref) eq 'HASH') {
  716:         $userhashref->{'name'} = $disk_env{'user.name'};
  717:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  718:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  719:         if ($userhashref->{'lti'}) {
  720:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  721:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  722:         }
  723:     }
  724: 
  725:     return $handle;
  726: }
  727: 
  728: sub timed_flock {
  729:     my ($file,$lock_type) = @_;
  730:     my $failed=0;
  731:     eval {
  732: 	local $SIG{__DIE__}='DEFAULT';
  733: 	local $SIG{ALRM}=sub {
  734: 	    $failed=1;
  735: 	    die("failed lock");
  736: 	};
  737: 	alarm(13);
  738: 	flock($file,$lock_type);
  739: 	alarm(0);
  740:     };
  741:     if ($failed) {
  742: 	return undef;
  743:     } else {
  744: 	return 1;
  745:     }
  746: }
  747: 
  748: # ---------------------------------------------------------- Append Environment
  749: 
  750: sub appenv {
  751:     my ($newenv,$roles) = @_;
  752:     if (ref($newenv) eq 'HASH') {
  753:         foreach my $key (keys(%{$newenv})) {
  754:             my $refused = 0;
  755: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  756:                 $refused = 1;
  757:                 if (ref($roles) eq 'ARRAY') {
  758:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  759:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  760:                         $refused = 0;
  761:                     }
  762:                 }
  763:             }
  764:             if ($refused) {
  765:                 &logthis("<font color=\"blue\">WARNING: ".
  766:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  767:                          .'</font>');
  768: 	        delete($newenv->{$key});
  769:             } else {
  770:                 $env{$key}=$newenv->{$key};
  771:             }
  772:         }
  773:         my $lonids = $perlvar{'lonIDsDir'};
  774:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  775:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  776:             if ($opened
  777: 	        && &timed_flock($env_file,LOCK_EX)
  778: 	        &&
  779: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  780: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  781: 	        while (my ($key,$value) = each(%{$newenv})) {
  782: 	            $disk_env{$key} = $value;
  783: 	        }
  784: 	        untie(%disk_env);
  785:             }
  786:         }
  787:     }
  788:     return 'ok';
  789: }
  790: # ----------------------------------------------------- Delete from Environment
  791: 
  792: sub delenv {
  793:     my ($delthis,$regexp,$roles) = @_;
  794:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  795:         my $refused = 1;
  796:         if (ref($roles) eq 'ARRAY') {
  797:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  798:             if (grep(/^\Q$role\E$/,@{$roles})) {
  799:                 $refused = 0;
  800:             }
  801:         }
  802:         if ($refused) {
  803:             &logthis("<font color=\"blue\">WARNING: ".
  804:                      "Attempt to delete from environment ".$delthis);
  805:             return 'error';
  806:         }
  807:     }
  808:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  809:     if ($opened
  810: 	&& &timed_flock($env_file,LOCK_EX)
  811: 	&&
  812: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  813: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  814: 	foreach my $key (keys(%disk_env)) {
  815: 	    if ($regexp) {
  816:                 if ($key=~/^$delthis/) {
  817:                     delete($env{$key});
  818:                     delete($disk_env{$key});
  819:                 } 
  820:             } else {
  821:                 if ($key=~/^\Q$delthis\E/) {
  822: 		    delete($env{$key});
  823: 		    delete($disk_env{$key});
  824: 	        }
  825:             }
  826: 	}
  827: 	untie(%disk_env);
  828:     }
  829:     return 'ok';
  830: }
  831: 
  832: sub get_env_multiple {
  833:     my ($name) = @_;
  834:     my @values;
  835:     if (defined($env{$name})) {
  836:         # exists is it an array
  837:         if (ref($env{$name})) {
  838:             @values=@{ $env{$name} };
  839:         } else {
  840:             $values[0]=$env{$name};
  841:         }
  842:     }
  843:     return(@values);
  844: }
  845: 
  846: # ------------------------------------------------------------------- Locking
  847: 
  848: sub set_lock {
  849:     my ($text)=@_;
  850:     $locknum++;
  851:     my $id=$$.'-'.$locknum;
  852:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  853:              'session.lock.'.$id => $text});
  854:     return $id;
  855: }
  856: 
  857: sub get_locks {
  858:     my $num=0;
  859:     my %texts=();
  860:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  861:        if ($lock=~/\w/) {
  862:           $num++;
  863:           $texts{$lock}=$env{'session.lock.'.$lock};
  864:        }
  865:    }
  866:    return ($num,%texts);
  867: }
  868: 
  869: sub remove_lock {
  870:     my ($id)=@_;
  871:     my $newlocks='';
  872:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  873:        if (($lock=~/\w/) && ($lock ne $id)) {
  874:           $newlocks.=','.$lock;
  875:        }
  876:     }
  877:     &appenv({'session.locks' => $newlocks});
  878:     &delenv('session.lock.'.$id);
  879: }
  880: 
  881: sub remove_all_locks {
  882:     my $activelocks=$env{'session.locks'};
  883:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  884:        if ($lock=~/\w/) {
  885:           &remove_lock($lock);
  886:        }
  887:     }
  888: }
  889: 
  890: 
  891: # ------------------------------------------ Find out current server userload
  892: sub userload {
  893:     my $numusers=0;
  894:     {
  895: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  896: 	my $filename;
  897: 	my $curtime=time;
  898: 	while ($filename=readdir(LONIDS)) {
  899: 	    next if ($filename eq '.' || $filename eq '..');
  900: 	    next if ($filename =~ /publicuser_\d+\.id/);
  901: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  902: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  903: 	}
  904: 	closedir(LONIDS);
  905:     }
  906:     my $userloadpercent=0;
  907:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  908:     if ($maxuserload) {
  909: 	$userloadpercent=100*$numusers/$maxuserload;
  910:     }
  911:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  912:     return $userloadpercent;
  913: }
  914: 
  915: # ------------------------------ Find server with least workload from spare.tab
  916: 
  917: sub spareserver {
  918:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  919:     my $spare_server;
  920:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  921:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  922:                                                      :  $userloadpercent;
  923:     my ($uint_dom,$remotesessions);
  924:     if (($udom ne '') && (&domain($udom) ne '')) {
  925:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  926:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  927:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  928:         $remotesessions = $udomdefaults{'remotesessions'};
  929:     }
  930:     my $spareshash = &this_host_spares($udom);
  931:     if (ref($spareshash) eq 'HASH') {
  932:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  933:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  934:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  935:                                              $try_server));
  936: 	        ($spare_server, $lowest_load) =
  937: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  938:             }
  939:         }
  940: 
  941:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  942: 
  943:         if (!$found_server) {
  944:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  945: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  946:                     next unless (&spare_can_host($udom,$uint_dom,
  947:                                                  $remotesessions,$try_server));
  948: 	            ($spare_server, $lowest_load) =
  949: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  950:                 }
  951: 	    }
  952:         }
  953:     }
  954: 
  955:     if (!$want_server_name) {
  956:         my $protocol = 'http';
  957:         if ($protocol{$spare_server} eq 'https') {
  958:             $protocol = $protocol{$spare_server};
  959:         }
  960:         if (defined($spare_server)) {
  961:             my $hostname = &hostname($spare_server);
  962:             if (defined($hostname)) {
  963: 	        $spare_server = $protocol.'://'.$hostname;
  964:             }
  965:         }
  966:     }
  967:     return $spare_server;
  968: }
  969: 
  970: sub compare_server_load {
  971:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  972: 
  973:     if ($required) {
  974:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  975:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  976:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  977:         if (($major eq '' && $minor eq '') ||
  978:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  979:             return ($spare_server,$lowest_load);
  980:         }
  981:     }
  982: 
  983:     my $loadans     = &reply('load',    $try_server);
  984:     my $userloadans = &reply('userload',$try_server);
  985: 
  986:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  987: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  988:     }
  989: 
  990:     my $load;
  991:     if ($loadans =~ /\d/) {
  992: 	if ($userloadans =~ /\d/) {
  993: 	    #both are numbers, pick the bigger one
  994: 	    $load = ($loadans > $userloadans) ? $loadans 
  995: 		                              : $userloadans;
  996: 	} else {
  997: 	    $load = $loadans;
  998: 	}
  999:     } else {
 1000: 	$load = $userloadans;
 1001:     }
 1002: 
 1003:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1004: 	$spare_server = $try_server;
 1005: 	$lowest_load  = $load;
 1006:     }
 1007:     return ($spare_server,$lowest_load);
 1008: }
 1009: 
 1010: # --------------------------- ask offload servers if user already has a session
 1011: sub find_existing_session {
 1012:     my ($udom,$uname) = @_;
 1013:     my $spareshash = &this_host_spares($udom);
 1014:     if (ref($spareshash) eq 'HASH') {
 1015:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1016:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1017:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1018:             }
 1019:         }
 1020:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1021:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1022:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1023:             }
 1024:         }
 1025:     }
 1026:     return;
 1027: }
 1028: 
 1029: # -------------------------------- ask if server already has a session for user
 1030: sub has_user_session {
 1031:     my ($lonid,$udom,$uname) = @_;
 1032:     my $result = &reply(join(':','userhassession',
 1033: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1034:     return 1 if ($result eq 'ok');
 1035: 
 1036:     return 0;
 1037: }
 1038: 
 1039: # --------- determine least loaded server in a user's domain which allows login
 1040: 
 1041: sub choose_server {
 1042:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1043:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1044:     my %servers = &get_servers($udom);
 1045:     my $lowest_load = 30000;
 1046:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1047:     if ($skiploadbal) {
 1048:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1049:         unless (defined($cached)) {
 1050:             my $cachetime = 60*60*24;
 1051:             my %domconfig =
 1052:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1053:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1054:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1055:                                            $cachetime);
 1056:             }
 1057:         }
 1058:     }
 1059:     foreach my $lonhost (keys(%servers)) {
 1060:         if ($skiploadbal) {
 1061:             if (ref($balancers) eq 'HASH') {
 1062:                 next if (exists($balancers->{$lonhost}));
 1063:             }
 1064:         }   
 1065:         my $loginvia;
 1066:         if ($checkloginvia) {
 1067:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1068:             if ($loginvia) {
 1069:                 my ($server,$path) = split(/:/,$loginvia);
 1070:                 ($login_host, $lowest_load) =
 1071:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1072:                 if ($login_host eq $server) {
 1073:                     $portal_path = $path;
 1074:                     $isredirect = 1;
 1075:                 }
 1076:             } else {
 1077:                 ($login_host, $lowest_load) =
 1078:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1079:                 if ($login_host eq $lonhost) {
 1080:                     $portal_path = '';
 1081:                     $isredirect = ''; 
 1082:                 }
 1083:             }
 1084:         } else {
 1085:             ($login_host, $lowest_load) =
 1086:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1087:         }
 1088:     }
 1089:     if ($login_host ne '') {
 1090:         $hostname = &hostname($login_host);
 1091:     }
 1092:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1093: }
 1094: 
 1095: # --------------------------------------------- Try to change a user's password
 1096: 
 1097: sub changepass {
 1098:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1099:     $currentpass = &escape($currentpass);
 1100:     $newpass     = &escape($newpass);
 1101:     my $lonhost = $perlvar{'lonHostID'};
 1102:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1103: 		       $server);
 1104:     if (! $answer) {
 1105: 	&logthis("No reply on password change request to $server ".
 1106: 		 "by $uname in domain $udom.");
 1107:     } elsif ($answer =~ "^ok") {
 1108:         &logthis("$uname in $udom successfully changed their password ".
 1109: 		 "on $server.");
 1110:     } elsif ($answer =~ "^pwchange_failure") {
 1111: 	&logthis("$uname in $udom was unable to change their password ".
 1112: 		 "on $server.  The action was blocked by either lcpasswd ".
 1113: 		 "or pwchange");
 1114:     } elsif ($answer =~ "^non_authorized") {
 1115:         &logthis("$uname in $udom did not get their password correct when ".
 1116: 		 "attempting to change it on $server.");
 1117:     } elsif ($answer =~ "^auth_mode_error") {
 1118:         &logthis("$uname in $udom attempted to change their password despite ".
 1119: 		 "not being locally or internally authenticated on $server.");
 1120:     } elsif ($answer =~ "^unknown_user") {
 1121:         &logthis("$uname in $udom attempted to change their password ".
 1122: 		 "on $server but were unable to because $server is not ".
 1123: 		 "their home server.");
 1124:     } elsif ($answer =~ "^refused") {
 1125: 	&logthis("$server refused to change $uname in $udom password because ".
 1126: 		 "it was sent an unencrypted request to change the password.");
 1127:     } elsif ($answer =~ "invalid_client") {
 1128:         &logthis("$server refused to change $uname in $udom password because ".
 1129:                  "it was a reset by e-mail originating from an invalid server.");
 1130:     }
 1131:     return $answer;
 1132: }
 1133: 
 1134: # ----------------------- Try to determine user's current authentication scheme
 1135: 
 1136: sub queryauthenticate {
 1137:     my ($uname,$udom)=@_;
 1138:     my $uhome=&homeserver($uname,$udom);
 1139:     if (!$uhome) {
 1140: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1141: 	return 'no_host';
 1142:     }
 1143:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1144:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1145: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1146:     }
 1147:     return $answer;
 1148: }
 1149: 
 1150: # --------- Try to authenticate user from domain's lib servers (first this one)
 1151: 
 1152: sub authenticate {
 1153:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1154:     $upass=&escape($upass);
 1155:     $uname= &LONCAPA::clean_username($uname);
 1156:     my $uhome=&homeserver($uname,$udom,1);
 1157:     my $newhome;
 1158:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1159: # Maybe the machine was offline and only re-appeared again recently?
 1160:         &reconlonc();
 1161: # One more
 1162: 	$uhome=&homeserver($uname,$udom,1);
 1163:         if (($uhome eq 'no_host') && $checkdefauth) {
 1164:             if (defined(&domain($udom,'primary'))) {
 1165:                 $newhome=&domain($udom,'primary');
 1166:             }
 1167:             if ($newhome ne '') {
 1168:                 $uhome = $newhome;
 1169:             }
 1170:         }
 1171: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1172: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1173: 	    return 'no_host';
 1174:         }
 1175:     }
 1176:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1177:     if ($answer eq 'authorized') {
 1178:         if ($newhome) {
 1179:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1180:             return 'no_account_on_host'; 
 1181:         } else {
 1182:             &logthis("User $uname at $udom authorized by $uhome");
 1183:             return $uhome;
 1184:         }
 1185:     }
 1186:     if ($answer eq 'non_authorized') {
 1187: 	&logthis("User $uname at $udom rejected by $uhome");
 1188: 	return 'no_host'; 
 1189:     }
 1190:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1191:     return 'no_host';
 1192: }
 1193: 
 1194: sub can_host_session {
 1195:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1196:     my $canhost = 1;
 1197:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1198:     if (ref($remotesessions) eq 'HASH') {
 1199:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1200:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1201:                 $canhost = 0;
 1202:             } else {
 1203:                 $canhost = 1;
 1204:             }
 1205:         }
 1206:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1207:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1208:                 $canhost = 1;
 1209:             } else {
 1210:                 $canhost = 0;
 1211:             }
 1212:         }
 1213:         if ($canhost) {
 1214:             if ($remotesessions->{'version'} ne '') {
 1215:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1216:                 if ($reqmajor ne '' && $reqminor ne '') {
 1217:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1218:                         my $major = $1;
 1219:                         my $minor = $2;
 1220:                         if (($major < $reqmajor ) ||
 1221:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1222:                             $canhost = 0;
 1223:                         }
 1224:                     } else {
 1225:                         $canhost = 0;
 1226:                     }
 1227:                 }
 1228:             }
 1229:         }
 1230:     }
 1231:     if ($canhost) {
 1232:         if (ref($hostedsessions) eq 'HASH') {
 1233:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1234:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1235:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1236:                 if (($uint_dom ne '') && 
 1237:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1238:                     $canhost = 0;
 1239:                 } else {
 1240:                     $canhost = 1;
 1241:                 }
 1242:             }
 1243:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1244:                 if (($uint_dom ne '') && 
 1245:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1246:                     $canhost = 1;
 1247:                 } else {
 1248:                     $canhost = 0;
 1249:                 }
 1250:             }
 1251:         }
 1252:     }
 1253:     return $canhost;
 1254: }
 1255: 
 1256: sub spare_can_host {
 1257:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1258:     my $canhost=1;
 1259:     my $try_server_hostname = &hostname($try_server);
 1260:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1261:     my $serverhomedom = &host_domain($serverhomeID);
 1262:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1263:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1264:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1265:             $canhost = 0;
 1266:         }
 1267:     }
 1268:     if (($canhost) && ($uint_dom)) {
 1269:         my @intdoms;
 1270:         my $internet_names = &get_internet_names($try_server);
 1271:         if (ref($internet_names) eq 'ARRAY') {
 1272:             @intdoms = @{$internet_names};
 1273:         }
 1274:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1275:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1276:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1277:                                          $remotesessions,
 1278:                                          $defdomdefaults{'hostedsessions'});
 1279:         }
 1280:     }
 1281:     return $canhost;
 1282: }
 1283: 
 1284: sub this_host_spares {
 1285:     my ($dom) = @_;
 1286:     my ($dom_in_use,$lonhost_in_use,$result);
 1287:     my @hosts = &current_machine_ids();
 1288:     foreach my $lonhost (@hosts) {
 1289:         if (&host_domain($lonhost) eq $dom) {
 1290:             $dom_in_use = $dom;
 1291:             $lonhost_in_use = $lonhost;
 1292:             last;
 1293:         }
 1294:     }
 1295:     if ($dom_in_use ne '') {
 1296:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1297:     }
 1298:     if (ref($result) ne 'HASH') {
 1299:         $lonhost_in_use = $perlvar{'lonHostID'};
 1300:         $dom_in_use = &host_domain($lonhost_in_use);
 1301:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1302:         if (ref($result) ne 'HASH') {
 1303:             $result = \%spareid;
 1304:         }
 1305:     }
 1306:     return $result;
 1307: }
 1308: 
 1309: sub spares_for_offload  {
 1310:     my ($dom_in_use,$lonhost_in_use) = @_;
 1311:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1312:     if (defined($cached)) {
 1313:         return $result;
 1314:     } else {
 1315:         my $cachetime = 60*60*24;
 1316:         my %domconfig =
 1317:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1318:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1319:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1320:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1321:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1322:                 }
 1323:             }
 1324:         }
 1325:     }
 1326:     return;
 1327: }
 1328: 
 1329: sub get_lonbalancer_config {
 1330:     my ($servers) = @_;
 1331:     my ($currbalancer,$currtargets);
 1332:     if (ref($servers) eq 'HASH') {
 1333:         foreach my $server (keys(%{$servers})) {
 1334:             my %what = (
 1335:                          spareid => 1,
 1336:                          perlvar => 1,
 1337:                        );
 1338:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1339:             if ($result eq 'ok') {
 1340:                 if (ref($returnhash) eq 'HASH') {
 1341:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1342:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1343:                             $currbalancer = $server;
 1344:                             $currtargets = {};
 1345:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1346:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1347:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1348:                                 }
 1349:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1350:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1351:                                 }
 1352:                             }
 1353:                             last;
 1354:                         }
 1355:                     }
 1356:                 }
 1357:             }
 1358:         }
 1359:     }
 1360:     return ($currbalancer,$currtargets);
 1361: }
 1362: 
 1363: sub check_loadbalancing {
 1364:     my ($uname,$udom,$caller) = @_;
 1365:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1366:         $rule_in_effect,$offloadto,$otherserver);
 1367:     my $lonhost = $perlvar{'lonHostID'};
 1368:     my @hosts = &current_machine_ids();
 1369:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1370:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1371:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1372:     my $serverhomedom = &host_domain($lonhost);
 1373:     my $domneedscache;
 1374:     my $cachetime = 60*60*24;
 1375: 
 1376:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1377:         $dom_in_use = $udom;
 1378:         $homeintdom = 1;
 1379:     } else {
 1380:         $dom_in_use = $serverhomedom;
 1381:     }
 1382:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1383:     unless (defined($cached)) {
 1384:         my %domconfig =
 1385:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1386:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1387:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1388:         } else {
 1389:             $domneedscache = $dom_in_use;
 1390:         }
 1391:     }
 1392:     if (ref($result) eq 'HASH') {
 1393:         ($is_balancer,$currtargets,$currrules) = 
 1394:             &check_balancer_result($result,@hosts);
 1395:         if ($is_balancer) {
 1396:             if (ref($currrules) eq 'HASH') {
 1397:                 if ($homeintdom) {
 1398:                     if ($uname ne '') {
 1399:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1400:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1401:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1402:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1403:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1404:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1405:                             }
 1406:                         }
 1407:                         if ($rule_in_effect eq '') {
 1408:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1409:                             if ($userenv{'inststatus'} ne '') {
 1410:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1411:                                 my ($othertitle,$usertypes,$types) =
 1412:                                     &Apache::loncommon::sorted_inst_types($udom);
 1413:                                 if (ref($types) eq 'ARRAY') {
 1414:                                     foreach my $type (@{$types}) {
 1415:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1416:                                             if (exists($currrules->{$type})) {
 1417:                                                 $rule_in_effect = $currrules->{$type};
 1418:                                             }
 1419:                                         }
 1420:                                     }
 1421:                                 }
 1422:                             } else {
 1423:                                 if (exists($currrules->{'default'})) {
 1424:                                     $rule_in_effect = $currrules->{'default'};
 1425:                                 }
 1426:                             }
 1427:                         }
 1428:                     } else {
 1429:                         if (exists($currrules->{'default'})) {
 1430:                             $rule_in_effect = $currrules->{'default'};
 1431:                         }
 1432:                     }
 1433:                 } else {
 1434:                     if ($currrules->{'_LC_external'} ne '') {
 1435:                         $rule_in_effect = $currrules->{'_LC_external'};
 1436:                     }
 1437:                 }
 1438:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1439:                                                        $uname,$udom);
 1440:             }
 1441:         }
 1442:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1443:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1444:         unless (defined($cached)) {
 1445:             my %domconfig =
 1446:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1447:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1448:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1449:             } else {
 1450:                 $domneedscache = $serverhomedom;
 1451:             }
 1452:         }
 1453:         if (ref($result) eq 'HASH') {
 1454:             ($is_balancer,$currtargets,$currrules) = 
 1455:                 &check_balancer_result($result,@hosts);
 1456:             if ($is_balancer) {
 1457:                 if (ref($currrules) eq 'HASH') {
 1458:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1459:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1460:                     }
 1461:                 }
 1462:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1463:                                                        $uname,$udom);
 1464:             }
 1465:         } else {
 1466:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1467:                 $is_balancer = 1;
 1468:                 $offloadto = &this_host_spares($dom_in_use);
 1469:             }
 1470:             unless (defined($cached)) {
 1471:                 $domneedscache = $serverhomedom;
 1472:             }
 1473:         }
 1474:     } else {
 1475:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1476:             $is_balancer = 1;
 1477:             $offloadto = &this_host_spares($dom_in_use);
 1478:         }
 1479:         unless (defined($cached)) {
 1480:             $domneedscache = $serverhomedom;
 1481:         }
 1482:     }
 1483:     if ($domneedscache) {
 1484:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1485:     }
 1486:     if ($is_balancer) {
 1487:         my $lowest_load = 30000;
 1488:         if (ref($offloadto) eq 'HASH') {
 1489:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1490:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1491:                     ($otherserver,$lowest_load) =
 1492:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1493:                 }
 1494:             }
 1495:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1496: 
 1497:             if (!$found_server) {
 1498:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1499:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1500:                         ($otherserver,$lowest_load) =
 1501:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1502:                     }
 1503:                 }
 1504:             }
 1505:         } elsif (ref($offloadto) eq 'ARRAY') {
 1506:             if (@{$offloadto} == 1) {
 1507:                 $otherserver = $offloadto->[0];
 1508:             } elsif (@{$offloadto} > 1) {
 1509:                 foreach my $try_server (@{$offloadto}) {
 1510:                     ($otherserver,$lowest_load) =
 1511:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1512:                 }
 1513:             }
 1514:         }
 1515:         unless ($caller eq 'login') {
 1516:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1517:                 $is_balancer = 0;
 1518:                 if ($uname ne '' && $udom ne '') {
 1519:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1520:                     
 1521:                         &appenv({'user.loadbalexempt'     => $lonhost,  
 1522:                                  'user.loadbalcheck.time' => time});
 1523:                     }
 1524:                 }
 1525:             }
 1526:         }
 1527:     }
 1528:     return ($is_balancer,$otherserver);
 1529: }
 1530: 
 1531: sub check_balancer_result {
 1532:     my ($result,@hosts) = @_;
 1533:     my ($is_balancer,$currtargets,$currrules);
 1534:     if (ref($result) eq 'HASH') {
 1535:         if ($result->{'lonhost'} ne '') {
 1536:             my $currbalancer = $result->{'lonhost'};
 1537:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1538:                 $is_balancer = 1;
 1539:                 $currtargets = $result->{'targets'};
 1540:                 $currrules = $result->{'rules'};
 1541:             }
 1542:         } else {
 1543:             foreach my $key (keys(%{$result})) {
 1544:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1545:                     (ref($result->{$key}) eq 'HASH')) {
 1546:                     $is_balancer = 1;
 1547:                     $currrules = $result->{$key}{'rules'};
 1548:                     $currtargets = $result->{$key}{'targets'};
 1549:                     last;
 1550:                 }
 1551:             }
 1552:         }
 1553:     }
 1554:     return ($is_balancer,$currtargets,$currrules);
 1555: }
 1556: 
 1557: sub get_loadbalancer_targets {
 1558:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1559:     my $offloadto;
 1560:     if ($rule_in_effect eq 'none') {
 1561:         return [$perlvar{'lonHostID'}];
 1562:     } elsif ($rule_in_effect eq '') {
 1563:         $offloadto = $currtargets;
 1564:     } else {
 1565:         if ($rule_in_effect eq 'homeserver') {
 1566:             my $homeserver = &homeserver($uname,$udom);
 1567:             if ($homeserver ne 'no_host') {
 1568:                 $offloadto = [$homeserver];
 1569:             }
 1570:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1571:             my %domconfig =
 1572:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1573:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1574:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1575:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1576:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1577:                     }
 1578:                 }
 1579:             } else {
 1580:                 my %servers = &internet_dom_servers($udom);
 1581:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1582:                 if (&hostname($remotebalancer) ne '') {
 1583:                     $offloadto = [$remotebalancer];
 1584:                 }
 1585:             }
 1586:         } elsif (&hostname($rule_in_effect) ne '') {
 1587:             $offloadto = [$rule_in_effect];
 1588:         }
 1589:     }
 1590:     return $offloadto;
 1591: }
 1592: 
 1593: sub internet_dom_servers {
 1594:     my ($dom) = @_;
 1595:     my (%uniqservers,%servers);
 1596:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1597:     my @machinedoms = &machine_domains($primaryserver);
 1598:     foreach my $mdom (@machinedoms) {
 1599:         my %currservers = %servers;
 1600:         my %server = &get_servers($mdom);
 1601:         %servers = (%currservers,%server);
 1602:     }
 1603:     my %by_hostname;
 1604:     foreach my $id (keys(%servers)) {
 1605:         push(@{$by_hostname{$servers{$id}}},$id);
 1606:     }
 1607:     foreach my $hostname (sort(keys(%by_hostname))) {
 1608:         if (@{$by_hostname{$hostname}} > 1) {
 1609:             my $match = 0;
 1610:             foreach my $id (@{$by_hostname{$hostname}}) {
 1611:                 if (&host_domain($id) eq $dom) {
 1612:                     $uniqservers{$id} = $hostname;
 1613:                     $match = 1;
 1614:                 }
 1615:             }
 1616:             unless ($match) {
 1617:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1618:             }
 1619:         } else {
 1620:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1621:         }
 1622:     }
 1623:     return %uniqservers;
 1624: }
 1625: 
 1626: sub trusted_domains {
 1627:     my ($cmdtype,$calldom) = @_;
 1628:     my ($trusted,$untrusted);
 1629:     if (&domain($calldom) eq '') {
 1630:         return ($trusted,$untrusted);
 1631:     }
 1632:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1633:         return ($trusted,$untrusted);
 1634:     }
 1635:     my $callprimary = &domain($calldom,'primary');
 1636:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1637:     if ($intcalldom eq '') {
 1638:         return ($trusted,$untrusted);
 1639:     }
 1640: 
 1641:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1642:     unless (defined($cached)) {
 1643:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1644:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1645:         $trustconfig = $domconfig{'trust'};
 1646:     }
 1647:     if (ref($trustconfig)) {
 1648:         my (%possexc,%possinc,@allexc,@allinc); 
 1649:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1650:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1651:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1652:             }
 1653:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1654:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1655:             }
 1656:         }
 1657:         if (keys(%possexc)) {
 1658:             if (keys(%possinc)) {
 1659:                 foreach my $key (sort(keys(%possexc))) {
 1660:                     next if ($key eq $intcalldom);
 1661:                     unless ($possinc{$key}) {
 1662:                         push(@allexc,$key);
 1663:                     }
 1664:                 }
 1665:             } else {
 1666:                 @allexc = sort(keys(%possexc));
 1667:             }
 1668:         }
 1669:         if (keys(%possinc)) {
 1670:             $possinc{$intcalldom} = 1;
 1671:             @allinc = sort(keys(%possinc));
 1672:         }
 1673:         if ((@allexc > 0) || (@allinc > 0)) {
 1674:             my %doms_by_intdom;
 1675:             my %allintdoms = &all_host_intdom();
 1676:             my %alldoms = &all_host_domain();
 1677:             foreach my $key (%allintdoms) {
 1678:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1679:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1680:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1681:                     }
 1682:                 } else {
 1683:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1684:                 }
 1685:             }
 1686:             foreach my $exc (@allexc) {
 1687:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1688:                     $untrusted = $doms_by_intdom{$exc};
 1689:                 }
 1690:             }
 1691:             foreach my $inc (@allinc) {
 1692:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1693:                     $trusted = $doms_by_intdom{$inc};
 1694:                 }
 1695:             }
 1696:         }
 1697:     }
 1698:     return ($trusted,$untrusted);
 1699: }
 1700: 
 1701: sub will_trust {
 1702:     my ($cmdtype,$domain,$possdom) = @_;
 1703:     return 1 if ($domain eq $possdom);
 1704:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1705:     my $willtrust; 
 1706:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1707:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1708:             $willtrust = 1;
 1709:         }
 1710:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1711:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1712:             $willtrust = 1;
 1713:         }
 1714:     } else {
 1715:         $willtrust = 1;
 1716:     }
 1717:     return $willtrust;
 1718: }
 1719: 
 1720: # ---------------------- Find the homebase for a user from domain's lib servers
 1721: 
 1722: my %homecache;
 1723: sub homeserver {
 1724:     my ($uname,$udom,$ignoreBadCache)=@_;
 1725:     my $index="$uname:$udom";
 1726: 
 1727:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1728: 
 1729:     my %servers = &get_servers($udom,'library');
 1730:     foreach my $tryserver (keys(%servers)) {
 1731:         next if ($ignoreBadCache ne 'true' && 
 1732: 		 exists($badServerCache{$tryserver}));
 1733: 
 1734: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1735: 	if ($answer eq 'found') {
 1736: 	    delete($badServerCache{$tryserver}); 
 1737: 	    return $homecache{$index}=$tryserver;
 1738: 	} elsif ($answer eq 'no_host') {
 1739: 	    $badServerCache{$tryserver}=1;
 1740: 	}
 1741:     }    
 1742:     return 'no_host';
 1743: }
 1744: 
 1745: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1746: 
 1747: sub idget {
 1748:     my ($udom,$idsref,$namespace)=@_;
 1749:     my %returnhash=();
 1750:     my @ids=(); 
 1751:     if (ref($idsref) eq 'ARRAY') {
 1752:         @ids = @{$idsref};
 1753:     } else {
 1754:         return %returnhash; 
 1755:     }
 1756:     if ($namespace eq '') {
 1757:         $namespace = 'ids';
 1758:     }
 1759:     
 1760:     my %servers = &get_servers($udom,'library');
 1761:     foreach my $tryserver (keys(%servers)) {
 1762: 	my $idlist=join('&', map { &escape($_); } @ids);
 1763: 	if ($namespace eq 'ids') {
 1764: 	    $idlist=~tr/A-Z/a-z/;
 1765: 	}
 1766: 	my $reply;
 1767: 	if ($namespace eq 'ids') {
 1768: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1769: 	} else {
 1770: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1771: 	}
 1772: 	my @answer=();
 1773: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1774: 	    @answer=split(/\&/,$reply);
 1775: 	}                    ;
 1776: 	my $i;
 1777: 	for ($i=0;$i<=$#ids;$i++) {
 1778: 	    if ($answer[$i]) {
 1779: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1780: 	    }
 1781: 	}
 1782:     }
 1783:     return %returnhash;
 1784: }
 1785: 
 1786: # ------------------------------------- Find the IDs behind a list of usernames
 1787: 
 1788: sub idrget {
 1789:     my ($udom,@unames)=@_;
 1790:     my %returnhash=();
 1791:     foreach my $uname (@unames) {
 1792:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1793:     }
 1794:     return %returnhash;
 1795: }
 1796: 
 1797: # Store away a list of names and associated student/employee IDs or clicker IDs
 1798: 
 1799: sub idput {
 1800:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1801:     my %servers=();
 1802:     my %ids=();
 1803:     my %byid = ();
 1804:     if (ref($idsref) eq 'HASH') {
 1805:         %ids=%{$idsref};
 1806:     }
 1807:     if ($namespace eq '') {
 1808:         $namespace = 'ids'; 
 1809:     }
 1810:     foreach my $uname (keys(%ids)) {
 1811: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1812:         if ($uhom eq '') {
 1813:             $uhom=&homeserver($uname,$udom);
 1814:         }
 1815:         if ($uhom ne 'no_host') {
 1816:             my $esc_unam=&escape($uname);
 1817:             if ($namespace eq 'ids') {
 1818:                 my $id=&escape($ids{$uname});
 1819:                 $id=~tr/A-Z/a-z/;
 1820:                 my $esc_unam=&escape($uname);
 1821:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1822:             } else {
 1823:                 my @currids = split(/,/,$ids{$uname});
 1824:                 foreach my $id (@currids) {
 1825:                     $byid{$uhom}{$id} .= $uname.',';
 1826:                 }
 1827:             }
 1828:         }
 1829:     }
 1830:     if ($namespace eq 'clickers') {
 1831:         foreach my $server (keys(%byid)) {
 1832:             if (ref($byid{$server}) eq 'HASH') {
 1833:                 foreach my $id (keys(%{$byid{$server}})) {
 1834:                     $byid{$server} =~ s/,$//;
 1835:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1836:                 }
 1837:             }
 1838:         }
 1839:     }
 1840:     foreach my $server (keys(%servers)) {
 1841:         $servers{$server} =~ s/\&$//;
 1842:         if ($namespace eq 'ids') {     
 1843:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1844:         } else {
 1845:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1846:         }
 1847:     }
 1848: }
 1849: 
 1850: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1851: 
 1852: sub iddel {
 1853:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1854:     my %result=();
 1855:     my %ids=();
 1856:     my %byid = ();
 1857:     if (ref($idshashref) eq 'HASH') {
 1858:         %ids=%{$idshashref};
 1859:     } else {
 1860:         return %result;
 1861:     }
 1862:     if ($namespace eq '') {
 1863:         $namespace = 'ids';
 1864:     }
 1865:     my %servers=();
 1866:     while (my ($id,$unamestr) = each(%ids)) {
 1867:         if ($namespace eq 'ids') {
 1868:             my $uhom = $uhome;
 1869:             if ($uhom eq '') { 
 1870:                 $uhom=&homeserver($unamestr,$udom);
 1871:             }
 1872:             if ($uhom ne 'no_host') {
 1873:                 $servers{$uhom}.='&'.&escape($id);
 1874:             }
 1875:          } else {
 1876:             my @curritems = split(/,/,$ids{$id});
 1877:             foreach my $uname (@curritems) {
 1878:                 my $uhom = $uhome;
 1879:                 if ($uhom eq '') {
 1880:                     $uhom=&homeserver($uname,$udom);
 1881:                 }
 1882:                 if ($uhom ne 'no_host') { 
 1883:                     $byid{$uhom}{$id} .= $uname.',';
 1884:                 }
 1885:             }
 1886:         }
 1887:     }
 1888:     if ($namespace eq 'clickers') {
 1889:         foreach my $server (keys(%byid)) {
 1890:             if (ref($byid{$server}) eq 'HASH') {
 1891:                 foreach my $id (keys(%{$byid{$server}})) {
 1892:                     $byid{$server}{$id} =~ s/,$//;
 1893:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 1894:                 }
 1895:             }
 1896:         }
 1897:     }
 1898:     foreach my $server (keys(%servers)) {
 1899:         $servers{$server} =~ s/\&$//;
 1900:         if ($namespace eq 'ids') {
 1901:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1902:         } elsif ($namespace eq 'clickers') {
 1903:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 1904:         }
 1905:     }
 1906:     return %result;
 1907: }
 1908: 
 1909: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 1910: 
 1911: sub updateclickers {
 1912:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 1913:     my %clickers;
 1914:     if (ref($idshashref) eq 'HASH') {
 1915:         %clickers=%{$idshashref};
 1916:     } else {
 1917:         return;
 1918:     }
 1919:     my $items='';
 1920:     foreach my $item (keys(%clickers)) {
 1921:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 1922:     }
 1923:     $items=~s/\&$//;
 1924:     my $request = "updateclickers:$udom:$action:$items";
 1925:     if ($critical) {
 1926:         return &critical($request,$uhome);
 1927:     } else {
 1928:         return &reply($request,$uhome);
 1929:     }
 1930: }
 1931: 
 1932: # ------------------------------dump from db file owned by domainconfig user
 1933: sub dump_dom {
 1934:     my ($namespace, $udom, $regexp) = @_;
 1935: 
 1936:     $udom ||= $env{'user.domain'};
 1937: 
 1938:     return () unless $udom;
 1939: 
 1940:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1941: }
 1942: 
 1943: # ------------------------------------------ get items from domain db files   
 1944: 
 1945: sub get_dom {
 1946:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1947:     return if ($udom eq 'public');
 1948:     my $items='';
 1949:     foreach my $item (@$storearr) {
 1950:         $items.=&escape($item).'&';
 1951:     }
 1952:     $items=~s/\&$//;
 1953:     if (!$udom) {
 1954:         $udom=$env{'user.domain'};
 1955:         return if ($udom eq 'public');
 1956:         if (defined(&domain($udom,'primary'))) {
 1957:             $uhome=&domain($udom,'primary');
 1958:         } else {
 1959:             undef($uhome);
 1960:         }
 1961:     } else {
 1962:         if (!$uhome) {
 1963:             if (defined(&domain($udom,'primary'))) {
 1964:                 $uhome=&domain($udom,'primary');
 1965:             }
 1966:         }
 1967:     }
 1968:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1969:         my $rep;
 1970:         if ($namespace =~ /^enc/) {
 1971:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 1972:         } else {
 1973:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1974:         }
 1975:         my %returnhash;
 1976:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1977:             return %returnhash;
 1978:         }
 1979:         my @pairs=split(/\&/,$rep);
 1980:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1981:             return @pairs;
 1982:         }
 1983:         my $i=0;
 1984:         foreach my $item (@$storearr) {
 1985:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1986:             $i++;
 1987:         }
 1988:         return %returnhash;
 1989:     } else {
 1990:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1991:     }
 1992: }
 1993: 
 1994: # -------------------------------------------- put items in domain db files 
 1995: 
 1996: sub put_dom {
 1997:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1998:     if (!$udom) {
 1999:         $udom=$env{'user.domain'};
 2000:         if (defined(&domain($udom,'primary'))) {
 2001:             $uhome=&domain($udom,'primary');
 2002:         } else {
 2003:             undef($uhome);
 2004:         }
 2005:     } else {
 2006:         if (!$uhome) {
 2007:             if (defined(&domain($udom,'primary'))) {
 2008:                 $uhome=&domain($udom,'primary');
 2009:             }
 2010:         }
 2011:     } 
 2012:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2013:         my $items='';
 2014:         foreach my $item (keys(%$storehash)) {
 2015:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2016:         }
 2017:         $items=~s/\&$//;
 2018:         if ($namespace =~ /^enc/) {
 2019:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2020:         } else {
 2021:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2022:         }
 2023:     } else {
 2024:         &logthis("put_dom failed - no homeserver and/or domain");
 2025:     }
 2026: }
 2027: 
 2028: # --------------------- newput for items in db file owned by domainconfig user
 2029: sub newput_dom {
 2030:     my ($namespace,$storehash,$udom) = @_;
 2031:     my $result;
 2032:     if (!$udom) {
 2033:         $udom=$env{'user.domain'};
 2034:     }
 2035:     if ($udom) {
 2036:         my $uname = &get_domainconfiguser($udom);
 2037:         $result = &newput($namespace,$storehash,$udom,$uname);
 2038:     }
 2039:     return $result;
 2040: }
 2041: 
 2042: # --------------------- delete for items in db file owned by domainconfig user
 2043: sub del_dom {
 2044:     my ($namespace,$storearr,$udom)=@_;
 2045:     if (ref($storearr) eq 'ARRAY') {
 2046:         if (!$udom) {
 2047:             $udom=$env{'user.domain'};
 2048:         }
 2049:         if ($udom) {
 2050:             my $uname = &get_domainconfiguser($udom); 
 2051:             return &del($namespace,$storearr,$udom,$uname);
 2052:         }
 2053:     }
 2054: }
 2055: 
 2056: # ----------------------------------construct domainconfig user for a domain 
 2057: sub get_domainconfiguser {
 2058:     my ($udom) = @_;
 2059:     return $udom.'-domainconfig';
 2060: }
 2061: 
 2062: sub retrieve_inst_usertypes {
 2063:     my ($udom) = @_;
 2064:     my (%returnhash,@order);
 2065:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2066:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2067:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2068:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2069:     } else {
 2070:         if (defined(&domain($udom,'primary'))) {
 2071:             my $uhome=&domain($udom,'primary');
 2072:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2073:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2074:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2075:                 return (\%returnhash,\@order);
 2076:             }
 2077:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2078:             my @pairs=split(/\&/,$hashitems);
 2079:             foreach my $item (@pairs) {
 2080:                 my ($key,$value)=split(/=/,$item,2);
 2081:                 $key = &unescape($key);
 2082:                 next if ($key =~ /^error: 2 /);
 2083:                 $returnhash{$key}=&thaw_unescape($value);
 2084:             }
 2085:             my @esc_order = split(/\&/,$orderitems);
 2086:             foreach my $item (@esc_order) {
 2087:                 push(@order,&unescape($item));
 2088:             }
 2089:         } else {
 2090:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2091:         }
 2092:         return (\%returnhash,\@order);
 2093:     }
 2094: }
 2095: 
 2096: sub is_domainimage {
 2097:     my ($url) = @_;
 2098:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2099:         if (&domain($1) ne '') {
 2100:             return '1';
 2101:         }
 2102:     }
 2103:     return;
 2104: }
 2105: 
 2106: sub inst_directory_query {
 2107:     my ($srch) = @_;
 2108:     my $udom = $srch->{'srchdomain'};
 2109:     my %results;
 2110:     my $homeserver = &domain($udom,'primary');
 2111:     my $outcome;
 2112:     if ($homeserver ne '') {
 2113:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2114:             if ($srch->{'srchby'} eq 'email') {
 2115:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2116:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2117:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2118:                     (($major == 2) && ($minor < 12))) {
 2119:                     return;
 2120:                 }
 2121:             }
 2122:         }
 2123: 	my $queryid=&reply("querysend:instdirsearch:".
 2124: 			   &escape($srch->{'srchby'}).':'.
 2125: 			   &escape($srch->{'srchterm'}).':'.
 2126: 			   &escape($srch->{'srchtype'}),$homeserver);
 2127: 	my $host=&hostname($homeserver);
 2128: 	if ($queryid !~/^\Q$host\E\_/) {
 2129: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2130: 	    return;
 2131: 	}
 2132: 	my $response = &get_query_reply($queryid);
 2133: 	my $maxtries = 5;
 2134: 	my $tries = 1;
 2135: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2136: 	    $response = &get_query_reply($queryid);
 2137: 	    $tries ++;
 2138: 	}
 2139: 
 2140:         if (!&error($response) && $response ne 'refused') {
 2141:             if ($response eq 'unavailable') {
 2142:                 $outcome = $response;
 2143:             } else {
 2144:                 $outcome = 'ok';
 2145:                 my @matches = split(/\n/,$response);
 2146:                 foreach my $match (@matches) {
 2147:                     my ($key,$value) = split(/=/,$match);
 2148:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2149:                 }
 2150:             }
 2151:         }
 2152:     }
 2153:     return ($outcome,%results);
 2154: }
 2155: 
 2156: sub usersearch {
 2157:     my ($srch) = @_;
 2158:     my $dom = $srch->{'srchdomain'};
 2159:     my %results;
 2160:     my %libserv = &all_library();
 2161:     my $query = 'usersearch';
 2162:     foreach my $tryserver (keys(%libserv)) {
 2163:         if (&host_domain($tryserver) eq $dom) {
 2164:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2165:                 if ($srch->{'srchby'} eq 'email') {
 2166:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2167:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2168:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2169:                              (($major == 2) && ($minor < 12)));
 2170:                 }
 2171:             }
 2172:             my $host=&hostname($tryserver);
 2173:             my $queryid=
 2174:                 &reply("querysend:".&escape($query).':'.
 2175:                        &escape($srch->{'srchby'}).':'.
 2176:                        &escape($srch->{'srchtype'}).':'.
 2177:                        &escape($srch->{'srchterm'}),$tryserver);
 2178:             if ($queryid !~/^\Q$host\E\_/) {
 2179:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2180:                 next;
 2181:             }
 2182:             my $reply = &get_query_reply($queryid);
 2183:             my $maxtries = 1;
 2184:             my $tries = 1;
 2185:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2186:                 $reply = &get_query_reply($queryid);
 2187:                 $tries ++;
 2188:             }
 2189:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2190:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2191:             } else {
 2192:                 my @matches;
 2193:                 if ($reply =~ /\n/) {
 2194:                     @matches = split(/\n/,$reply);
 2195:                 } else {
 2196:                     @matches = split(/\&/,$reply);
 2197:                 }
 2198:                 foreach my $match (@matches) {
 2199:                     my ($uname,$udom,%userhash);
 2200:                     foreach my $entry (split(/:/,$match)) {
 2201:                         my ($key,$value) =
 2202:                             map {&unescape($_);} split(/=/,$entry);
 2203:                         $userhash{$key} = $value;
 2204:                         if ($key eq 'username') {
 2205:                             $uname = $value;
 2206:                         } elsif ($key eq 'domain') {
 2207:                             $udom = $value;
 2208:                         }
 2209:                     }
 2210:                     $results{$uname.':'.$udom} = \%userhash;
 2211:                 }
 2212:             }
 2213:         }
 2214:     }
 2215:     return %results;
 2216: }
 2217: 
 2218: sub get_instuser {
 2219:     my ($udom,$uname,$id) = @_;
 2220:     my $homeserver = &domain($udom,'primary');
 2221:     my ($outcome,%results);
 2222:     if ($homeserver ne '') {
 2223:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2224:                            &escape($id).':'.&escape($udom),$homeserver);
 2225:         my $host=&hostname($homeserver);
 2226:         if ($queryid !~/^\Q$host\E\_/) {
 2227:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2228:             return;
 2229:         }
 2230:         my $response = &get_query_reply($queryid);
 2231:         my $maxtries = 5;
 2232:         my $tries = 1;
 2233:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2234:             $response = &get_query_reply($queryid);
 2235:             $tries ++;
 2236:         }
 2237:         if (!&error($response) && $response ne 'refused') {
 2238:             if ($response eq 'unavailable') {
 2239:                 $outcome = $response;
 2240:             } else {
 2241:                 $outcome = 'ok';
 2242:                 my @matches = split(/\n/,$response);
 2243:                 foreach my $match (@matches) {
 2244:                     my ($key,$value) = split(/=/,$match);
 2245:                     $results{&unescape($key)} = &thaw_unescape($value);
 2246:                 }
 2247:             }
 2248:         }
 2249:     }
 2250:     my %userinfo;
 2251:     if (ref($results{$uname}) eq 'HASH') {
 2252:         %userinfo = %{$results{$uname}};
 2253:     } 
 2254:     return ($outcome,%userinfo);
 2255: }
 2256: 
 2257: sub get_multiple_instusers {
 2258:     my ($udom,$users,$caller) = @_;
 2259:     my ($outcome,$results);
 2260:     if (ref($users) eq 'HASH') {
 2261:         my $count = keys(%{$users}); 
 2262:         my $requested = &freeze_escape($users);
 2263:         my $homeserver = &domain($udom,'primary');
 2264:         if ($homeserver ne '') {
 2265:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2266:             my $host=&hostname($homeserver);
 2267:             if ($queryid !~/^\Q$host\E\_/) {
 2268:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2269:                          ' for host: '.$homeserver.'in domain '.$udom);
 2270:                 return ($outcome,$results);
 2271:             }
 2272:             my $response = &get_query_reply($queryid);
 2273:             my $maxtries = 5;
 2274:             if ($count > 100) {
 2275:                 $maxtries = 1+int($count/20);
 2276:             }
 2277:             my $tries = 1;
 2278:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2279:                 $response = &get_query_reply($queryid);
 2280:                 $tries ++;
 2281:             }
 2282:             if ($response eq '') {
 2283:                 $results = {};
 2284:                 foreach my $key (keys(%{$users})) {
 2285:                     my ($uname,$id);
 2286:                     if ($caller eq 'id') {
 2287:                         $id = $key;
 2288:                     } else {
 2289:                         $uname = $key;
 2290:                     }
 2291:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2292:                     $outcome = $resp;
 2293:                     if ($resp eq 'ok') {
 2294:                         %{$results} = (%{$results}, %info);
 2295:                     } else {
 2296:                         last;
 2297:                     }
 2298:                 }
 2299:             } elsif(!&error($response) && ($response ne 'refused')) {
 2300:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2301:                     $outcome = $response;
 2302:                 } else {
 2303:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2304:                     if ($outcome eq 'ok') {
 2305:                         $results = &thaw_unescape($userdata); 
 2306:                     }
 2307:                 }
 2308:             }
 2309:         }
 2310:     }
 2311:     return ($outcome,$results);
 2312: }
 2313: 
 2314: sub inst_rulecheck {
 2315:     my ($udom,$uname,$id,$item,$rules) = @_;
 2316:     my %returnhash;
 2317:     if ($udom ne '') {
 2318:         if (ref($rules) eq 'ARRAY') {
 2319:             @{$rules} = map {&escape($_);} (@{$rules});
 2320:             my $rulestr = join(':',@{$rules});
 2321:             my $homeserver=&domain($udom,'primary');
 2322:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2323:                 my $response;
 2324:                 if ($item eq 'username') {                
 2325:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2326:                                               ':'.&escape($uname).':'.$rulestr,
 2327:                                               $homeserver));
 2328:                 } elsif ($item eq 'id') {
 2329:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2330:                                               ':'.&escape($id).':'.$rulestr,
 2331:                                               $homeserver));
 2332:                 } elsif ($item eq 'selfcreate') {
 2333:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2334:                                                &escape($udom).':'.&escape($uname).
 2335:                                               ':'.$rulestr,$homeserver));
 2336:                 }
 2337:                 if ($response ne 'refused') {
 2338:                     my @pairs=split(/\&/,$response);
 2339:                     foreach my $item (@pairs) {
 2340:                         my ($key,$value)=split(/=/,$item,2);
 2341:                         $key = &unescape($key);
 2342:                         next if ($key =~ /^error: 2 /);
 2343:                         $returnhash{$key}=&thaw_unescape($value);
 2344:                     }
 2345:                 }
 2346:             }
 2347:         }
 2348:     }
 2349:     return %returnhash;
 2350: }
 2351: 
 2352: sub inst_userrules {
 2353:     my ($udom,$check) = @_;
 2354:     my (%ruleshash,@ruleorder);
 2355:     if ($udom ne '') {
 2356:         my $homeserver=&domain($udom,'primary');
 2357:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2358:             my $response;
 2359:             if ($check eq 'id') {
 2360:                 $response=&reply('instidrules:'.&escape($udom),
 2361:                                  $homeserver);
 2362:             } elsif ($check eq 'email') {
 2363:                 $response=&reply('instemailrules:'.&escape($udom),
 2364:                                  $homeserver);
 2365:             } else {
 2366:                 $response=&reply('instuserrules:'.&escape($udom),
 2367:                                  $homeserver);
 2368:             }
 2369:             if (($response ne 'refused') && ($response ne 'error') && 
 2370:                 ($response ne 'unknown_cmd') && 
 2371:                 ($response ne 'no_such_host')) {
 2372:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2373:                 my @pairs=split(/\&/,$hashitems);
 2374:                 foreach my $item (@pairs) {
 2375:                     my ($key,$value)=split(/=/,$item,2);
 2376:                     $key = &unescape($key);
 2377:                     next if ($key =~ /^error: 2 /);
 2378:                     $ruleshash{$key}=&thaw_unescape($value);
 2379:                 }
 2380:                 my @esc_order = split(/\&/,$orderitems);
 2381:                 foreach my $item (@esc_order) {
 2382:                     push(@ruleorder,&unescape($item));
 2383:                 }
 2384:             }
 2385:         }
 2386:     }
 2387:     return (\%ruleshash,\@ruleorder);
 2388: }
 2389: 
 2390: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2391: 
 2392: sub get_domain_defaults {
 2393:     my ($domain,$ignore_cache) = @_;
 2394:     return if (($domain eq '') || ($domain eq 'public'));
 2395:     my $cachetime = 60*60*24;
 2396:     unless ($ignore_cache) {
 2397:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2398:         if (defined($cached)) {
 2399:             if (ref($result) eq 'HASH') {
 2400:                 return %{$result};
 2401:             }
 2402:         }
 2403:     }
 2404:     my %domdefaults;
 2405:     my %domconfig =
 2406:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2407:                                   'requestcourses','inststatus',
 2408:                                   'coursedefaults','usersessions',
 2409:                                   'requestauthor','selfenrollment',
 2410:                                   'coursecategories','ssl','autoenroll',
 2411:                                   'trust','helpsettings'],$domain);
 2412:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2413:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2414:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2415:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2416:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2417:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2418:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2419:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2420:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2421:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2422:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2423:     } else {
 2424:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2425:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2426:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2427:     }
 2428:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2429:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2430:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2431:         } else {
 2432:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2433:         }
 2434:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2435:         foreach my $item (@usertools) {
 2436:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2437:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2438:             }
 2439:         }
 2440:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2441:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2442:         }
 2443:     }
 2444:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2445:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2446:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2447:         }
 2448:     }
 2449:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2450:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2451:     }
 2452:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2453:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2454:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2455:         }
 2456:     }
 2457:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2458:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2459:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2460:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2461:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2462:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2463:         }
 2464:         foreach my $type (@coursetypes) {
 2465:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2466:                 unless ($type eq 'community') {
 2467:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2468:                 }
 2469:             }
 2470:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2471:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2472:             }
 2473:             if ($domdefaults{'postsubmit'} eq 'on') {
 2474:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2475:                     $domdefaults{$type.'postsubtimeout'} = 
 2476:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2477:                 }
 2478:             }
 2479:         }
 2480:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2481:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2482:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2483:                 if (@clonecodes) {
 2484:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2485:                 }
 2486:             }
 2487:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2488:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2489:         }
 2490:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2491:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2492:         } 
 2493:     }
 2494:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2495:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2496:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2497:         }
 2498:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2499:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2500:         }
 2501:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2502:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2503:         }
 2504:     }
 2505:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2506:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2507:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2508:                             'approval','limit');
 2509:             foreach my $type (@coursetypes) {
 2510:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2511:                     my @mgrdc = ();
 2512:                     foreach my $item (@settings) {
 2513:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2514:                             push(@mgrdc,$item);
 2515:                         }
 2516:                     }
 2517:                     if (@mgrdc) {
 2518:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2519:                     }
 2520:                 }
 2521:             }
 2522:         }
 2523:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2524:             foreach my $type (@coursetypes) {
 2525:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2526:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2527:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2528:                     }
 2529:                 }
 2530:             }
 2531:         }
 2532:     }
 2533:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2534:         $domdefaults{'catauth'} = 'std';
 2535:         $domdefaults{'catunauth'} = 'std';
 2536:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2537:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2538:         }
 2539:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2540:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2541:         }
 2542:     }
 2543:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2544:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2545:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2546:         }
 2547:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2548:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2549:         }
 2550:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2551:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2552:         }
 2553:     }
 2554:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2555:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2556:         foreach my $prefix (@prefixes) {
 2557:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2558:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2559:             }
 2560:         }
 2561:     }
 2562:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2563:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2564:     }
 2565:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2566:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2567:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2568:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2569:         }
 2570:     }
 2571:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2572:     return %domdefaults;
 2573: }
 2574: 
 2575: sub course_portal_url {
 2576:     my ($cnum,$cdom) = @_;
 2577:     my $chome = &homeserver($cnum,$cdom);
 2578:     my $hostname = &hostname($chome);
 2579:     my $protocol = $protocol{$chome};
 2580:     $protocol = 'http' if ($protocol ne 'https');
 2581:     my %domdefaults = &get_domain_defaults($cdom);
 2582:     my $firsturl;
 2583:     if ($domdefaults{'portal_def'}) {
 2584:         $firsturl = $domdefaults{'portal_def'};
 2585:     } else {
 2586:         $firsturl = $protocol.'://'.$hostname;
 2587:     }
 2588:     return $firsturl;
 2589: }
 2590: 
 2591: # --------------------------------------------------- Assign a key to a student
 2592: 
 2593: sub assign_access_key {
 2594: #
 2595: # a valid key looks like uname:udom#comments
 2596: # comments are being appended
 2597: #
 2598:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2599:     $kdom=
 2600:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2601:     $knum=
 2602:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2603:     $cdom=
 2604:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2605:     $cnum=
 2606:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2607:     $udom=$env{'user.name'} unless (defined($udom));
 2608:     $uname=$env{'user.domain'} unless (defined($uname));
 2609:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2610:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2611:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2612:                                                   # assigned to this person
 2613:                                                   # - this should not happen,
 2614:                                                   # unless something went wrong
 2615:                                                   # the first time around
 2616: # ready to assign
 2617:         $logentry=$1.'; '.$logentry;
 2618:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2619:                                                  $kdom,$knum) eq 'ok') {
 2620: # key now belongs to user
 2621: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2622:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2623:                 &appenv({'environment.'.$envkey => $ckey});
 2624:                 return 'ok';
 2625:             } else {
 2626:                 return 
 2627:   'error: Count not permanently assign key, will need to be re-entered later.';
 2628: 	    }
 2629:         } else {
 2630:             return 'error: Could not assign key, try again later.';
 2631:         }
 2632:     } elsif (!$existing{$ckey}) {
 2633: # the key does not exist
 2634: 	return 'error: The key does not exist';
 2635:     } else {
 2636: # the key is somebody else's
 2637: 	return 'error: The key is already in use';
 2638:     }
 2639: }
 2640: 
 2641: # ------------------------------------------ put an additional comment on a key
 2642: 
 2643: sub comment_access_key {
 2644: #
 2645: # a valid key looks like uname:udom#comments
 2646: # comments are being appended
 2647: #
 2648:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2649:     $cdom=
 2650:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2651:     $cnum=
 2652:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2653:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2654:     if ($existing{$ckey}) {
 2655:         $existing{$ckey}.='; '.$logentry;
 2656: # ready to assign
 2657:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2658:                                                  $cdom,$cnum) eq 'ok') {
 2659: 	    return 'ok';
 2660:         } else {
 2661: 	    return 'error: Count not store comment.';
 2662:         }
 2663:     } else {
 2664: # the key does not exist
 2665: 	return 'error: The key does not exist';
 2666:     }
 2667: }
 2668: 
 2669: # ------------------------------------------------------ Generate a set of keys
 2670: 
 2671: sub generate_access_keys {
 2672:     my ($number,$cdom,$cnum,$logentry)=@_;
 2673:     $cdom=
 2674:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2675:     $cnum=
 2676:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2677:     unless (&allowed('mky',$cdom)) { return 0; }
 2678:     unless (($cdom) && ($cnum)) { return 0; }
 2679:     if ($number>10000) { return 0; }
 2680:     sleep(2); # make sure don't get same seed twice
 2681:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2682:     my $total=0;
 2683:     for (my $i=1;$i<=$number;$i++) {
 2684:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2685:                   sprintf("%lx",int(100000*rand)).'-'.
 2686:                   sprintf("%lx",int(100000*rand));
 2687:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2688:        $newkey=~s/0/h/g; # and also 0 and O
 2689:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2690:        if ($existing{$newkey}) {
 2691:            $i--;
 2692:        } else {
 2693: 	  if (&put('accesskeys',
 2694:               { $newkey => '# generated '.localtime().
 2695:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2696:                            '; '.$logentry },
 2697: 		   $cdom,$cnum) eq 'ok') {
 2698:               $total++;
 2699: 	  }
 2700:        }
 2701:     }
 2702:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2703:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2704:     return $total;
 2705: }
 2706: 
 2707: # ------------------------------------------------------- Validate an accesskey
 2708: 
 2709: sub validate_access_key {
 2710:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2711:     $cdom=
 2712:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2713:     $cnum=
 2714:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2715:     $udom=$env{'user.domain'} unless (defined($udom));
 2716:     $uname=$env{'user.name'} unless (defined($uname));
 2717:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2718:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2719: }
 2720: 
 2721: # ------------------------------------- Find the section of student in a course
 2722: sub devalidate_getsection_cache {
 2723:     my ($udom,$unam,$courseid)=@_;
 2724:     my $hashid="$udom:$unam:$courseid";
 2725:     &devalidate_cache_new('getsection',$hashid);
 2726: }
 2727: 
 2728: sub courseid_to_courseurl {
 2729:     my ($courseid) = @_;
 2730:     #already url style courseid
 2731:     return $courseid if ($courseid =~ m{^/});
 2732: 
 2733:     if (exists($env{'course.'.$courseid.'.num'})) {
 2734: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2735: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2736: 	return "/$cdom/$cnum";
 2737:     }
 2738: 
 2739:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2740:     if (exists($courseinfo{'num'})) {
 2741: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2742:     }
 2743: 
 2744:     return undef;
 2745: }
 2746: 
 2747: sub getsection {
 2748:     my ($udom,$unam,$courseid)=@_;
 2749:     my $cachetime=1800;
 2750: 
 2751:     my $hashid="$udom:$unam:$courseid";
 2752:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2753:     if (defined($cached)) { return $result; }
 2754: 
 2755:     my %Pending; 
 2756:     my %Expired;
 2757:     #
 2758:     # Each role can either have not started yet (pending), be active, 
 2759:     #    or have expired.
 2760:     #
 2761:     # If there is an active role, we are done.
 2762:     #
 2763:     # If there is more than one role which has not started yet, 
 2764:     #     choose the one which will start sooner
 2765:     # If there is one role which has not started yet, return it.
 2766:     #
 2767:     # If there is more than one expired role, choose the one which ended last.
 2768:     # If there is a role which has expired, return it.
 2769:     #
 2770:     $courseid = &courseid_to_courseurl($courseid);
 2771:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2772:     foreach my $key (keys(%roleshash)) {
 2773:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2774:         my $section=$1;
 2775:         if ($key eq $courseid.'_st') { $section=''; }
 2776:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2777:         my $now=time;
 2778:         if (defined($end) && $end && ($now > $end)) {
 2779:             $Expired{$end}=$section;
 2780:             next;
 2781:         }
 2782:         if (defined($start) && $start && ($now < $start)) {
 2783:             $Pending{$start}=$section;
 2784:             next;
 2785:         }
 2786:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2787:     }
 2788:     #
 2789:     # Presumedly there will be few matching roles from the above
 2790:     # loop and the sorting time will be negligible.
 2791:     if (scalar(keys(%Pending))) {
 2792:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2793:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2794:     } 
 2795:     if (scalar(keys(%Expired))) {
 2796:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2797:         my $time = pop(@sorted);
 2798:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2799:     }
 2800:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2801: }
 2802: 
 2803: sub save_cache {
 2804:     &purge_remembered();
 2805:     #&Apache::loncommon::validate_page();
 2806:     undef(%env);
 2807:     undef($env_loaded);
 2808: }
 2809: 
 2810: my $to_remember=-1;
 2811: my %remembered;
 2812: my %accessed;
 2813: my $kicks=0;
 2814: my $hits=0;
 2815: sub make_key {
 2816:     my ($name,$id) = @_;
 2817:     if (length($id) > 65 
 2818: 	&& length(&escape($id)) > 200) {
 2819: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2820:     }
 2821:     return &escape($name.':'.$id);
 2822: }
 2823: 
 2824: sub devalidate_cache_new {
 2825:     my ($name,$id,$debug) = @_;
 2826:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2827:     my $remembered_id=$name.':'.$id;
 2828:     $id=&make_key($name,$id);
 2829:     $memcache->delete($id);
 2830:     delete($remembered{$remembered_id});
 2831:     delete($accessed{$remembered_id});
 2832: }
 2833: 
 2834: sub is_cached_new {
 2835:     my ($name,$id,$debug) = @_;
 2836:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2837:     if (exists($remembered{$remembered_id})) {
 2838: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2839: 	$accessed{$remembered_id}=[&gettimeofday()];
 2840: 	$hits++;
 2841: 	return ($remembered{$remembered_id},1);
 2842:     }
 2843:     $id=&make_key($name,$id);
 2844:     my $value = $memcache->get($id);
 2845:     if (!(defined($value))) {
 2846: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2847: 	return (undef,undef);
 2848:     }
 2849:     if ($value eq '__undef__') {
 2850: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2851: 	$value=undef;
 2852:     }
 2853:     &make_room($remembered_id,$value,$debug);
 2854:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2855:     return ($value,1);
 2856: }
 2857: 
 2858: sub do_cache_new {
 2859:     my ($name,$id,$value,$time,$debug) = @_;
 2860:     my $remembered_id=$name.':'.$id;
 2861:     $id=&make_key($name,$id);
 2862:     my $setvalue=$value;
 2863:     if (!defined($setvalue)) {
 2864: 	$setvalue='__undef__';
 2865:     }
 2866:     if (!defined($time) ) {
 2867: 	$time=600;
 2868:     }
 2869:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2870:     my $result = $memcache->set($id,$setvalue,$time);
 2871:     if (! $result) {
 2872: 	&logthis("caching of id -> $id  failed");
 2873: 	$memcache->disconnect_all();
 2874:     }
 2875:     # need to make a copy of $value
 2876:     &make_room($remembered_id,$value,$debug);
 2877:     return $value;
 2878: }
 2879: 
 2880: sub make_room {
 2881:     my ($remembered_id,$value,$debug)=@_;
 2882: 
 2883:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2884:                                     : $value;
 2885:     if ($to_remember<0) { return; }
 2886:     $accessed{$remembered_id}=[&gettimeofday()];
 2887:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2888:     my $to_kick;
 2889:     my $max_time=0;
 2890:     foreach my $other (keys(%accessed)) {
 2891: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2892: 	    $to_kick=$other;
 2893: 	    $max_time=&tv_interval($accessed{$other});
 2894: 	}
 2895:     }
 2896:     delete($remembered{$to_kick});
 2897:     delete($accessed{$to_kick});
 2898:     $kicks++;
 2899:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2900:     return;
 2901: }
 2902: 
 2903: sub purge_remembered {
 2904:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2905:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2906:     undef(%remembered);
 2907:     undef(%accessed);
 2908: }
 2909: # ------------------------------------- Read an entry from a user's environment
 2910: 
 2911: sub userenvironment {
 2912:     my ($udom,$unam,@what)=@_;
 2913:     my $items;
 2914:     foreach my $item (@what) {
 2915:         $items.=&escape($item).'&';
 2916:     }
 2917:     $items=~s/\&$//;
 2918:     my %returnhash=();
 2919:     my $uhome = &homeserver($unam,$udom);
 2920:     unless ($uhome eq 'no_host') {
 2921:         my @answer=split(/\&/, 
 2922:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2923:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2924:             return %returnhash;
 2925:         }
 2926:         my $i;
 2927:         for ($i=0;$i<=$#what;$i++) {
 2928: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2929:         }
 2930:     }
 2931:     return %returnhash;
 2932: }
 2933: 
 2934: # ---------------------------------------------------------- Get a studentphoto
 2935: sub studentphoto {
 2936:     my ($udom,$unam,$ext) = @_;
 2937:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2938:     if (defined($env{'request.course.id'})) {
 2939:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2940:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2941:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2942:             } else {
 2943:                 my ($result,$perm_reqd)=
 2944: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2945:                 if ($result eq 'ok') {
 2946:                     if (!($perm_reqd eq 'yes')) {
 2947:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2948:                     }
 2949:                 }
 2950:             }
 2951:         }
 2952:     } else {
 2953:         my ($result,$perm_reqd) = 
 2954: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2955:         if ($result eq 'ok') {
 2956:             if (!($perm_reqd eq 'yes')) {
 2957:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2958:             }
 2959:         }
 2960:     }
 2961:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2962: }
 2963: 
 2964: sub retrievestudentphoto {
 2965:     my ($udom,$unam,$ext,$type) = @_;
 2966:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2967:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2968:     if ($ret eq 'ok') {
 2969:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2970:         if ($type eq 'thumbnail') {
 2971:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2972:         }
 2973:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2974:         return $tokenurl;
 2975:     } else {
 2976:         if ($type eq 'thumbnail') {
 2977:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2978:         } else { 
 2979:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2980:         }
 2981:     }
 2982: }
 2983: 
 2984: # -------------------------------------------------------------------- New chat
 2985: 
 2986: sub chatsend {
 2987:     my ($newentry,$anon,$group)=@_;
 2988:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2989:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2990:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2991:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2992: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2993: 		   &escape($newentry)).':'.$group,$chome);
 2994: }
 2995: 
 2996: # ------------------------------------------ Find current version of a resource
 2997: 
 2998: sub getversion {
 2999:     my $fname=&clutter(shift);
 3000:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3001:     return &currentversion(&filelocation('',$fname));
 3002: }
 3003: 
 3004: sub currentversion {
 3005:     my $fname=shift;
 3006:     my $author=$fname;
 3007:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3008:     my ($udom,$uname)=split(/\//,$author);
 3009:     my $home=&homeserver($uname,$udom);
 3010:     if ($home eq 'no_host') { 
 3011:         return -1; 
 3012:     }
 3013:     my $answer=&reply("currentversion:$fname",$home);
 3014:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3015: 	return -1;
 3016:     }
 3017:     return $answer;
 3018: }
 3019: 
 3020: #
 3021: # Return special version number of resource if set by override, empty otherwise
 3022: #
 3023: sub usedversion {
 3024:     my $fname=shift;
 3025:     unless ($fname) { $fname=$env{'request.uri'}; }
 3026:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3027:     if ($urlversion) { return $urlversion; }
 3028:     return '';
 3029: }
 3030: 
 3031: # ----------------------------- Subscribe to a resource, return URL if possible
 3032: 
 3033: sub subscribe {
 3034:     my $fname=shift;
 3035:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3036:     $fname=~s/[\n\r]//g;
 3037:     my $author=$fname;
 3038:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3039:     my ($udom,$uname)=split(/\//,$author);
 3040:     my $home=homeserver($uname,$udom);
 3041:     if ($home eq 'no_host') {
 3042:         return 'not_found';
 3043:     }
 3044:     my $answer=reply("sub:$fname",$home);
 3045:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3046: 	$answer.=' by '.$home;
 3047:     }
 3048:     return $answer;
 3049: }
 3050:     
 3051: # -------------------------------------------------------------- Replicate file
 3052: 
 3053: sub repcopy {
 3054:     my $filename=shift;
 3055:     $filename=~s/\/+/\//g;
 3056:     my $londocroot = $perlvar{'lonDocRoot'};
 3057:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3058:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3059:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3060: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3061: 	return &repcopy_userfile($filename);
 3062:     }
 3063:     $filename=~s/[\n\r]//g;
 3064:     my $transname="$filename.in.transfer";
 3065: # FIXME: this should flock
 3066:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3067:     my $remoteurl=subscribe($filename);
 3068:     if ($remoteurl =~ /^con_lost by/) {
 3069: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3070:            return 'unavailable';
 3071:     } elsif ($remoteurl eq 'not_found') {
 3072: 	   #&logthis("Subscribe returned not_found: $filename");
 3073: 	   return 'not_found';
 3074:     } elsif ($remoteurl =~ /^rejected by/) {
 3075: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3076:            return 'forbidden';
 3077:     } elsif ($remoteurl eq 'directory') {
 3078:            return 'ok';
 3079:     } else {
 3080:         my $author=$filename;
 3081:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3082:         my ($udom,$uname)=split(/\//,$author);
 3083:         my $home=homeserver($uname,$udom);
 3084:         unless ($home eq $perlvar{'lonHostID'}) {
 3085:            my @parts=split(/\//,$filename);
 3086:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3087:            if ($path ne "$londocroot/res") {
 3088:                &logthis("Malconfiguration for replication: $filename");
 3089: 	       return 'bad_request';
 3090:            }
 3091:            my $count;
 3092:            for ($count=5;$count<$#parts;$count++) {
 3093:                $path.="/$parts[$count]";
 3094:                if ((-e $path)!=1) {
 3095: 		   mkdir($path,0777);
 3096:                }
 3097:            }
 3098:            my $request=new HTTP::Request('GET',"$remoteurl");
 3099:            my $response;
 3100:            if ($remoteurl =~ m{/raw/}) {
 3101:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3102:            } else {
 3103:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3104:            }
 3105:            if ($response->is_error()) {
 3106: 	       unlink($transname);
 3107:                my $message=$response->status_line;
 3108:                &logthis("<font color=\"blue\">WARNING:"
 3109:                        ." LWP get: $message: $filename</font>");
 3110:                return 'unavailable';
 3111:            } else {
 3112: 	       if ($remoteurl!~/\.meta$/) {
 3113:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3114:                   my $mresponse;
 3115:                   if ($remoteurl =~ m{/raw/}) {
 3116:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3117:                   } else {
 3118:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3119:                   }
 3120:                   if ($mresponse->is_error()) {
 3121: 		      unlink($filename.'.meta');
 3122:                       &logthis(
 3123:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3124:                   }
 3125: 	       }
 3126:                rename($transname,$filename);
 3127:                return 'ok';
 3128:            }
 3129:        }
 3130:     }
 3131: }
 3132: 
 3133: # ------------------------------------------------ Get server side include body
 3134: sub ssi_body {
 3135:     my ($filelink,%form)=@_;
 3136:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3137:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3138:     }
 3139:     my $output='';
 3140:     my $response;
 3141:     if ($filelink=~/^https?\:/) {
 3142:        ($output,$response)=&externalssi($filelink);
 3143:     } else {
 3144:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3145:        $filelink .= 'inhibitmenu=yes';
 3146:        ($output,$response)=&ssi($filelink,%form);
 3147:     }
 3148:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3149:     $output=~s/^.*?\<body[^\>]*\>//si;
 3150:     $output=~s/\<\/body\s*\>.*?$//si;
 3151:     if (wantarray) {
 3152:         return ($output, $response);
 3153:     } else {
 3154:         return $output;
 3155:     }
 3156: }
 3157: 
 3158: # --------------------------------------------------------- Server Side Include
 3159: 
 3160: sub absolute_url {
 3161:     my ($host_name) = @_;
 3162:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3163:     if ($host_name eq '') {
 3164: 	$host_name = $ENV{'SERVER_NAME'};
 3165:     }
 3166:     return $protocol.$host_name;
 3167: }
 3168: 
 3169: #
 3170: #   Server side include.
 3171: # Parameters:
 3172: #  fn     Possibly encrypted resource name/id.
 3173: #  form   Hash that describes how the rendering should be done
 3174: #         and other things.
 3175: # Returns:
 3176: #   Scalar context: The content of the response.
 3177: #   Array context:  2 element list of the content and the full response object.
 3178: #     
 3179: sub ssi {
 3180: 
 3181:     my ($fn,%form)=@_;
 3182:     my $request;
 3183: 
 3184:     $form{'no_update_last_known'}=1;
 3185:     &Apache::lonenc::check_encrypt(\$fn);
 3186:     if (%form) {
 3187:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3188:       $request->content(join('&',map { 
 3189:             my $name = escape($_);
 3190:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3191:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3192:             : &escape($form{$_}) );    
 3193:         } keys(%form)));
 3194:     } else {
 3195:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3196:     }
 3197: 
 3198:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3199:     my $lonhost = $perlvar{'lonHostID'};
 3200:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3201:                                                 '','','',1);
 3202: 
 3203:     if (wantarray) {
 3204: 	return ($response->content, $response);
 3205:     } else {
 3206: 	return $response->content;
 3207:     }
 3208: }
 3209: 
 3210: sub externalssi {
 3211:     my ($url)=@_;
 3212:     my $request=new HTTP::Request('GET',$url);
 3213:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3214:     if (wantarray) {
 3215:         return ($response->content, $response);
 3216:     } else {
 3217:         return $response->content;
 3218:     }
 3219: }
 3220: 
 3221: 
 3222: # If the local copy of a replicated resource is outdated, trigger a  
 3223: # connection from the homeserver to flush the delayed queue. If no update 
 3224: # happens, remove local copies of outdated resource (and corresponding
 3225: # metadata file).
 3226: 
 3227: sub remove_stale_resfile {
 3228:     my ($url) = @_;
 3229:     my $removed;
 3230:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3231:         my $audom = $1;
 3232:         my $auname = $2;
 3233:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3234:             my $homeserver = &homeserver($auname,$audom);
 3235:             unless (($homeserver eq 'no_host') ||
 3236:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3237:                 my $fname = &filelocation('',$url);
 3238:                 if (-e $fname) {
 3239:                     my $protocol = $protocol{$homeserver};
 3240:                     $protocol = 'http' if ($protocol ne 'https');
 3241:                     my $hostname = &hostname($homeserver);
 3242:                     if ($hostname) {
 3243:                         my $uri = &declutter($url);
 3244:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3245:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3246:                         if ($response->is_success()) {
 3247:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3248:                             my $locmodtime = (stat($fname))[9];
 3249:                             if ($locmodtime < $remmodtime) {
 3250:                                 my $stale;
 3251:                                 my $answer = &reply('pong',$homeserver);
 3252:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3253:                                     sleep(0.2);
 3254:                                     $locmodtime = (stat($fname))[9];
 3255:                                     if ($locmodtime < $remmodtime) {
 3256:                                         my $posstransfer = $fname.'.in.transfer';
 3257:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3258:                                             $removed = 1;
 3259:                                         } else {
 3260:                                             $stale = 1;
 3261:                                         }
 3262:                                     } else {
 3263:                                         $removed = 1;
 3264:                                     }
 3265:                                 } else {
 3266:                                     $stale = 1;
 3267:                                 }
 3268:                                 if ($stale) {
 3269:                                     unlink($fname);
 3270:                                     if ($uri!~/\.meta$/) {
 3271:                                         unlink($fname.'.meta');
 3272:                                     }
 3273:                                     &reply("unsub:$fname",$homeserver);
 3274:                                     $removed = 1;
 3275:                                 }
 3276:                             }
 3277:                         }
 3278:                     }
 3279:                 }
 3280:             }
 3281:         }
 3282:     }
 3283:     return $removed;
 3284: }
 3285: 
 3286: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3287: 
 3288: sub allowuploaded {
 3289:     my ($srcurl,$url)=@_;
 3290:     $url=&clutter(&declutter($url));
 3291:     my $dir=$url;
 3292:     $dir=~s/\/[^\/]+$//;
 3293:     my %httpref=();
 3294:     my $httpurl=&hreflocation('',$url);
 3295:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3296:     &Apache::lonnet::appenv(\%httpref);
 3297: }
 3298: 
 3299: #
 3300: # Determine if the current user should be able to edit a particular resource,
 3301: # when viewing in course context.
 3302: # (a) When viewing resource used to determine if "Edit" item is included in 
 3303: #     Functions.
 3304: # (b) When displaying folder contents in course editor, used to determine if
 3305: #     "Edit" link will be displayed alongside resource.
 3306: #
 3307: #  input: six args -- filename (decluttered), course number, course domain,
 3308: #                   url, symb (if registered) and group (if this is a group
 3309: #                   item -- e.g., bulletin board, group page etc.).
 3310: #  output: array of five scalars -- 
 3311: #          $cfile -- url for file editing if editable on current server
 3312: #          $home -- homeserver of resource (i.e., for author if published,
 3313: #                                           or course if uploaded.).
 3314: #          $switchserver --  1 if server switch will be needed.
 3315: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3316: #          $forceview -- 1 if icon/link should be to go to view mode
 3317: #
 3318: 
 3319: sub can_edit_resource {
 3320:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3321:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3322: #
 3323: # For aboutme pages user can only edit his/her own.
 3324: #
 3325:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3326:         my ($sdom,$sname) = ($1,$2);
 3327:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3328:             $home = $env{'user.home'};
 3329:             $cfile = $resurl;
 3330:             if ($env{'form.forceedit'}) {
 3331:                 $forceview = 1;
 3332:             } else {
 3333:                 $forceedit = 1;
 3334:             }
 3335:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3336:         } else {
 3337:             return;
 3338:         }
 3339:     }
 3340: 
 3341:     if ($env{'request.course.id'}) {
 3342:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3343:         if ($group ne '') {
 3344: # if this is a group homepage or group bulletin board, check group privs
 3345:             my $allowed = 0;
 3346:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3347:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3348:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3349:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3350:                     $allowed = 1;
 3351:                 }
 3352:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3353:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3354:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3355:                     $allowed = 1;
 3356:                 }
 3357:             }
 3358:             if ($allowed) {
 3359:                 $home=&homeserver($cnum,$cdom);
 3360:                 if ($env{'form.forceedit'}) {
 3361:                     $forceview = 1;
 3362:                 } else {
 3363:                     $forceedit = 1;
 3364:                 }
 3365:                 $cfile = $resurl;
 3366:             } else {
 3367:                 return;
 3368:             }
 3369:         } else {
 3370:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3371:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3372:                     return;
 3373:                 }
 3374:             } elsif (!$crsedit) {
 3375: #
 3376: # No edit allowed where CC has switched to student role.
 3377: #
 3378:                 return;
 3379:             }
 3380:         }
 3381:     }
 3382: 
 3383:     if ($file ne '') {
 3384:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3385:             if (&is_course_upload($file,$cnum,$cdom)) {
 3386:                 $uploaded = 1;
 3387:                 $incourse = 1;
 3388:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3389:                     $cfile = &hreflocation('',$file);
 3390:                     if ($env{'form.forceedit'}) {
 3391:                         $forceview = 1;
 3392:                     } else {
 3393:                         $forceedit = 1;
 3394:                     }
 3395:                 }
 3396:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3397:                 $incourse = 1;
 3398:                 if ($env{'form.forceedit'}) {
 3399:                     $forceview = 1;
 3400:                 } else {
 3401:                     $forceedit = 1;
 3402:                 }
 3403:                 $cfile = $resurl;
 3404:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3405:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3406:                     $incourse = 1;
 3407:                     if ($env{'form.forceedit'}) {
 3408:                         $forceview = 1;
 3409:                     } else {
 3410:                         $forceedit = 1;
 3411:                     }
 3412:                     $cfile = $resurl;
 3413:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3414:                     $incourse = 1;
 3415:                     $cfile = $resurl.'/smpedit';
 3416:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3417:                     $incourse = 1;
 3418:                     if ($env{'form.forceedit'}) {
 3419:                         $forceview = 1;
 3420:                     } else {
 3421:                         $forceedit = 1;
 3422:                     }
 3423:                     $cfile = $resurl;
 3424:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3425:                     $incourse = 1;
 3426:                     if ($env{'form.forceedit'}) {
 3427:                         $forceview = 1;
 3428:                     } else {
 3429:                         $forceedit = 1;
 3430:                     }
 3431:                     $cfile = $resurl;
 3432:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3433:                     $incourse = 1;
 3434:                     if ($env{'form.forceedit'}) {
 3435:                         $forceview = 1;
 3436:                     } else {
 3437:                         $forceedit = 1;
 3438:                     }
 3439:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3440:                 }
 3441:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3442:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3443:                 if (&is_on_map($template)) { 
 3444:                     $incourse = 1;
 3445:                     $forceview = 1;
 3446:                     $cfile = $template;
 3447:                 }
 3448:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3449:                     $incourse = 1;
 3450:                     if ($env{'form.forceedit'}) {
 3451:                         $forceview = 1;
 3452:                     } else {
 3453:                         $forceedit = 1;
 3454:                     }
 3455:                     $cfile = $resurl;
 3456:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3457:                 $incourse = 1;
 3458:                 if ($env{'form.forceedit'}) {
 3459:                     $forceview = 1;
 3460:                 } else {
 3461:                     $forceedit = 1;
 3462:                 }
 3463:                 $cfile = $resurl;
 3464:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3465:                 $incourse = 1;
 3466:                 $forceview = 1;
 3467:                 if ($symb) {
 3468:                     my ($map,$id,$res)=&decode_symb($symb);
 3469:                     $env{'request.symb'} = $symb;
 3470:                     $cfile = &clutter($res);
 3471:                 } else {
 3472:                     $cfile = $env{'form.suppurl'};
 3473:                     my $escfile = &unescape($cfile);
 3474:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3475:                         $cfile = '/adm/wrapper'.$escfile;
 3476:                     } else {
 3477:                         $escfile =~ s{^http://}{};
 3478:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3479:                     }
 3480:                 }
 3481:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3482:                 if ($env{'form.forceedit'}) {
 3483:                     $forceview = 1;
 3484:                 } else {
 3485:                     $forceedit = 1;
 3486:                 }
 3487:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3488:             }
 3489:         }
 3490:         if ($uploaded || $incourse) {
 3491:             $home=&homeserver($cnum,$cdom);
 3492:         } elsif ($file !~ m{/$}) {
 3493:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3494:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3495:             # Check that the user has permission to edit this resource
 3496:             my $setpriv = 1;
 3497:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3498:             if (defined($cfudom)) {
 3499:                 $home=&homeserver($cfuname,$cfudom);
 3500:                 $cfile=$file;
 3501:             }
 3502:         }
 3503:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3504:             (($home ne '') && ($home ne 'no_host'))) {
 3505:             my @ids=&current_machine_ids();
 3506:             unless (grep(/^\Q$home\E$/,@ids)) {
 3507:                 $switchserver=1;
 3508:             }
 3509:         }
 3510:     }
 3511:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3512: }
 3513: 
 3514: sub is_course_upload {
 3515:     my ($file,$cnum,$cdom) = @_;
 3516:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3517:     $uploadpath =~ s{^\/}{};
 3518:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3519:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3520:         return 1;
 3521:     }
 3522:     return;
 3523: }
 3524: 
 3525: sub in_course {
 3526:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3527:     if ($hideprivileged) {
 3528:         my $skipuser;
 3529:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3530:         my @possdoms = ($cdom);  
 3531:         if ($coursehash{'checkforpriv'}) { 
 3532:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3533:         }
 3534:         if (&privileged($uname,$udom,\@possdoms)) {
 3535:             $skipuser = 1;
 3536:             if ($coursehash{'nothideprivileged'}) {
 3537:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3538:                     my $user;
 3539:                     if ($item =~ /:/) {
 3540:                         $user = $item;
 3541:                     } else {
 3542:                         $user = join(':',split(/[\@]/,$item));
 3543:                     }
 3544:                     if ($user eq $uname.':'.$udom) {
 3545:                         undef($skipuser);
 3546:                         last;
 3547:                     }
 3548:                 }
 3549:             }
 3550:             if ($skipuser) {
 3551:                 return 0;
 3552:             }
 3553:         }
 3554:     }
 3555:     $type ||= 'any';
 3556:     if (!defined($cdom) || !defined($cnum)) {
 3557:         my $cid  = $env{'request.course.id'};
 3558:         $cdom = $env{'course.'.$cid.'.domain'};
 3559:         $cnum = $env{'course.'.$cid.'.num'};
 3560:     }
 3561:     my $typesref;
 3562:     if (($type eq 'any') || ($type eq 'all')) {
 3563:         $typesref = ['active','previous','future'];
 3564:     } elsif ($type eq 'previous' || $type eq 'future') {
 3565:         $typesref = [$type];
 3566:     }
 3567:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3568:                               $typesref,undef,[$cdom]);
 3569:     my ($tmp) = keys(%roles);
 3570:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3571:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3572:     if (@course_roles > 0) {
 3573:         return 1;
 3574:     }
 3575:     return 0;
 3576: }
 3577: 
 3578: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3579: # input: action, courseID, current domain, intended
 3580: #        path to file, source of file, instruction to parse file for objects,
 3581: #        ref to hash for embedded objects,
 3582: #        ref to hash for codebase of java objects.
 3583: #        reference to scalar to accommodate mime type determined
 3584: #          from File::MMagic if $parser = parse.
 3585: #
 3586: # output: url to file (if action was uploaddoc), 
 3587: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3588: #
 3589: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3590: # course.
 3591: #
 3592: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3593: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3594: #          course's home server.
 3595: #
 3596: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3597: #          be copied from $source (current location) to 
 3598: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3599: #         and will then be copied to
 3600: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3601: #         course's home server.
 3602: #
 3603: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3604: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3605: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3606: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3607: #         in course's home server.
 3608: #
 3609: 
 3610: sub process_coursefile {
 3611:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3612:         $mimetype)=@_;
 3613:     my $fetchresult;
 3614:     my $home=&homeserver($docuname,$docudom);
 3615:     if ($action eq 'propagate') {
 3616:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3617: 			     $home);
 3618:     } else {
 3619:         my $fpath = '';
 3620:         my $fname = $file;
 3621:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3622:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3623:         my $filepath = &build_filepath($fpath);
 3624:         if ($action eq 'copy') {
 3625:             if ($source eq '') {
 3626:                 $fetchresult = 'no source file';
 3627:                 return $fetchresult;
 3628:             } else {
 3629:                 my $destination = $filepath.'/'.$fname;
 3630:                 rename($source,$destination);
 3631:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3632:                                  $home);
 3633:             }
 3634:         } elsif ($action eq 'uploaddoc') {
 3635:             open(my $fh,'>',$filepath.'/'.$fname);
 3636:             print $fh $env{'form.'.$source};
 3637:             close($fh);
 3638:             if ($parser eq 'parse') {
 3639:                 my $mm = new File::MMagic;
 3640:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3641:                 if ($type eq 'text/html') {
 3642:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3643:                     unless ($parse_result eq 'ok') {
 3644:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3645:                     }
 3646:                 }
 3647:                 if (ref($mimetype)) {
 3648:                     $$mimetype = $type;
 3649:                 } 
 3650:             }
 3651:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3652:                                  $home);
 3653:             if ($fetchresult eq 'ok') {
 3654:                 return '/uploaded/'.$fpath.'/'.$fname;
 3655:             } else {
 3656:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3657:                         ' to host '.$home.': '.$fetchresult);
 3658:                 return '/adm/notfound.html';
 3659:             }
 3660:         }
 3661:     }
 3662:     unless ( $fetchresult eq 'ok') {
 3663:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3664:              ' to host '.$home.': '.$fetchresult);
 3665:     }
 3666:     return $fetchresult;
 3667: }
 3668: 
 3669: sub build_filepath {
 3670:     my ($fpath) = @_;
 3671:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3672:     unless ($fpath eq '') {
 3673:         my @parts=split('/',$fpath);
 3674:         foreach my $part (@parts) {
 3675:             $filepath.= '/'.$part;
 3676:             if ((-e $filepath)!=1) {
 3677:                 mkdir($filepath,0777);
 3678:             }
 3679:         }
 3680:     }
 3681:     return $filepath;
 3682: }
 3683: 
 3684: sub store_edited_file {
 3685:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3686:     my $file = $primary_url;
 3687:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3688:     my $fpath = '';
 3689:     my $fname = $file;
 3690:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3691:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3692:     my $filepath = &build_filepath($fpath);
 3693:     open(my $fh,'>',$filepath.'/'.$fname);
 3694:     print $fh $content;
 3695:     close($fh);
 3696:     my $home=&homeserver($docuname,$docudom);
 3697:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3698: 			  $home);
 3699:     if ($$fetchresult eq 'ok') {
 3700:         return '/uploaded/'.$fpath.'/'.$fname;
 3701:     } else {
 3702:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3703: 		 ' to host '.$home.': '.$$fetchresult);
 3704:         return '/adm/notfound.html';
 3705:     }
 3706: }
 3707: 
 3708: sub clean_filename {
 3709:     my ($fname,$args)=@_;
 3710: # Replace Windows backslashes by forward slashes
 3711:     $fname=~s/\\/\//g;
 3712:     if (!$args->{'keep_path'}) {
 3713:         # Get rid of everything but the actual filename
 3714: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3715:     }
 3716: # Replace spaces by underscores
 3717:     $fname=~s/\s+/\_/g;
 3718: # Replace all other weird characters by nothing
 3719:     $fname=~s{[^/\w\.\-]}{}g;
 3720: # Replace all .\d. sequences with _\d. so they no longer look like version
 3721: # numbers
 3722:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3723:     return $fname;
 3724: }
 3725: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3726: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3727: # image with the same aspect ratio as the original, but with dimensions which do 
 3728: # not exceed $resizewidth and $resizeheight.
 3729:  
 3730: sub resizeImage {
 3731:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3732:     my $ima = Image::Magick->new;
 3733:     my $resized;
 3734:     if (-e $img_path) {
 3735:         $ima->Read($img_path);
 3736:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3737:             my $width = $ima->Get('width');
 3738:             my $height = $ima->Get('height');
 3739:             if ($width > $resizewidth) {
 3740: 	        my $factor = $width/$resizewidth;
 3741:                 my $newheight = $height/$factor;
 3742:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3743:                 $resized = 1;
 3744:             }
 3745:         }
 3746:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3747:             my $width = $ima->Get('width');
 3748:             my $height = $ima->Get('height');
 3749:             if ($height > $resizeheight) {
 3750:                 my $factor = $height/$resizeheight;
 3751:                 my $newwidth = $width/$factor;
 3752:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3753:                 $resized = 1;
 3754:             }
 3755:         }
 3756:         if ($resized) {
 3757:             $ima->Write($img_path);
 3758:         }
 3759:     }
 3760:     return;
 3761: }
 3762: 
 3763: # --------------- Take an uploaded file and put it into the userfiles directory
 3764: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3765: #                    the desired filename is in $env{"form.$formname.filename"}
 3766: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3767: #                                    canceloverwrite, or ''. 
 3768: #                   if 'coursedoc': upload to the current course
 3769: #                   if 'existingfile': write file to tmp/overwrites directory 
 3770: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3771: #                   $context is passed as argument to &finishuserfileupload
 3772: #        $subdir - directory in userfile to store the file into
 3773: #        $parser - instruction to parse file for objects ($parser = parse)    
 3774: #        $allfiles - reference to hash for embedded objects
 3775: #        $codebase - reference to hash for codebase of java objects
 3776: #        $desuname - username for permanent storage of uploaded file
 3777: #        $dsetudom - domain for permanaent storage of uploaded file
 3778: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3779: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3780: #        $resizewidth - width (pixels) to which to resize uploaded image
 3781: #        $resizeheight - height (pixels) to which to resize uploaded image
 3782: #        $mimetype - reference to scalar to accommodate mime type determined
 3783: #                    from File::MMagic.
 3784: # 
 3785: # output: url of file in userspace, or error: <message> 
 3786: #             or /adm/notfound.html if failure to upload occurse
 3787: 
 3788: sub userfileupload {
 3789:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3790:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3791:     if (!defined($subdir)) { $subdir='unknown'; }
 3792:     my $fname=$env{'form.'.$formname.'.filename'};
 3793:     $fname=&clean_filename($fname);
 3794:     # See if there is anything left
 3795:     unless ($fname) { return 'error: no uploaded file'; }
 3796:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3797:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3798:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3799:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3800:         my $now = time;
 3801:         my $filepath;
 3802:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3803:              $filepath = 'tmp/helprequests/'.$now;
 3804:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3805:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3806:                          '_'.$env{'user.domain'}.'/pending';
 3807:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3808:             my ($docuname,$docudom);
 3809:             if ($destudom =~ /^$match_domain$/) {
 3810:                 $docudom = $destudom;
 3811:             } else {
 3812:                 $docudom = $env{'user.domain'};
 3813:             }
 3814:             if ($destuname =~ /^$match_username$/) {
 3815:                 $docuname = $destuname;
 3816:             } else {
 3817:                 $docuname = $env{'user.name'};
 3818:             }
 3819:             if (exists($env{'form.group'})) {
 3820:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3821:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3822:             }
 3823:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3824:             if ($context eq 'canceloverwrite') {
 3825:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3826:                 if (-e  $tempfile) {
 3827:                     my @info = stat($tempfile);
 3828:                     if ($info[9] eq $env{'form.timestamp'}) {
 3829:                         unlink($tempfile);
 3830:                     }
 3831:                 }
 3832:                 return;
 3833:             }
 3834:         }
 3835:         # Create the directory if not present
 3836:         my @parts=split(/\//,$filepath);
 3837:         my $fullpath = $perlvar{'lonDaemons'};
 3838:         for (my $i=0;$i<@parts;$i++) {
 3839:             $fullpath .= '/'.$parts[$i];
 3840:             if ((-e $fullpath)!=1) {
 3841:                 mkdir($fullpath,0777);
 3842:             }
 3843:         }
 3844:         open(my $fh,'>',$fullpath.'/'.$fname);
 3845:         print $fh $env{'form.'.$formname};
 3846:         close($fh);
 3847:         if ($context eq 'existingfile') {
 3848:             my @info = stat($fullpath.'/'.$fname);
 3849:             return ($fullpath.'/'.$fname,$info[9]);
 3850:         } else {
 3851:             return $fullpath.'/'.$fname;
 3852:         }
 3853:     }
 3854:     if ($subdir eq 'scantron') {
 3855:         $fname = 'scantron_orig_'.$fname;
 3856:     } else {
 3857:         $fname="$subdir/$fname";
 3858:     }
 3859:     if ($context eq 'coursedoc') {
 3860: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3861: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3862:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3863:             return &finishuserfileupload($docuname,$docudom,
 3864: 					 $formname,$fname,$parser,$allfiles,
 3865: 					 $codebase,$thumbwidth,$thumbheight,
 3866:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3867:         } else {
 3868:             if ($env{'form.folder'}) {
 3869:                 $fname=$env{'form.folder'}.'/'.$fname;
 3870:             }
 3871:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3872: 				       $fname,$formname,$parser,
 3873: 				       $allfiles,$codebase,$mimetype);
 3874:         }
 3875:     } elsif (defined($destuname)) {
 3876:         my $docuname=$destuname;
 3877:         my $docudom=$destudom;
 3878: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3879: 				     $parser,$allfiles,$codebase,
 3880:                                      $thumbwidth,$thumbheight,
 3881:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3882:     } else {
 3883:         my $docuname=$env{'user.name'};
 3884:         my $docudom=$env{'user.domain'};
 3885:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3886:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3887:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3888:         }
 3889: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3890: 				     $parser,$allfiles,$codebase,
 3891:                                      $thumbwidth,$thumbheight,
 3892:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3893:     }
 3894: }
 3895: 
 3896: sub finishuserfileupload {
 3897:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3898:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3899:     my $path=$docudom.'/'.$docuname.'/';
 3900:     my $filepath=$perlvar{'lonDocRoot'};
 3901:   
 3902:     my ($fnamepath,$file,$fetchthumb);
 3903:     $file=$fname;
 3904:     if ($fname=~m|/|) {
 3905:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3906: 	$path.=$fnamepath.'/';
 3907:     }
 3908:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3909:     my $count;
 3910:     for ($count=4;$count<=$#parts;$count++) {
 3911:         $filepath.="/$parts[$count]";
 3912:         if ((-e $filepath)!=1) {
 3913: 	    mkdir($filepath,0777);
 3914:         }
 3915:     }
 3916: 
 3917: # Save the file
 3918:     {
 3919: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 3920: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3921: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3922: 	    return '/adm/notfound.html';
 3923: 	}
 3924:         if ($context eq 'overwrite') {
 3925:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3926:             my $target = $filepath.'/'.$file;
 3927:             if (-e $source) {
 3928:                 my @info = stat($source);
 3929:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3930:                     unless (&File::Copy::move($source,$target)) {
 3931:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3932:                         return "Moving from $source failed";
 3933:                     }
 3934:                 } else {
 3935:                     return "Temporary file: $source had unexpected date/time for last modification";
 3936:                 }
 3937:             } else {
 3938:                 return "Temporary file: $source missing";
 3939:             }
 3940:         } elsif (!print FH ($env{'form.'.$formname})) {
 3941: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3942: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3943: 	    return '/adm/notfound.html';
 3944: 	}
 3945: 	close(FH);
 3946:         if ($resizewidth && $resizeheight) {
 3947:             my $mm = new File::MMagic;
 3948:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3949:             if ($mime_type =~ m{^image/}) {
 3950: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3951:             }  
 3952: 	}
 3953:     }
 3954:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3955:         if (ref($mimetype)) {
 3956:             if ($$mimetype eq '') {
 3957:                 my $mm = new File::MMagic;
 3958:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3959:                 $$mimetype = $type;
 3960:             }
 3961:         }
 3962:     }
 3963:     if ($parser eq 'parse') {
 3964:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3965:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3966:                                                        $allfiles,$codebase);
 3967:             unless ($parse_result eq 'ok') {
 3968:                 &logthis('Failed to parse '.$filepath.$file.
 3969: 	   	         ' for embedded media: '.$parse_result); 
 3970:             }
 3971:         }
 3972:     }
 3973:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3974:         my $input = $filepath.'/'.$file;
 3975:         my $output = $filepath.'/'.'tn-'.$file;
 3976:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3977:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 3978:         system({$args[0]} @args);
 3979:         if (-e $filepath.'/'.'tn-'.$file) {
 3980:             $fetchthumb  = 1; 
 3981:         }
 3982:     }
 3983:  
 3984: # Notify homeserver to grep it
 3985: #
 3986:     my $docuhome=&homeserver($docuname,$docudom);	
 3987:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3988:     if ($fetchresult eq 'ok') {
 3989:         if ($fetchthumb) {
 3990:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3991:             if ($thumbresult ne 'ok') {
 3992:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3993:                          $docuhome.': '.$thumbresult);
 3994:             }
 3995:         }
 3996: #
 3997: # Return the URL to it
 3998:         return '/uploaded/'.$path.$file;
 3999:     } else {
 4000:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4001: 		 ': '.$fetchresult);
 4002:         return '/adm/notfound.html';
 4003:     }
 4004: }
 4005: 
 4006: sub extract_embedded_items {
 4007:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4008:     my @state = ();
 4009:     my (%lastids,%related,%shockwave,%flashvars);
 4010:     my %javafiles = (
 4011:                       codebase => '',
 4012:                       code => '',
 4013:                       archive => ''
 4014:                     );
 4015:     my %mediafiles = (
 4016:                       src => '',
 4017:                       movie => '',
 4018:                      );
 4019:     my $p;
 4020:     if ($content) {
 4021:         $p = HTML::LCParser->new($content);
 4022:     } else {
 4023:         $p = HTML::LCParser->new($fullpath);
 4024:     }
 4025:     while (my $t=$p->get_token()) {
 4026: 	if ($t->[0] eq 'S') {
 4027: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4028: 	    push(@state, $tagname);
 4029:             if (lc($tagname) eq 'allow') {
 4030:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4031:             }
 4032: 	    if (lc($tagname) eq 'img') {
 4033: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4034: 	    }
 4035: 	    if (lc($tagname) eq 'a') {
 4036:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4037:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4038:                 }
 4039: 	    }
 4040:             if (lc($tagname) eq 'script') {
 4041:                 my $src;
 4042:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4043:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4044:                 } else {
 4045:                     if ($attr->{'src'} ne '') {
 4046:                         $src = $attr->{'src'};
 4047:                         &add_filetype($allfiles,$src,'src');
 4048:                     }
 4049:                 }
 4050:                 my $text = $p->get_trimmed_text();
 4051:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4052:                     my @swfargs = split(/,/,$1);
 4053:                     foreach my $item (@swfargs) {
 4054:                         $item =~ s/["']//g;
 4055:                         $item =~ s/^\s+//;
 4056:                         $item =~ s/\s+$//;
 4057:                     }
 4058:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4059:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4060:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4061:                         } else {
 4062:                             $related{$swfargs[0]} = [$swfargs[2]];
 4063:                         }
 4064:                     }
 4065:                 }
 4066:             }
 4067:             if (lc($tagname) eq 'link') {
 4068:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4069:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4070:                 }
 4071:             }
 4072: 	    if (lc($tagname) eq 'object' ||
 4073: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4074: 		foreach my $item (keys(%javafiles)) {
 4075: 		    $javafiles{$item} = '';
 4076: 		}
 4077:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4078:                     $lastids{lc($tagname)} = $attr->{'id'};
 4079:                 }
 4080: 	    }
 4081: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4082: 		my $name = lc($attr->{'name'});
 4083: 		foreach my $item (keys(%javafiles)) {
 4084: 		    if ($name eq $item) {
 4085: 			$javafiles{$item} = $attr->{'value'};
 4086: 			last;
 4087: 		    }
 4088: 		}
 4089:                 my $pathfrom;
 4090: 		foreach my $item (keys(%mediafiles)) {
 4091: 		    if ($name eq $item) {
 4092:                         $pathfrom = $attr->{'value'};
 4093:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4094: 			&add_filetype($allfiles,$pathfrom,$name);
 4095: 			last;
 4096: 		    }
 4097: 		}
 4098:                 if ($name eq 'flashvars') {
 4099:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4100:                 }
 4101:                 if ($pathfrom ne '') {
 4102:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4103:                                          $pathfrom);
 4104:                 }
 4105: 	    }
 4106: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4107: 		foreach my $item (keys(%javafiles)) {
 4108: 		    if ($attr->{$item}) {
 4109: 			$javafiles{$item} = $attr->{$item};
 4110: 			last;
 4111: 		    }
 4112: 		}
 4113: 		foreach my $item (keys(%mediafiles)) {
 4114: 		    if ($attr->{$item}) {
 4115: 			&add_filetype($allfiles,$attr->{$item},$item);
 4116: 			last;
 4117: 		    }
 4118: 		}
 4119:                 if (lc($tagname) eq 'embed') {
 4120:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4121:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4122:                                              $attr->{'src'});
 4123:                     }
 4124:                 }
 4125: 	    }
 4126:             if (lc($tagname) eq 'iframe') {
 4127:                 my $src = $attr->{'src'} ;
 4128:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4129:                     &add_filetype($allfiles,$src,'src');
 4130:                 } elsif ($src =~ m{^/}) {
 4131:                     if ($env{'request.course.id'}) {
 4132:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4133:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4134:                         my $url = &hreflocation('',$fullpath);
 4135:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4136:                             my $relpath = $1;
 4137:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4138:                                 &add_filetype($allfiles,$1,'src');
 4139:                             }
 4140:                         }
 4141:                     }
 4142:                 }
 4143:             }
 4144:             if ($t->[4] =~ m{/>$}) {
 4145:                 pop(@state);
 4146:             }
 4147: 	} elsif ($t->[0] eq 'E') {
 4148: 	    my ($tagname) = ($t->[1]);
 4149: 	    if ($javafiles{'codebase'} ne '') {
 4150: 		$javafiles{'codebase'} .= '/';
 4151: 	    }  
 4152: 	    if (lc($tagname) eq 'applet' ||
 4153: 		lc($tagname) eq 'object' ||
 4154: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4155: 		) {
 4156: 		foreach my $item (keys(%javafiles)) {
 4157: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4158: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4159: 			&add_filetype($allfiles,$file,$item);
 4160: 		    }
 4161: 		}
 4162: 	    } 
 4163: 	    pop @state;
 4164: 	}
 4165:     }
 4166:     foreach my $id (sort(keys(%flashvars))) {
 4167:         if ($shockwave{$id} ne '') {
 4168:             my @pairs = split(/\&/,$flashvars{$id});
 4169:             foreach my $pair (@pairs) {
 4170:                 my ($key,$value) = split(/\=/,$pair);
 4171:                 if ($key eq 'thumb') {
 4172:                     &add_filetype($allfiles,$value,$key);
 4173:                 } elsif ($key eq 'content') {
 4174:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4175:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4176:                     if ($ext ne '') {
 4177:                         &add_filetype($allfiles,$path.$value,$ext);
 4178:                     }
 4179:                 }
 4180:             }
 4181:         }
 4182:     }
 4183:     return 'ok';
 4184: }
 4185: 
 4186: sub add_filetype {
 4187:     my ($allfiles,$file,$type)=@_;
 4188:     if (exists($allfiles->{$file})) {
 4189: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4190: 	    push(@{$allfiles->{$file}}, &escape($type));
 4191: 	}
 4192:     } else {
 4193: 	@{$allfiles->{$file}} = (&escape($type));
 4194:     }
 4195: }
 4196: 
 4197: sub embedded_dependency {
 4198:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4199:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4200:         if (($identifier ne '') &&
 4201:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4202:             ($pathfrom ne '')) {
 4203:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4204:             foreach my $dep (@{$related->{$identifier}}) {
 4205:                 &add_filetype($allfiles,$path.$dep,'object');
 4206:             }
 4207:         }
 4208:     }
 4209:     return;
 4210: }
 4211: 
 4212: sub removeuploadedurl {
 4213:     my ($url)=@_;	
 4214:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4215:     return &removeuserfile($uname,$udom,$fname);
 4216: }
 4217: 
 4218: sub removeuserfile {
 4219:     my ($docuname,$docudom,$fname)=@_;
 4220:     my $home=&homeserver($docuname,$docudom);    
 4221:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4222:     if ($result eq 'ok') {	
 4223:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4224:             my $metafile = $fname.'.meta';
 4225:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4226: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4227:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4228:             my $sqlresult = 
 4229:                 &update_portfolio_table($docuname,$docudom,$file,
 4230:                                         'portfolio_metadata',$group,
 4231:                                         'delete');
 4232:         }
 4233:     }
 4234:     return $result;
 4235: }
 4236: 
 4237: sub mkdiruserfile {
 4238:     my ($docuname,$docudom,$dir)=@_;
 4239:     my $home=&homeserver($docuname,$docudom);
 4240:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4241: }
 4242: 
 4243: sub renameuserfile {
 4244:     my ($docuname,$docudom,$old,$new)=@_;
 4245:     my $home=&homeserver($docuname,$docudom);
 4246:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4247:                         &escape("$old").':'.&escape("$new"),$home);
 4248:     if ($result eq 'ok') {
 4249:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4250:             my $oldmeta = $old.'.meta';
 4251:             my $newmeta = $new.'.meta';
 4252:             my $metaresult = 
 4253:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4254: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4255:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4256:             my $sqlresult = 
 4257:                 &update_portfolio_table($docuname,$docudom,$file,
 4258:                                         'portfolio_metadata',$group,
 4259:                                         'delete');
 4260:         }
 4261:     }
 4262:     return $result;
 4263: }
 4264: 
 4265: # ------------------------------------------------------------------------- Log
 4266: 
 4267: sub log {
 4268:     my ($dom,$nam,$hom,$what)=@_;
 4269:     return critical("log:$dom:$nam:$what",$hom);
 4270: }
 4271: 
 4272: # ------------------------------------------------------------------ Course Log
 4273: #
 4274: # This routine flushes several buffers of non-mission-critical nature
 4275: #
 4276: 
 4277: sub flushcourselogs {
 4278:     &logthis('Flushing log buffers');
 4279: #
 4280: # course logs
 4281: # This is a log of all transactions in a course, which can be used
 4282: # for data mining purposes
 4283: #
 4284: # It also collects the courseid database, which lists last transaction
 4285: # times and course titles for all courseids
 4286: #
 4287:     my %courseidbuffer=();
 4288:     foreach my $crsid (keys(%courselogs)) {
 4289:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4290: 		          &escape($courselogs{$crsid}),
 4291: 		          $coursehombuf{$crsid}) eq 'ok') {
 4292: 	    delete $courselogs{$crsid};
 4293:         } else {
 4294:             &logthis('Failed to flush log buffer for '.$crsid);
 4295:             if (length($courselogs{$crsid})>40000) {
 4296:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4297:                         " exceeded maximum size, deleting.</font>");
 4298:                delete $courselogs{$crsid};
 4299:             }
 4300:         }
 4301:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4302:             'description' => $coursedescrbuf{$crsid},
 4303:             'inst_code'    => $courseinstcodebuf{$crsid},
 4304:             'type'        => $coursetypebuf{$crsid},
 4305:             'owner'       => $courseownerbuf{$crsid},
 4306:         };
 4307:     }
 4308: #
 4309: # Write course id database (reverse lookup) to homeserver of courses 
 4310: # Is used in pickcourse
 4311: #
 4312:     foreach my $crs_home (keys(%courseidbuffer)) {
 4313:         my $response = &courseidput(&host_domain($crs_home),
 4314:                                     $courseidbuffer{$crs_home},
 4315:                                     $crs_home,'timeonly');
 4316:     }
 4317: #
 4318: # File accesses
 4319: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4320: #
 4321:     foreach my $entry (keys(%accesshash)) {
 4322:         if ($entry =~ /___count$/) {
 4323:             my ($dom,$name);
 4324:             ($dom,$name,undef)=
 4325: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4326:             if (! defined($dom) || $dom eq '' || 
 4327:                 ! defined($name) || $name eq '') {
 4328:                 my $cid = $env{'request.course.id'};
 4329:                 $dom  = $env{'request.'.$cid.'.domain'};
 4330:                 $name = $env{'request.'.$cid.'.num'};
 4331:             }
 4332:             my $value = $accesshash{$entry};
 4333:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4334:             my %temphash=($url => $value);
 4335:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4336:             if ($result eq 'ok') {
 4337:                 delete $accesshash{$entry};
 4338:             }
 4339:         } else {
 4340:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4341:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4342:             my %temphash=($entry => $accesshash{$entry});
 4343:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4344:                 delete $accesshash{$entry};
 4345:             }
 4346:         }
 4347:     }
 4348: #
 4349: # Roles
 4350: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4351: #
 4352:     foreach my $entry (keys(%userrolehash)) {
 4353:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4354: 	    split(/\:/,$entry);
 4355:         if (&Apache::lonnet::put('nohist_userroles',
 4356:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4357:                 $rudom,$runame) eq 'ok') {
 4358: 	    delete $userrolehash{$entry};
 4359:         }
 4360:     }
 4361: #
 4362: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4363: #
 4364:     my %domrolebuffer = ();
 4365:     foreach my $entry (keys(%domainrolehash)) {
 4366:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4367:         if ($domrolebuffer{$rudom}) {
 4368:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4369:                       '='.&escape($domainrolehash{$entry});
 4370:         } else {
 4371:             $domrolebuffer{$rudom}.=&escape($entry).
 4372:                       '='.&escape($domainrolehash{$entry});
 4373:         }
 4374:         delete $domainrolehash{$entry};
 4375:     }
 4376:     foreach my $dom (keys(%domrolebuffer)) {
 4377: 	my %servers;
 4378: 	if (defined(&domain($dom,'primary'))) {
 4379: 	    my $primary=&domain($dom,'primary');
 4380: 	    my $hostname=&hostname($primary);
 4381: 	    $servers{$primary} = $hostname;
 4382: 	} else { 
 4383: 	    %servers = &get_servers($dom,'library');
 4384: 	}
 4385: 	foreach my $tryserver (keys(%servers)) {
 4386: 	    if (&reply('domroleput:'.$dom.':'.
 4387: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4388: 		last;
 4389: 	    } else {  
 4390: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4391: 	    }
 4392:         }
 4393:     }
 4394:     $dumpcount++;
 4395: }
 4396: 
 4397: sub courselog {
 4398:     my $what=shift;
 4399:     $what=time.':'.$what;
 4400:     unless ($env{'request.course.id'}) { return ''; }
 4401:     $coursedombuf{$env{'request.course.id'}}=
 4402:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4403:     $coursenumbuf{$env{'request.course.id'}}=
 4404:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4405:     $coursehombuf{$env{'request.course.id'}}=
 4406:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4407:     $coursedescrbuf{$env{'request.course.id'}}=
 4408:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4409:     $courseinstcodebuf{$env{'request.course.id'}}=
 4410:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4411:     $courseownerbuf{$env{'request.course.id'}}=
 4412:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4413:     $coursetypebuf{$env{'request.course.id'}}=
 4414:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4415:     if (defined $courselogs{$env{'request.course.id'}}) {
 4416: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4417:     } else {
 4418: 	$courselogs{$env{'request.course.id'}}.=$what;
 4419:     }
 4420:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4421: 	&flushcourselogs();
 4422:     }
 4423: }
 4424: 
 4425: sub courseacclog {
 4426:     my $fnsymb=shift;
 4427:     unless ($env{'request.course.id'}) { return ''; }
 4428:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4429:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4430:         $what.=':POST';
 4431:         # FIXME: Probably ought to escape things....
 4432: 	foreach my $key (keys(%env)) {
 4433:             if ($key=~/^form\.(.*)/) {
 4434:                 my $formitem = $1;
 4435:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4436:                     $what.=':'.$formitem.'='.$env{$key};
 4437:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4438:                     $what.=':'.$formitem.'='.$env{$key};
 4439:                 }
 4440:             }
 4441:         }
 4442:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4443:         # FIXME: We should not be depending on a form parameter that someone
 4444:         # editing lonsearchcat.pm might change in the future.
 4445:         if ($env{'form.phase'} eq 'course_search') {
 4446:             $what.= ':POST';
 4447:             # FIXME: Probably ought to escape things....
 4448:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4449:                                  'crsdiscuss') {
 4450:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4451:             }
 4452:         }
 4453:     }
 4454:     &courselog($what);
 4455: }
 4456: 
 4457: sub countacc {
 4458:     my $url=&declutter(shift);
 4459:     return if (! defined($url) || $url eq '');
 4460:     unless ($env{'request.course.id'}) { return ''; }
 4461: #
 4462: # Mark that this url was used in this course
 4463: #
 4464:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4465: #
 4466: # Increase the access count for this resource in this child process
 4467: #
 4468:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4469:     $accesshash{$key}++;
 4470: }
 4471: 
 4472: sub linklog {
 4473:     my ($from,$to)=@_;
 4474:     $from=&declutter($from);
 4475:     $to=&declutter($to);
 4476:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4477:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4478: }
 4479: 
 4480: sub statslog {
 4481:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4482:     if ($users<2) { return; }
 4483:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4484:             'course'       => $env{'request.course.id'},
 4485:             'sections'     => '"all"',
 4486:             'num_students' => $users,
 4487:             'part'         => $part,
 4488:             'symb'         => $symb,
 4489:             'mean_tries'   => $av_attempts,
 4490:             'deg_of_diff'  => $degdiff});
 4491:     foreach my $key (keys(%dynstore)) {
 4492:         $accesshash{$key}=$dynstore{$key};
 4493:     }
 4494: }
 4495:   
 4496: sub userrolelog {
 4497:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4498:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4499:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4500:        $userrolehash
 4501:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4502:                     =$tend.':'.$tstart;
 4503:     }
 4504:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4505:        $userrolehash
 4506:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4507:                     =$tend.':'.$tstart;
 4508:     }
 4509:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4510:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4511:        $domainrolehash
 4512:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4513:                     = $tend.':'.$tstart;
 4514:     }
 4515: }
 4516: 
 4517: sub courserolelog {
 4518:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4519:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4520:         my $cdom = $1;
 4521:         my $cnum = $2;
 4522:         my $sec = $3;
 4523:         my $namespace = 'rolelog';
 4524:         my %storehash = (
 4525:                            role    => $trole,
 4526:                            start   => $tstart,
 4527:                            end     => $tend,
 4528:                            selfenroll => $selfenroll,
 4529:                            context    => $context,
 4530:                         );
 4531:         if ($trole eq 'gr') {
 4532:             $namespace = 'groupslog';
 4533:             $storehash{'group'} = $sec;
 4534:         } else {
 4535:             $storehash{'section'} = $sec;
 4536:         }
 4537:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4538:                    $domain,$cnum,$cdom);
 4539:         if (($trole ne 'st') || ($sec ne '')) {
 4540:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4541:         }
 4542:     }
 4543:     return;
 4544: }
 4545: 
 4546: sub domainrolelog {
 4547:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4548:     if ($area =~ m{^/($match_domain)/$}) {
 4549:         my $cdom = $1;
 4550:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4551:         my $namespace = 'rolelog';
 4552:         my %storehash = (
 4553:                            role    => $trole,
 4554:                            start   => $tstart,
 4555:                            end     => $tend,
 4556:                            context => $context,
 4557:                         );
 4558:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4559:                    $domain,$domconfiguser,$cdom);
 4560:     }
 4561:     return;
 4562: 
 4563: }
 4564: 
 4565: sub coauthorrolelog {
 4566:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4567:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4568:         my $audom = $1;
 4569:         my $auname = $2;
 4570:         my $namespace = 'rolelog';
 4571:         my %storehash = (
 4572:                            role    => $trole,
 4573:                            start   => $tstart,
 4574:                            end     => $tend,
 4575:                            context => $context,
 4576:                         );
 4577:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4578:                    $domain,$auname,$audom);
 4579:     }
 4580:     return;
 4581: }
 4582: 
 4583: sub get_course_adv_roles {
 4584:     my ($cid,$codes) = @_;
 4585:     $cid=$env{'request.course.id'} unless (defined($cid));
 4586:     my %coursehash=&coursedescription($cid);
 4587:     my $crstype = &Apache::loncommon::course_type($cid);
 4588:     my %nothide=();
 4589:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4590:         if ($user !~ /:/) {
 4591: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4592:         } else {
 4593:             $nothide{$user}=1;
 4594:         }
 4595:     }
 4596:     my @possdoms = ($coursehash{'domain'});
 4597:     if ($coursehash{'checkforpriv'}) {
 4598:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4599:     }
 4600:     my %returnhash=();
 4601:     my %dumphash=
 4602:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4603:     my $now=time;
 4604:     my %privileged;
 4605:     foreach my $entry (keys(%dumphash)) {
 4606: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4607:         if (($tstart) && ($tstart<0)) { next; }
 4608:         if (($tend) && ($tend<$now)) { next; }
 4609:         if (($tstart) && ($now<$tstart)) { next; }
 4610:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4611: 	if ($username eq '' || $domain eq '') { next; }
 4612:         if ((&privileged($username,$domain,\@possdoms)) &&
 4613:             (!$nothide{$username.':'.$domain})) { next; }
 4614: 	if ($role eq 'cr') { next; }
 4615:         if ($codes) {
 4616:             if ($section) { $role .= ':'.$section; }
 4617:             if ($returnhash{$role}) {
 4618:                 $returnhash{$role}.=','.$username.':'.$domain;
 4619:             } else {
 4620:                 $returnhash{$role}=$username.':'.$domain;
 4621:             }
 4622:         } else {
 4623:             my $key=&plaintext($role,$crstype);
 4624:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4625:             if ($returnhash{$key}) {
 4626: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4627:             } else {
 4628:                 $returnhash{$key}=$username.':'.$domain;
 4629:             }
 4630:         }
 4631:     }
 4632:     return %returnhash;
 4633: }
 4634: 
 4635: sub get_my_roles {
 4636:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4637:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4638:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4639:     my (%dumphash,%nothide);
 4640:     if ($context eq 'userroles') {
 4641:         %dumphash = &dump('roles',$udom,$uname);
 4642:     } else {
 4643:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4644:         if ($hidepriv) {
 4645:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4646:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4647:                 if ($user !~ /:/) {
 4648:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4649:                 } else {
 4650:                     $nothide{$user} = 1;
 4651:                 }
 4652:             }
 4653:         }
 4654:     }
 4655:     my %returnhash=();
 4656:     my $now=time;
 4657:     my %privileged;
 4658:     foreach my $entry (keys(%dumphash)) {
 4659:         my ($role,$tend,$tstart);
 4660:         if ($context eq 'userroles') {
 4661:             next if ($entry =~ /^rolesdef/);
 4662: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4663:         } else {
 4664:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4665:         }
 4666:         if (($tstart) && ($tstart<0)) { next; }
 4667:         my $status = 'active';
 4668:         if (($tend) && ($tend<=$now)) {
 4669:             $status = 'previous';
 4670:         } 
 4671:         if (($tstart) && ($now<$tstart)) {
 4672:             $status = 'future';
 4673:         }
 4674:         if (ref($types) eq 'ARRAY') {
 4675:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4676:                 next;
 4677:             } 
 4678:         } else {
 4679:             if ($status ne 'active') {
 4680:                 next;
 4681:             }
 4682:         }
 4683:         my ($rolecode,$username,$domain,$section,$area);
 4684:         if ($context eq 'userroles') {
 4685:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4686:             (undef,$domain,$username,$section) = split(/\//,$area);
 4687:         } else {
 4688:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4689:         }
 4690:         if (ref($roledoms) eq 'ARRAY') {
 4691:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4692:                 next;
 4693:             }
 4694:         }
 4695:         if (ref($roles) eq 'ARRAY') {
 4696:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4697:                 if ($role =~ /^cr\//) {
 4698:                     if (!grep(/^cr$/,@{$roles})) {
 4699:                         next;
 4700:                     }
 4701:                 } elsif ($role =~ /^gr\//) {
 4702:                     if (!grep(/^gr$/,@{$roles})) {
 4703:                         next;
 4704:                     }
 4705:                 } else {
 4706:                     next;
 4707:                 }
 4708:             }
 4709:         }
 4710:         if ($hidepriv) {
 4711:             my @privroles = ('dc','su');
 4712:             if ($context eq 'userroles') {
 4713:                 next if (grep(/^\Q$role\E$/,@privroles));
 4714:             } else {
 4715:                 my $possdoms = [$domain];
 4716:                 if (ref($roledoms) eq 'ARRAY') {
 4717:                    push(@{$possdoms},@{$roledoms}); 
 4718:                 }
 4719:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4720:                     if (!$nothide{$username.':'.$domain}) {
 4721:                         next;
 4722:                     }
 4723:                 }
 4724:             }
 4725:         }
 4726:         if ($withsec) {
 4727:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4728:                 $tstart.':'.$tend;
 4729:         } else {
 4730:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4731:         }
 4732:     }
 4733:     return %returnhash;
 4734: }
 4735: 
 4736: sub get_all_adhocroles {
 4737:     my ($dom) = @_;
 4738:     my @roles_by_num = ();
 4739:     my %domdefaults = &get_domain_defaults($dom);
 4740:     my (%description,%access_in_dom,%access_info);
 4741:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4742:         my $count = 0;
 4743:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4744:         my %ordered;
 4745:         foreach my $role (sort(keys(%domcurrent))) {
 4746:             my ($order,$desc,$access_in_dom);
 4747:             if (ref($domcurrent{$role}) eq 'HASH') {
 4748:                 $order = $domcurrent{$role}{'order'};
 4749:                 $desc = $domcurrent{$role}{'desc'};
 4750:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4751:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4752:             }
 4753:             if ($order eq '') {
 4754:                 $order = $count;
 4755:             }
 4756:             $ordered{$order} = $role;
 4757:             if ($desc ne '') {
 4758:                 $description{$role} = $desc;
 4759:             } else {
 4760:                 $description{$role}= $role;
 4761:             }
 4762:             $count++;
 4763:         }
 4764:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4765:             push(@roles_by_num,$ordered{$item});
 4766:         }
 4767:     }
 4768:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4769: }
 4770: 
 4771: sub get_my_adhocroles {
 4772:     my ($cid,$checkreg) = @_;
 4773:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4774:     if ($env{'request.course.id'} eq $cid) {
 4775:         $cdom = $env{'course.'.$cid.'.domain'};
 4776:         $cnum = $env{'course.'.$cid.'.num'};
 4777:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4778:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4779:         $cdom = $1;
 4780:         $cnum = $2;
 4781:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4782:                                      $cdom,$cnum);
 4783:     }
 4784:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4785:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4786:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4787:         if ($rosterhash{$user} ne '') {
 4788:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4789:             return ([],{}) if ($type eq 'auto');
 4790:         }
 4791:     }
 4792:     if (($cdom ne '') && ($cnum ne ''))  {
 4793:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4794:             my $then=$env{'user.login.time'};
 4795:             my $update=$env{'user.update.time'};
 4796:             if (!$update) {
 4797:                 $update = $then;
 4798:             }
 4799:             my @liveroles;
 4800:             foreach my $role ('dh','da') {
 4801:                 if ($env{"user.role.$role./$cdom/"}) {
 4802:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4803:                     my $limit = $update;
 4804:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4805:                         $limit = $then;
 4806:                     }
 4807:                     my $activerole = 1;
 4808:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4809:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4810:                     if ($activerole) {
 4811:                         push(@liveroles,$role);
 4812:                     }
 4813:                 }
 4814:             }
 4815:             if (@liveroles) {
 4816:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4817:                     my ($accessref,$accessinfo,%access_in_dom);
 4818:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4819:                     if (ref($roles_by_num) eq 'ARRAY') {
 4820:                         if (@{$roles_by_num}) {
 4821:                             my %settings;
 4822:                             if ($env{'request.course.id'} eq $cid) {
 4823:                                 foreach my $envkey (keys(%env)) {
 4824:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4825:                                         $settings{$1} = $env{$envkey};
 4826:                                     }
 4827:                                 }
 4828:                             } else {
 4829:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4830:                             }
 4831:                             my %setincrs;
 4832:                             if ($settings{'internal.adhocaccess'}) {
 4833:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4834:                             }
 4835:                             my @statuses;
 4836:                             if ($env{'environment.inststatus'}) {
 4837:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4838:                             }
 4839:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4840:                             if (ref($accessref) eq 'HASH') {
 4841:                                 %access_in_dom = %{$accessref};
 4842:                             }
 4843:                             foreach my $role (@{$roles_by_num}) {
 4844:                                 my ($curraccess,@okstatus,@personnel);
 4845:                                 if ($setincrs{$role}) {
 4846:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4847:                                     if ($curraccess eq 'status') {
 4848:                                         @okstatus = split(/\&/,$rest);
 4849:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4850:                                         @personnel = split(/\&/,$rest);
 4851:                                     }
 4852:                                 } else {
 4853:                                     $curraccess = $access_in_dom{$role};
 4854:                                     if (ref($accessinfo) eq 'HASH') {
 4855:                                         if ($curraccess eq 'status') {
 4856:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4857:                                                 @okstatus = @{$accessinfo->{$role}};
 4858:                                             }
 4859:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4860:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4861:                                                 @personnel = @{$accessinfo->{$role}};
 4862:                                             }
 4863:                                         }
 4864:                                     }
 4865:                                 }
 4866:                                 if ($curraccess eq 'none') {
 4867:                                     next;
 4868:                                 } elsif ($curraccess eq 'all') {
 4869:                                     push(@possroles,$role);
 4870:                                 } elsif ($curraccess eq 'dh') {
 4871:                                     if (grep(/^dh$/,@liveroles)) {
 4872:                                         push(@possroles,$role);
 4873:                                     } else {
 4874:                                         next;
 4875:                                     }
 4876:                                 } elsif ($curraccess eq 'da') {
 4877:                                     if (grep(/^da$/,@liveroles)) {
 4878:                                         push(@possroles,$role);
 4879:                                     } else {
 4880:                                         next;
 4881:                                     }
 4882:                                 } elsif ($curraccess eq 'status') {
 4883:                                     if (@okstatus) {
 4884:                                         if (!@statuses) {
 4885:                                             if (grep(/^default$/,@okstatus)) {
 4886:                                                 push(@possroles,$role);
 4887:                                             }
 4888:                                         } else {
 4889:                                             foreach my $status (@okstatus) {
 4890:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 4891:                                                     push(@possroles,$role);
 4892:                                                     last;
 4893:                                                 }
 4894:                                             }
 4895:                                         }
 4896:                                     }
 4897:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4898:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 4899:                                         if ($curraccess eq 'exc') {
 4900:                                             push(@possroles,$role);
 4901:                                         }
 4902:                                     } elsif ($curraccess eq 'inc') {
 4903:                                         push(@possroles,$role);
 4904:                                     }
 4905:                                 }
 4906:                             }
 4907:                         }
 4908:                     }
 4909:                 }
 4910:             }
 4911:         }
 4912:     }
 4913:     unless (ref($description) eq 'HASH') {
 4914:         if (ref($roles_by_num) eq 'ARRAY') {
 4915:             my %desc;
 4916:             map { $desc{$_} = $_; } (@{$roles_by_num});
 4917:             $description = \%desc;
 4918:         } else {
 4919:             $description = {};
 4920:         }
 4921:     }
 4922:     return (\@possroles,$description);
 4923: }
 4924: 
 4925: # ----------------------------------------------------- Frontpage Announcements
 4926: #
 4927: #
 4928: 
 4929: sub postannounce {
 4930:     my ($server,$text)=@_;
 4931:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4932:     unless ($text=~/\w/) { $text=''; }
 4933:     return &reply('setannounce:'.&escape($text),$server);
 4934: }
 4935: 
 4936: sub getannounce {
 4937: 
 4938:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4939: 	my $announcement='';
 4940: 	while (my $line = <$fh>) { $announcement .= $line; }
 4941: 	close($fh);
 4942: 	if ($announcement=~/\w/) { 
 4943: 	    return 
 4944:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4945:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4946: 	} else {
 4947: 	    return '';
 4948: 	}
 4949:     } else {
 4950: 	return '';
 4951:     }
 4952: }
 4953: 
 4954: # ---------------------------------------------------------- Course ID routines
 4955: # Deal with domain's nohist_courseid.db files
 4956: #
 4957: 
 4958: sub courseidput {
 4959:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4960:     return unless (ref($storehash) eq 'HASH');
 4961:     my $outcome;
 4962:     if ($caller eq 'timeonly') {
 4963:         my $cids = '';
 4964:         foreach my $item (keys(%$storehash)) {
 4965:             $cids.=&escape($item).'&';
 4966:         }
 4967:         $cids=~s/\&$//;
 4968:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4969:                           $coursehome);       
 4970:     } else {
 4971:         my $items = '';
 4972:         foreach my $item (keys(%$storehash)) {
 4973:             $items.= &escape($item).'='.
 4974:                      &freeze_escape($$storehash{$item}).'&';
 4975:         }
 4976:         $items=~s/\&$//;
 4977:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4978:                           $coursehome);
 4979:     }
 4980:     if ($outcome eq 'unknown_cmd') {
 4981:         my $what;
 4982:         foreach my $cid (keys(%$storehash)) {
 4983:             $what .= &escape($cid).'=';
 4984:             foreach my $item ('description','inst_code','owner','type') {
 4985:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4986:             }
 4987:             $what =~ s/\:$/&/;
 4988:         }
 4989:         $what =~ s/\&$//;  
 4990:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4991:     } else {
 4992:         return $outcome;
 4993:     }
 4994: }
 4995: 
 4996: sub courseiddump {
 4997:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4998:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4999:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5000:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5001:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5002:     my $as_hash = 1;
 5003:     my %returnhash;
 5004:     if (!$domfilter) { $domfilter=''; }
 5005:     my %libserv = &all_library();
 5006:     foreach my $tryserver (keys(%libserv)) {
 5007:         if ( (  $hostidflag == 1 
 5008: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5009: 	     || (!defined($hostidflag)) ) {
 5010: 
 5011: 	    if (($domfilter eq '') ||
 5012: 		(&host_domain($tryserver) eq $domfilter)) {
 5013:                 my $rep;
 5014:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5015:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5016:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5017:                                 &escape($descfilter), &escape($instcodefilter), 
 5018:                                 &escape($ownerfilter), &escape($coursefilter),
 5019:                                 &escape($typefilter), &escape($regexp_ok), 
 5020:                                 $as_hash, &escape($selfenrollonly), 
 5021:                                 &escape($catfilter), $showhidden, $caller, 
 5022:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5023:                                 &escape($createdbefore), &escape($createdafter), 
 5024:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5025:                                 $reqcrsdom,&escape($reqinstcode))));
 5026:                 } else {
 5027:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5028:                              $sincefilter.':'.&escape($descfilter).':'.
 5029:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5030:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5031:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5032:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5033:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5034:                              &escape($cc_clone).':'.$cloneonly.':'.
 5035:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5036:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5037:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5038:                 }
 5039:                      
 5040:                 my @pairs=split(/\&/,$rep);
 5041:                 foreach my $item (@pairs) {
 5042:                     my ($key,$value)=split(/\=/,$item,2);
 5043:                     $key = &unescape($key);
 5044:                     next if ($key =~ /^error: 2 /);
 5045:                     my $result = &thaw_unescape($value);
 5046:                     if (ref($result) eq 'HASH') {
 5047:                         $returnhash{$key}=$result;
 5048:                     } else {
 5049:                         my @responses = split(/:/,$value);
 5050:                         my @items = ('description','inst_code','owner','type');
 5051:                         for (my $i=0; $i<@responses; $i++) {
 5052:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5053:                         }
 5054:                     }
 5055:                 }
 5056:             }
 5057:         }
 5058:     }
 5059:     return %returnhash;
 5060: }
 5061: 
 5062: sub courselastaccess {
 5063:     my ($cdom,$cnum,$hostidref) = @_;
 5064:     my %returnhash;
 5065:     if ($cdom && $cnum) {
 5066:         my $chome = &homeserver($cnum,$cdom);
 5067:         if ($chome ne 'no_host') {
 5068:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5069:             &extract_lastaccess(\%returnhash,$rep);
 5070:         }
 5071:     } else {
 5072:         if (!$cdom) { $cdom=''; }
 5073:         my %libserv = &all_library();
 5074:         foreach my $tryserver (keys(%libserv)) {
 5075:             if (ref($hostidref) eq 'ARRAY') {
 5076:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5077:             } 
 5078:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5079:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5080:                 &extract_lastaccess(\%returnhash,$rep);
 5081:             }
 5082:         }
 5083:     }
 5084:     return %returnhash;
 5085: }
 5086: 
 5087: sub extract_lastaccess {
 5088:     my ($returnhash,$rep) = @_;
 5089:     if (ref($returnhash) eq 'HASH') {
 5090:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5091:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5092:                  $rep eq '') {
 5093:             my @pairs=split(/\&/,$rep);
 5094:             foreach my $item (@pairs) {
 5095:                 my ($key,$value)=split(/\=/,$item,2);
 5096:                 $key = &unescape($key);
 5097:                 next if ($key =~ /^error: 2 /);
 5098:                 $returnhash->{$key} = &thaw_unescape($value);
 5099:             }
 5100:         }
 5101:     }
 5102:     return;
 5103: }
 5104: 
 5105: # ---------------------------------------------------------- DC e-mail
 5106: 
 5107: sub dcmailput {
 5108:     my ($domain,$msgid,$message,$server)=@_;
 5109:     my $status = &Apache::lonnet::critical(
 5110:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5111:        &escape($message),$server);
 5112:     return $status;
 5113: }
 5114: 
 5115: sub dcmaildump {
 5116:     my ($dom,$startdate,$enddate,$senders) = @_;
 5117:     my %returnhash=();
 5118: 
 5119:     if (defined(&domain($dom,'primary'))) {
 5120:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5121:                                                          &escape($enddate).':';
 5122: 	my @esc_senders=map { &escape($_)} @$senders;
 5123: 	$cmd.=&escape(join('&',@esc_senders));
 5124: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5125:             my ($key,$value) = split(/\=/,$line,2);
 5126:             if (($key) && ($value)) {
 5127:                 $returnhash{&unescape($key)} = &unescape($value);
 5128:             }
 5129:         }
 5130:     }
 5131:     return %returnhash;
 5132: }
 5133: # ---------------------------------------------------------- Domain roles
 5134: 
 5135: sub get_domain_roles {
 5136:     my ($dom,$roles,$startdate,$enddate)=@_;
 5137:     if ((!defined($startdate)) || ($startdate eq '')) {
 5138:         $startdate = '.';
 5139:     }
 5140:     if ((!defined($enddate)) || ($enddate eq '')) {
 5141:         $enddate = '.';
 5142:     }
 5143:     my $rolelist;
 5144:     if (ref($roles) eq 'ARRAY') {
 5145:         $rolelist = join('&',@{$roles});
 5146:     }
 5147:     my %personnel = ();
 5148: 
 5149:     my %servers = &get_servers($dom,'library');
 5150:     foreach my $tryserver (keys(%servers)) {
 5151: 	%{$personnel{$tryserver}}=();
 5152: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5153: 					    &escape($startdate).':'.
 5154: 					    &escape($enddate).':'.
 5155: 					    &escape($rolelist), $tryserver))) {
 5156: 	    my ($key,$value) = split(/\=/,$line,2);
 5157: 	    if (($key) && ($value)) {
 5158: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5159: 	    }
 5160: 	}
 5161:     }
 5162:     return %personnel;
 5163: }
 5164: 
 5165: sub get_active_domroles {
 5166:     my ($dom,$roles) = @_;
 5167:     return () unless (ref($roles) eq 'ARRAY');
 5168:     my $now = time;
 5169:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5170:     my %domroles;
 5171:     foreach my $server (keys(%dompersonnel)) {
 5172:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5173:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5174:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5175:         }
 5176:     }
 5177:     return %domroles;
 5178: }
 5179: 
 5180: # ----------------------------------------------------------- Interval timing 
 5181: 
 5182: {
 5183: # Caches needed for speedup of navmaps
 5184: # We don't want to cache this for very long at all (5 seconds at most)
 5185: # 
 5186: # The user for whom we cache
 5187: my $cachedkey='';
 5188: # The cached times for this user
 5189: my %cachedtimes=();
 5190: # When this was last done
 5191: my $cachedtime='';
 5192: 
 5193: sub load_all_first_access {
 5194:     my ($uname,$udom,$ignorecache)=@_;
 5195:     if (($cachedkey eq $uname.':'.$udom) &&
 5196:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5197:         (!$ignorecache)) {
 5198:         return;
 5199:     }
 5200:     $cachedtime=time;
 5201:     $cachedkey=$uname.':'.$udom;
 5202:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5203: }
 5204: 
 5205: sub get_first_access {
 5206:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5207:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5208:     if ($argsymb) { $symb=$argsymb; }
 5209:     my ($map,$id,$res)=&decode_symb($symb);
 5210:     if ($argmap) { $map = $argmap; }
 5211:     if ($type eq 'course') {
 5212: 	$res='course';
 5213:     } elsif ($type eq 'map') {
 5214: 	$res=&symbread($map);
 5215:     } else {
 5216: 	$res=$symb;
 5217:     }
 5218:     &load_all_first_access($uname,$udom,$ignorecache);
 5219:     return $cachedtimes{"$courseid\0$res"};
 5220: }
 5221: 
 5222: sub set_first_access {
 5223:     my ($type,$interval)=@_;
 5224:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5225:     my ($map,$id,$res)=&decode_symb($symb);
 5226:     if ($type eq 'course') {
 5227: 	$res='course';
 5228:     } elsif ($type eq 'map') {
 5229: 	$res=&symbread($map);
 5230:     } else {
 5231: 	$res=$symb;
 5232:     }
 5233:     $cachedkey='';
 5234:     my $firstaccess=&get_first_access($type,$symb,$map);
 5235:     if (!$firstaccess) {
 5236:         my $start = time;
 5237: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5238:                           $udom,$uname);
 5239:         if ($putres eq 'ok') {
 5240:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5241:                  $udom,$uname); 
 5242:             &appenv(
 5243:                      {
 5244:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5245:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5246:                      }
 5247:                   );
 5248:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5249:                 $cachedtimes{"$courseid\0$res"} = $start;
 5250:             }
 5251:         }
 5252:         return $putres;
 5253:     }
 5254:     return 'already_set';
 5255: }
 5256: }
 5257: 
 5258: # --------------------------------------------- Set Expire Date for Spreadsheet
 5259: 
 5260: sub expirespread {
 5261:     my ($uname,$udom,$stype,$usymb)=@_;
 5262:     my $cid=$env{'request.course.id'}; 
 5263:     if ($cid) {
 5264:        my $now=time;
 5265:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5266:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5267:                             $env{'course.'.$cid.'.num'}.
 5268: 	        	    ':nohist_expirationdates:'.
 5269:                             &escape($key).'='.$now,
 5270:                             $env{'course.'.$cid.'.home'})
 5271:     }
 5272:     return 'ok';
 5273: }
 5274: 
 5275: # ----------------------------------------------------- Devalidate Spreadsheets
 5276: 
 5277: sub devalidate {
 5278:     my ($symb,$uname,$udom)=@_;
 5279:     my $cid=$env{'request.course.id'}; 
 5280:     if ($cid) {
 5281:         # delete the stored spreadsheets for
 5282:         # - the student level sheet of this user in course's homespace
 5283:         # - the assessment level sheet for this resource 
 5284:         #   for this user in user's homespace
 5285: 	# - current conditional state info
 5286: 	my $key=$uname.':'.$udom.':';
 5287:         my $status=
 5288: 	    &del('nohist_calculatedsheets',
 5289: 		 [$key.'studentcalc:'],
 5290: 		 $env{'course.'.$cid.'.domain'},
 5291: 		 $env{'course.'.$cid.'.num'})
 5292: 		.' '.
 5293: 	    &del('nohist_calculatedsheets_'.$cid,
 5294: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5295:         unless ($status eq 'ok ok') {
 5296:            &logthis('Could not devalidate spreadsheet '.
 5297:                     $uname.' at '.$udom.' for '.
 5298: 		    $symb.': '.$status);
 5299:         }
 5300: 	&delenv('user.state.'.$cid);
 5301:     }
 5302: }
 5303: 
 5304: sub get_scalar {
 5305:     my ($string,$end) = @_;
 5306:     my $value;
 5307:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5308: 	$value = $1;
 5309:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5310: 	$value = $1;
 5311:     }
 5312:     return &unescape($value);
 5313: }
 5314: 
 5315: sub array2str {
 5316:   my (@array) = @_;
 5317:   my $result=&arrayref2str(\@array);
 5318:   $result=~s/^__ARRAY_REF__//;
 5319:   $result=~s/__END_ARRAY_REF__$//;
 5320:   return $result;
 5321: }
 5322: 
 5323: sub arrayref2str {
 5324:   my ($arrayref) = @_;
 5325:   my $result='__ARRAY_REF__';
 5326:   foreach my $elem (@$arrayref) {
 5327:     if(ref($elem) eq 'ARRAY') {
 5328:       $result.=&arrayref2str($elem).'&';
 5329:     } elsif(ref($elem) eq 'HASH') {
 5330:       $result.=&hashref2str($elem).'&';
 5331:     } elsif(ref($elem)) {
 5332:       #print("Got a ref of ".(ref($elem))." skipping.");
 5333:     } else {
 5334:       $result.=&escape($elem).'&';
 5335:     }
 5336:   }
 5337:   $result=~s/\&$//;
 5338:   $result .= '__END_ARRAY_REF__';
 5339:   return $result;
 5340: }
 5341: 
 5342: sub hash2str {
 5343:   my (%hash) = @_;
 5344:   my $result=&hashref2str(\%hash);
 5345:   $result=~s/^__HASH_REF__//;
 5346:   $result=~s/__END_HASH_REF__$//;
 5347:   return $result;
 5348: }
 5349: 
 5350: sub hashref2str {
 5351:   my ($hashref)=@_;
 5352:   my $result='__HASH_REF__';
 5353:   foreach my $key (sort(keys(%$hashref))) {
 5354:     if (ref($key) eq 'ARRAY') {
 5355:       $result.=&arrayref2str($key).'=';
 5356:     } elsif (ref($key) eq 'HASH') {
 5357:       $result.=&hashref2str($key).'=';
 5358:     } elsif (ref($key)) {
 5359:       $result.='=';
 5360:       #print("Got a ref of ".(ref($key))." skipping.");
 5361:     } else {
 5362: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5363:     }
 5364: 
 5365:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5366:       $result.=&arrayref2str($hashref->{$key}).'&';
 5367:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5368:       $result.=&hashref2str($hashref->{$key}).'&';
 5369:     } elsif(ref($hashref->{$key})) {
 5370:        $result.='&';
 5371:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5372:     } else {
 5373:       $result.=&escape($hashref->{$key}).'&';
 5374:     }
 5375:   }
 5376:   $result=~s/\&$//;
 5377:   $result .= '__END_HASH_REF__';
 5378:   return $result;
 5379: }
 5380: 
 5381: sub str2hash {
 5382:     my ($string)=@_;
 5383:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5384:     return %$hash;
 5385: }
 5386: 
 5387: sub str2hashref {
 5388:   my ($string) = @_;
 5389: 
 5390:   my %hash;
 5391: 
 5392:   if($string !~ /^__HASH_REF__/) {
 5393:       if (! ($string eq '' || !defined($string))) {
 5394: 	  $hash{'error'}='Not hash reference';
 5395:       }
 5396:       return (\%hash, $string);
 5397:   }
 5398: 
 5399:   $string =~ s/^__HASH_REF__//;
 5400: 
 5401:   while($string !~ /^__END_HASH_REF__/) {
 5402:       #key
 5403:       my $key='';
 5404:       if($string =~ /^__HASH_REF__/) {
 5405:           ($key, $string)=&str2hashref($string);
 5406:           if(defined($key->{'error'})) {
 5407:               $hash{'error'}='Bad data';
 5408:               return (\%hash, $string);
 5409:           }
 5410:       } elsif($string =~ /^__ARRAY_REF__/) {
 5411:           ($key, $string)=&str2arrayref($string);
 5412:           if($key->[0] eq 'Array reference error') {
 5413:               $hash{'error'}='Bad data';
 5414:               return (\%hash, $string);
 5415:           }
 5416:       } else {
 5417:           $string =~ s/^(.*?)=//;
 5418: 	  $key=&unescape($1);
 5419:       }
 5420:       $string =~ s/^=//;
 5421: 
 5422:       #value
 5423:       my $value='';
 5424:       if($string =~ /^__HASH_REF__/) {
 5425:           ($value, $string)=&str2hashref($string);
 5426:           if(defined($value->{'error'})) {
 5427:               $hash{'error'}='Bad data';
 5428:               return (\%hash, $string);
 5429:           }
 5430:       } elsif($string =~ /^__ARRAY_REF__/) {
 5431:           ($value, $string)=&str2arrayref($string);
 5432:           if($value->[0] eq 'Array reference error') {
 5433:               $hash{'error'}='Bad data';
 5434:               return (\%hash, $string);
 5435:           }
 5436:       } else {
 5437: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5438:       }
 5439:       $string =~ s/^&//;
 5440: 
 5441:       $hash{$key}=$value;
 5442:   }
 5443: 
 5444:   $string =~ s/^__END_HASH_REF__//;
 5445: 
 5446:   return (\%hash, $string);
 5447: }
 5448: 
 5449: sub str2array {
 5450:     my ($string)=@_;
 5451:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5452:     return @$array;
 5453: }
 5454: 
 5455: sub str2arrayref {
 5456:   my ($string) = @_;
 5457:   my @array;
 5458: 
 5459:   if($string !~ /^__ARRAY_REF__/) {
 5460:       if (! ($string eq '' || !defined($string))) {
 5461: 	  $array[0]='Array reference error';
 5462:       }
 5463:       return (\@array, $string);
 5464:   }
 5465: 
 5466:   $string =~ s/^__ARRAY_REF__//;
 5467: 
 5468:   while($string !~ /^__END_ARRAY_REF__/) {
 5469:       my $value='';
 5470:       if($string =~ /^__HASH_REF__/) {
 5471:           ($value, $string)=&str2hashref($string);
 5472:           if(defined($value->{'error'})) {
 5473:               $array[0] ='Array reference error';
 5474:               return (\@array, $string);
 5475:           }
 5476:       } elsif($string =~ /^__ARRAY_REF__/) {
 5477:           ($value, $string)=&str2arrayref($string);
 5478:           if($value->[0] eq 'Array reference error') {
 5479:               $array[0] ='Array reference error';
 5480:               return (\@array, $string);
 5481:           }
 5482:       } else {
 5483: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5484:       }
 5485:       $string =~ s/^&//;
 5486: 
 5487:       push(@array, $value);
 5488:   }
 5489: 
 5490:   $string =~ s/^__END_ARRAY_REF__//;
 5491: 
 5492:   return (\@array, $string);
 5493: }
 5494: 
 5495: # -------------------------------------------------------------------Temp Store
 5496: 
 5497: sub tmpreset {
 5498:   my ($symb,$namespace,$domain,$stuname) = @_;
 5499:   if (!$symb) {
 5500:     $symb=&symbread();
 5501:     if (!$symb) { $symb= $env{'request.url'}; }
 5502:   }
 5503:   $symb=escape($symb);
 5504: 
 5505:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5506:   $namespace=~s/\//\_/g;
 5507:   $namespace=~s/\W//g;
 5508: 
 5509:   if (!$domain) { $domain=$env{'user.domain'}; }
 5510:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5511:   if ($domain eq 'public' && $stuname eq 'public') {
 5512:       $stuname=$ENV{'REMOTE_ADDR'};
 5513:   }
 5514:   my $path=LONCAPA::tempdir();
 5515:   my %hash;
 5516:   if (tie(%hash,'GDBM_File',
 5517: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5518: 	  &GDBM_WRCREAT(),0640)) {
 5519:     foreach my $key (keys(%hash)) {
 5520:       if ($key=~ /:$symb/) {
 5521: 	delete($hash{$key});
 5522:       }
 5523:     }
 5524:   }
 5525: }
 5526: 
 5527: sub tmpstore {
 5528:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5529: 
 5530:   if (!$symb) {
 5531:     $symb=&symbread();
 5532:     if (!$symb) { $symb= $env{'request.url'}; }
 5533:   }
 5534:   $symb=escape($symb);
 5535: 
 5536:   if (!$namespace) {
 5537:     # I don't think we would ever want to store this for a course.
 5538:     # it seems this will only be used if we don't have a course.
 5539:     #$namespace=$env{'request.course.id'};
 5540:     #if (!$namespace) {
 5541:       $namespace=$env{'request.state'};
 5542:     #}
 5543:   }
 5544:   $namespace=~s/\//\_/g;
 5545:   $namespace=~s/\W//g;
 5546:   if (!$domain) { $domain=$env{'user.domain'}; }
 5547:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5548:   if ($domain eq 'public' && $stuname eq 'public') {
 5549:       $stuname=$ENV{'REMOTE_ADDR'};
 5550:   }
 5551:   my $now=time;
 5552:   my %hash;
 5553:   my $path=LONCAPA::tempdir();
 5554:   if (tie(%hash,'GDBM_File',
 5555: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5556: 	  &GDBM_WRCREAT(),0640)) {
 5557:     $hash{"version:$symb"}++;
 5558:     my $version=$hash{"version:$symb"};
 5559:     my $allkeys=''; 
 5560:     foreach my $key (keys(%$storehash)) {
 5561:       $allkeys.=$key.':';
 5562:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5563:     }
 5564:     $hash{"$version:$symb:timestamp"}=$now;
 5565:     $allkeys.='timestamp';
 5566:     $hash{"$version:keys:$symb"}=$allkeys;
 5567:     if (untie(%hash)) {
 5568:       return 'ok';
 5569:     } else {
 5570:       return "error:$!";
 5571:     }
 5572:   } else {
 5573:     return "error:$!";
 5574:   }
 5575: }
 5576: 
 5577: # -----------------------------------------------------------------Temp Restore
 5578: 
 5579: sub tmprestore {
 5580:   my ($symb,$namespace,$domain,$stuname) = @_;
 5581: 
 5582:   if (!$symb) {
 5583:     $symb=&symbread();
 5584:     if (!$symb) { $symb= $env{'request.url'}; }
 5585:   }
 5586:   $symb=escape($symb);
 5587: 
 5588:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5589: 
 5590:   if (!$domain) { $domain=$env{'user.domain'}; }
 5591:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5592:   if ($domain eq 'public' && $stuname eq 'public') {
 5593:       $stuname=$ENV{'REMOTE_ADDR'};
 5594:   }
 5595:   my %returnhash;
 5596:   $namespace=~s/\//\_/g;
 5597:   $namespace=~s/\W//g;
 5598:   my %hash;
 5599:   my $path=LONCAPA::tempdir();
 5600:   if (tie(%hash,'GDBM_File',
 5601: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5602: 	  &GDBM_READER(),0640)) {
 5603:     my $version=$hash{"version:$symb"};
 5604:     $returnhash{'version'}=$version;
 5605:     my $scope;
 5606:     for ($scope=1;$scope<=$version;$scope++) {
 5607:       my $vkeys=$hash{"$scope:keys:$symb"};
 5608:       my @keys=split(/:/,$vkeys);
 5609:       my $key;
 5610:       $returnhash{"$scope:keys"}=$vkeys;
 5611:       foreach $key (@keys) {
 5612: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5613: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5614:       }
 5615:     }
 5616:     if (!(untie(%hash))) {
 5617:       return "error:$!";
 5618:     }
 5619:   } else {
 5620:     return "error:$!";
 5621:   }
 5622:   return %returnhash;
 5623: }
 5624: 
 5625: # ----------------------------------------------------------------------- Store
 5626: 
 5627: sub store {
 5628:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5629:     my $home='';
 5630: 
 5631:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5632: 
 5633:     $symb=&symbclean($symb);
 5634:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5635: 
 5636:     if (!$domain) { $domain=$env{'user.domain'}; }
 5637:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5638: 
 5639:     &devalidate($symb,$stuname,$domain);
 5640: 
 5641:     $symb=escape($symb);
 5642:     if (!$namespace) { 
 5643:        unless ($namespace=$env{'request.course.id'}) { 
 5644:           return ''; 
 5645:        } 
 5646:     }
 5647:     if (!$home) { $home=$env{'user.home'}; }
 5648: 
 5649:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5650:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5651: 
 5652:     my $namevalue='';
 5653:     foreach my $key (keys(%$storehash)) {
 5654:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5655:     }
 5656:     $namevalue=~s/\&$//;
 5657:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5658:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5659: }
 5660: 
 5661: # -------------------------------------------------------------- Critical Store
 5662: 
 5663: sub cstore {
 5664:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5665:     my $home='';
 5666: 
 5667:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5668: 
 5669:     $symb=&symbclean($symb);
 5670:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5671: 
 5672:     if (!$domain) { $domain=$env{'user.domain'}; }
 5673:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5674: 
 5675:     &devalidate($symb,$stuname,$domain);
 5676: 
 5677:     $symb=escape($symb);
 5678:     if (!$namespace) { 
 5679:        unless ($namespace=$env{'request.course.id'}) { 
 5680:           return ''; 
 5681:        } 
 5682:     }
 5683:     if (!$home) { $home=$env{'user.home'}; }
 5684: 
 5685:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5686:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5687: 
 5688:     my $namevalue='';
 5689:     foreach my $key (keys(%$storehash)) {
 5690:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5691:     }
 5692:     $namevalue=~s/\&$//;
 5693:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5694:     return critical
 5695:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5696: }
 5697: 
 5698: # --------------------------------------------------------------------- Restore
 5699: 
 5700: sub restore {
 5701:     my ($symb,$namespace,$domain,$stuname) = @_;
 5702:     my $home='';
 5703: 
 5704:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5705: 
 5706:     if (!$symb) {
 5707:         return if ($namespace eq 'courserequests');
 5708:         unless ($symb=escape(&symbread())) { return ''; }
 5709:     } else {
 5710:         unless ($namespace eq 'courserequests') {
 5711:             $symb=&escape(&symbclean($symb));
 5712:         }
 5713:     }
 5714:     if (!$namespace) { 
 5715:        unless ($namespace=$env{'request.course.id'}) { 
 5716:           return ''; 
 5717:        } 
 5718:     }
 5719:     if (!$domain) { $domain=$env{'user.domain'}; }
 5720:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5721:     if (!$home) { $home=$env{'user.home'}; }
 5722:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5723: 
 5724:     my %returnhash=();
 5725:     foreach my $line (split(/\&/,$answer)) {
 5726: 	my ($name,$value)=split(/\=/,$line);
 5727:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5728:     }
 5729:     my $version;
 5730:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5731:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5732:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5733:        }
 5734:     }
 5735:     return %returnhash;
 5736: }
 5737: 
 5738: # ---------------------------------------------------------- Course Description
 5739: #
 5740: #  
 5741: 
 5742: sub coursedescription {
 5743:     my ($courseid,$args)=@_;
 5744:     $courseid=~s/^\///;
 5745:     $courseid=~s/\_/\//g;
 5746:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5747:     my $chome=&homeserver($cnum,$cdomain);
 5748:     my $normalid=$cdomain.'_'.$cnum;
 5749:     # need to always cache even if we get errors otherwise we keep 
 5750:     # trying and trying and trying to get the course description.
 5751:     my %envhash=();
 5752:     my %returnhash=();
 5753:     
 5754:     my $expiretime=600;
 5755:     if ($env{'request.course.id'} eq $normalid) {
 5756: 	$expiretime=120;
 5757:     }
 5758: 
 5759:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5760:     if (!$args->{'freshen_cache'}
 5761: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5762: 	foreach my $key (keys(%env)) {
 5763: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5764: 	    my ($setting) = $1;
 5765: 	    $returnhash{$setting} = $env{$key};
 5766: 	}
 5767: 	return %returnhash;
 5768:     }
 5769: 
 5770:     # get the data again
 5771: 
 5772:     if (!$args->{'one_time'}) {
 5773: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5774:     }
 5775: 
 5776:     if ($chome ne 'no_host') {
 5777:        %returnhash=&dump('environment',$cdomain,$cnum);
 5778:        if (!exists($returnhash{'con_lost'})) {
 5779: 	   my $username = $env{'user.name'}; # Defult username
 5780: 	   if(defined $args->{'user'}) {
 5781: 	       $username = $args->{'user'};
 5782: 	   }
 5783:            $returnhash{'home'}= $chome;
 5784: 	   $returnhash{'domain'} = $cdomain;
 5785: 	   $returnhash{'num'} = $cnum;
 5786:            if (!defined($returnhash{'type'})) {
 5787:                $returnhash{'type'} = 'Course';
 5788:            }
 5789:            while (my ($name,$value) = each %returnhash) {
 5790:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5791:            }
 5792:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5793:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5794: 	       $username.'_'.$cdomain.'_'.$cnum;
 5795:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5796:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5797:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5798:        }
 5799:     }
 5800:     if (!$args->{'one_time'}) {
 5801: 	&appenv(\%envhash);
 5802:     }
 5803:     return %returnhash;
 5804: }
 5805: 
 5806: sub update_released_required {
 5807:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5808:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5809:         $cid = $env{'request.course.id'};
 5810:         $cdom = $env{'course.'.$cid.'.domain'};
 5811:         $cnum = $env{'course.'.$cid.'.num'};
 5812:         $chome = $env{'course.'.$cid.'.home'};
 5813:     }
 5814:     if ($needsrelease) {
 5815:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5816:         my $needsupdate;
 5817:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5818:             $needsupdate = 1;
 5819:         } else {
 5820:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5821:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5822:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5823:                 $needsupdate = 1;
 5824:             }
 5825:         }
 5826:         if ($needsupdate) {
 5827:             my %needshash = (
 5828:                              'internal.releaserequired' => $needsrelease,
 5829:                             );
 5830:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5831:             if ($putresult eq 'ok') {
 5832:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5833:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5834:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5835:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5836:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5837:                 }
 5838:             }
 5839:         }
 5840:     }
 5841:     return;
 5842: }
 5843: 
 5844: # -------------------------------------------------See if a user is privileged
 5845: 
 5846: sub privileged {
 5847:     my ($username,$domain,$possdomains,$possroles)=@_;
 5848:     my $now = time;
 5849:     my $roles;
 5850:     if (ref($possroles) eq 'ARRAY') {
 5851:         $roles = $possroles; 
 5852:     } else {
 5853:         $roles = ['dc','su'];
 5854:     }
 5855:     if (ref($possdomains) eq 'ARRAY') {
 5856:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5857:         foreach my $dom (@{$possdomains}) {
 5858:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5859:                 (ref($privileged{$dom}) eq 'HASH')) {
 5860:                 foreach my $role (@{$roles}) {
 5861:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5862:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5863:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5864:                             return 1 unless (($end && $end < $now) ||
 5865:                                              ($start && $start > $now));
 5866:                         }
 5867:                     }
 5868:                 }
 5869:             }
 5870:         }
 5871:     } else {
 5872:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5873:         my $now = time;
 5874: 
 5875:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5876:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5877:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5878:                 return 1 unless ($tend && $tend < $now) 
 5879:                         or ($tstart && $tstart > $now);
 5880:             }
 5881:         }
 5882:     }
 5883:     return 0;
 5884: }
 5885: 
 5886: sub privileged_by_domain {
 5887:     my ($domains,$roles) = @_;
 5888:     my %privileged = ();
 5889:     my $cachetime = 60*60*24;
 5890:     my $now = time;
 5891:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5892:         return %privileged;
 5893:     }
 5894:     foreach my $dom (@{$domains}) {
 5895:         next if (ref($privileged{$dom}) eq 'HASH');
 5896:         my $needroles;
 5897:         foreach my $role (@{$roles}) {
 5898:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5899:             if (defined($cached)) {
 5900:                 if (ref($result) eq 'HASH') {
 5901:                     $privileged{$dom}{$role} = $result;
 5902:                 }
 5903:             } else {
 5904:                 $needroles = 1;
 5905:             }
 5906:         }
 5907:         if ($needroles) {
 5908:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5909:             $privileged{$dom} = {};
 5910:             foreach my $server (keys(%dompersonnel)) {
 5911:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5912:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5913:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5914:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5915:                         next if ($end && $end < $now);
 5916:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5917:                             $dompersonnel{$server}{$item};
 5918:                     }
 5919:                 }
 5920:             }
 5921:             if (ref($privileged{$dom}) eq 'HASH') {
 5922:                 foreach my $role (@{$roles}) {
 5923:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5924:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5925:                     } else {
 5926:                         my %hash = ();
 5927:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5928:                     }
 5929:                 }
 5930:             }
 5931:         }
 5932:     }
 5933:     return %privileged;
 5934: }
 5935: 
 5936: # -------------------------------------------------------- Get user privileges
 5937: 
 5938: sub rolesinit {
 5939:     my ($domain, $username) = @_;
 5940:     my %userroles = ('user.login.time' => time);
 5941:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5942: 
 5943:     # firstaccess and timerinterval are related to timed maps/resources. 
 5944:     # also, blocking can be triggered by an activating timer
 5945:     # it's saved in the user's %env.
 5946:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5947:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5948:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5949:         %timerintchk, %timerintenv);
 5950: 
 5951:     foreach my $key (keys(%firstaccess)) {
 5952:         my ($cid, $rest) = split(/\0/, $key);
 5953:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5954:     }
 5955: 
 5956:     foreach my $key (keys(%timerinterval)) {
 5957:         my ($cid,$rest) = split(/\0/,$key);
 5958:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5959:     }
 5960: 
 5961:     my %allroles=();
 5962:     my %allgroups=();
 5963: 
 5964:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5965:         my $role = $rolesdump{$area};
 5966:         $area =~ s/\_\w\w$//;
 5967: 
 5968:         my ($trole, $tend, $tstart, $group_privs);
 5969: 
 5970:         if ($role =~ /^cr/) {
 5971:         # Custom role, defined by a user 
 5972:         # e.g., user.role.cr/msu/smith/mynewrole
 5973:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5974:                 $trole = $1;
 5975:                 ($tend, $tstart) = split('_', $2);
 5976:             } else {
 5977:                 $trole = $role;
 5978:             }
 5979:         } elsif ($role =~ m|^gr/|) {
 5980:         # Role of member in a group, defined within a course/community
 5981:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5982:             ($trole, $tend, $tstart) = split(/_/, $role);
 5983:             next if $tstart eq '-1';
 5984:             ($trole, $group_privs) = split(/\//, $trole);
 5985:             $group_privs = &unescape($group_privs);
 5986:         } else {
 5987:         # Just a normal role, defined in roles.tab
 5988:             ($trole, $tend, $tstart) = split(/_/,$role);
 5989:         }
 5990: 
 5991:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5992:                  $username);
 5993:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5994: 
 5995:         # role expired or not available yet?
 5996:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5997:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5998: 
 5999:         next if $area eq '' or $trole eq '';
 6000: 
 6001:         my $spec = "$trole.$area";
 6002:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6003: 
 6004:         if ($trole =~ /^cr\//) {
 6005:         # Custom role, defined by a user
 6006:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6007:         } elsif ($trole eq 'gr') {
 6008:         # Role of a member in a group, defined within a course/community
 6009:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6010:             next;
 6011:         } else {
 6012:         # Normal role, defined in roles.tab
 6013:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6014:         }
 6015: 
 6016:         my $cid = $tdomain.'_'.$trest;
 6017:         unless ($firstaccchk{$cid}) {
 6018:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6019:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6020:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6021:                         $coursetimerstarts{$cid}{$item}; 
 6022:                 }
 6023:             }
 6024:             $firstaccchk{$cid} = 1;
 6025:         }
 6026:         unless ($timerintchk{$cid}) {
 6027:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6028:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6029:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6030:                        $coursetimerintervals{$cid}{$item};
 6031:                 }
 6032:             }
 6033:             $timerintchk{$cid} = 1;
 6034:         }
 6035:     }
 6036: 
 6037:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6038:                                                           \%allroles, \%allgroups);
 6039:     $env{'user.adv'} = $userroles{'user.adv'};
 6040:     $env{'user.rar'} = $userroles{'user.rar'};
 6041: 
 6042:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6043: }
 6044: 
 6045: sub set_arearole {
 6046:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6047:     unless ($nolog) {
 6048: # log the associated role with the area
 6049:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6050:     }
 6051:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6052: }
 6053: 
 6054: sub custom_roleprivs {
 6055:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6056:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6057:     my $homsvr = &homeserver($rauthor,$rdomain);
 6058:     if (&hostname($homsvr) ne '') {
 6059:         my ($rdummy,$roledef)=
 6060:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6061:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6062:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6063:             if (defined($syspriv)) {
 6064:                 if ($trest =~ /^$match_community$/) {
 6065:                     $syspriv =~ s/bre\&S//; 
 6066:                 }
 6067:                 $$allroles{'cm./'}.=':'.$syspriv;
 6068:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6069:             }
 6070:             if ($tdomain ne '') {
 6071:                 if (defined($dompriv)) {
 6072:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6073:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6074:                 }
 6075:                 if (($trest ne '') && (defined($coursepriv))) {
 6076:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6077:                         my $rolename = $1;
 6078:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6079:                     }
 6080:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6081:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6082:                 }
 6083:             }
 6084:         }
 6085:     }
 6086: }
 6087: 
 6088: sub course_adhocrole_privs {
 6089:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6090:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6091:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6092:         my (%currprivs,%storeprivs);
 6093:         foreach my $item (split(/:/,$coursepriv)) {
 6094:             my ($priv,$restrict) = split(/\&/,$item);
 6095:             $currprivs{$priv} = $restrict;
 6096:         }
 6097:         my (%possadd,%possremove,%full);
 6098:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6099:             my ($priv,$restrict)=split(/\&/,$item);
 6100:             $full{$priv} = $restrict;
 6101:         }
 6102:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6103:              next if ($item eq '');
 6104:              my ($rule,$rest) = split(/=/,$item);
 6105:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6106:              foreach my $priv (split(/:/,$rest)) {
 6107:                  if ($priv ne '') {
 6108:                      if ($rule eq 'off') {
 6109:                          $possremove{$priv} = 1;
 6110:                      } else {
 6111:                          $possadd{$priv} = 1;
 6112:                      }
 6113:                  }
 6114:              }
 6115:          }
 6116:          foreach my $priv (sort(keys(%full))) {
 6117:              if (exists($currprivs{$priv})) {
 6118:                  unless (exists($possremove{$priv})) {
 6119:                      $storeprivs{$priv} = $currprivs{$priv};
 6120:                  }
 6121:              } elsif (exists($possadd{$priv})) {
 6122:                  $storeprivs{$priv} = $full{$priv};
 6123:              }
 6124:          }
 6125:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6126:      }
 6127:      return $coursepriv;
 6128: }
 6129: 
 6130: sub group_roleprivs {
 6131:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6132:     my $access = 1;
 6133:     my $now = time;
 6134:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6135:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6136:     if ($access) {
 6137:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6138:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6139:     }
 6140: }
 6141: 
 6142: sub standard_roleprivs {
 6143:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6144:     if (defined($pr{$trole.':s'})) {
 6145:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6146:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6147:     }
 6148:     if ($tdomain ne '') {
 6149:         if (defined($pr{$trole.':d'})) {
 6150:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6151:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6152:         }
 6153:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6154:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6155:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6156:         }
 6157:     }
 6158: }
 6159: 
 6160: sub set_userprivs {
 6161:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6162:     my $author=0;
 6163:     my $adv=0;
 6164:     my $rar=0;
 6165:     my %grouproles = ();
 6166:     if (keys(%{$allgroups}) > 0) {
 6167:         my @groupkeys; 
 6168:         foreach my $role (keys(%{$allroles})) {
 6169:             push(@groupkeys,$role);
 6170:         }
 6171:         if (ref($groups_roles) eq 'HASH') {
 6172:             foreach my $key (keys(%{$groups_roles})) {
 6173:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6174:                     push(@groupkeys,$key);
 6175:                 }
 6176:             }
 6177:         }
 6178:         if (@groupkeys > 0) {
 6179:             foreach my $role (@groupkeys) {
 6180:                 my ($trole,$area,$sec,$extendedarea);
 6181:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6182:                     $trole = $1;
 6183:                     $area = $2;
 6184:                     $sec = $3;
 6185:                     $extendedarea = $area.$sec;
 6186:                     if (exists($$allgroups{$area})) {
 6187:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6188:                             my $spec = $trole.'.'.$extendedarea;
 6189:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6190:                                                 $$allgroups{$area}{$group};
 6191:                         }
 6192:                     }
 6193:                 }
 6194:             }
 6195:         }
 6196:     }
 6197:     foreach my $group (keys(%grouproles)) {
 6198:         $$allroles{$group} = $grouproles{$group};
 6199:     }
 6200:     foreach my $role (keys(%{$allroles})) {
 6201:         my %thesepriv;
 6202:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6203:         foreach my $item (split(/:/,$$allroles{$role})) {
 6204:             if ($item ne '') {
 6205:                 my ($privilege,$restrictions)=split(/&/,$item);
 6206:                 if ($restrictions eq '') {
 6207:                     $thesepriv{$privilege}='F';
 6208:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6209:                     $thesepriv{$privilege}.=$restrictions;
 6210:                 }
 6211:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6212:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6213:             }
 6214:         }
 6215:         my $thesestr='';
 6216:         foreach my $priv (sort(keys(%thesepriv))) {
 6217: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6218: 	}
 6219:         $userroles->{'user.priv.'.$role} = $thesestr;
 6220:     }
 6221:     return ($author,$adv,$rar);
 6222: }
 6223: 
 6224: sub role_status {
 6225:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6226:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6227:         my ($one,$two) = split(m{\./},$rolekey,2);
 6228:         (undef,undef,$$role) = split(/\./,$one,3);
 6229:         unless (!defined($$role) || $$role eq '') {
 6230:             $$where = '/'.$two;
 6231:             $$trolecode=$$role.'.'.$$where;
 6232:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6233:             $$tstatus='is';
 6234:             if ($$tstart && $$tstart>$update) {
 6235:                 $$tstatus='future';
 6236:                 if ($$tstart<$now) {
 6237:                     if ($$tstart && $$tstart>$refresh) {
 6238:                         if (($$where ne '') && ($$role ne '')) {
 6239:                             my (%allroles,%allgroups,$group_privs,
 6240:                                 %groups_roles,@rolecodes);
 6241:                             my %userroles = (
 6242:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6243:                             );
 6244:                             @rolecodes = ('cm'); 
 6245:                             my $spec=$$role.'.'.$$where;
 6246:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6247:                             if ($$role =~ /^cr\//) {
 6248:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6249:                                 push(@rolecodes,'cr');
 6250:                             } elsif ($$role eq 'gr') {
 6251:                                 push(@rolecodes,$$role);
 6252:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6253:                                                     $env{'user.name'});
 6254:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6255:                                 (undef,my $group_privs) = split(/\//,$trole);
 6256:                                 $group_privs = &unescape($group_privs);
 6257:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6258:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6259:                                 &get_groups_roles($tdomain,$trest,
 6260:                                                   \%course_roles,\@rolecodes,
 6261:                                                   \%groups_roles);
 6262:                             } else {
 6263:                                 push(@rolecodes,$$role);
 6264:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6265:                             }
 6266:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6267:                                                                    \%groups_roles);
 6268:                             &appenv(\%userroles,\@rolecodes);
 6269:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6270:                         }
 6271:                     }
 6272:                     $$tstatus = 'is';
 6273:                 }
 6274:             }
 6275:             if ($$tend) {
 6276:                 if ($$tend<$update) {
 6277:                     $$tstatus='expired';
 6278:                 } elsif ($$tend<$now) {
 6279:                     $$tstatus='will_not';
 6280:                 }
 6281:             }
 6282:         }
 6283:     }
 6284: }
 6285: 
 6286: sub get_groups_roles {
 6287:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6288:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6289:                   (ref($rolecodes) eq 'ARRAY') && 
 6290:                   (ref($groups_roles) eq 'HASH')); 
 6291:     if (keys(%{$cdom_courseroles}) > 0) {
 6292:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6293:         if ($cdom ne '' && $cnum ne '') {
 6294:             foreach my $key (keys(%{$cdom_courseroles})) {
 6295:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6296:                     my $crsrole = $1;
 6297:                     my $crssec = $2;
 6298:                     if ($crsrole =~ /^cr/) {
 6299:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6300:                             push(@{$rolecodes},'cr');
 6301:                         }
 6302:                     } else {
 6303:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6304:                             push(@{$rolecodes},$crsrole);
 6305:                         }
 6306:                     }
 6307:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6308:                     if ($crssec ne '') {
 6309:                         $rolekey .= "/$crssec";
 6310:                     }
 6311:                     $rolekey .= './';
 6312:                     $groups_roles->{$rolekey} = $rolecodes;
 6313:                 }
 6314:             }
 6315:         }
 6316:     }
 6317:     return;
 6318: }
 6319: 
 6320: sub delete_env_groupprivs {
 6321:     my ($where,$courseroles,$possroles) = @_;
 6322:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6323:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6324:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6325:         %{$courseroles->{$udom}} =
 6326:             &get_my_roles('','','userroles',['active'],
 6327:                           $possroles,[$udom],1);
 6328:     }
 6329:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6330:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6331:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6332:             my $area = '/'.$cdom.'/'.$cnum;
 6333:             my $privkey = "user.priv.$crsrole.$area";
 6334:             if ($crssec ne '') {
 6335:                 $privkey .= '/'.$crssec;
 6336:             }
 6337:             $privkey .= ".$area/$group";
 6338:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6339:         }
 6340:     }
 6341:     return;
 6342: }
 6343: 
 6344: sub check_adhoc_privs {
 6345:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6346:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6347:     if ($sec) {
 6348:         $cckey .= '/'.$sec;
 6349:     } 
 6350:     my $setprivs;
 6351:     if ($env{$cckey}) {
 6352:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6353:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6354:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6355:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6356:             $setprivs = 1;
 6357:         }
 6358:     } else {
 6359:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6360:         $setprivs = 1;
 6361:     }
 6362:     return $setprivs;
 6363: }
 6364: 
 6365: sub set_adhoc_privileges {
 6366: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6367:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6368:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6369:     if ($sec ne '') {
 6370:         $area .= '/'.$sec;
 6371:     }
 6372:     my $spec = $role.'.'.$area;
 6373:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6374:                                   $env{'user.name'},1);
 6375:     my %rolehash = ();
 6376:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6377:         my $rolename = $1;
 6378:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6379:         my %domdef = &get_domain_defaults($dcdom);
 6380:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6381:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6382:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6383:             }
 6384:         }
 6385:     } else {
 6386:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6387:     }
 6388:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6389:     &appenv(\%userroles,[$role,'cm']);
 6390:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6391:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6392:         &appenv( {'request.role'        => $spec,
 6393:                   'request.role.domain' => $dcdom,
 6394:                   'request.course.sec'  => $sec,
 6395:                  }
 6396:                );
 6397:         my $tadv=0;
 6398:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6399:         &appenv({'request.role.adv'    => $tadv});
 6400:     }
 6401: }
 6402: 
 6403: # --------------------------------------------------------------- get interface
 6404: 
 6405: sub get {
 6406:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6407:    my $items='';
 6408:    foreach my $item (@$storearr) {
 6409:        $items.=&escape($item).'&';
 6410:    }
 6411:    $items=~s/\&$//;
 6412:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6413:    if (!$uname) { $uname=$env{'user.name'}; }
 6414:    my $uhome=&homeserver($uname,$udomain);
 6415: 
 6416:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6417:    my @pairs=split(/\&/,$rep);
 6418:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6419:      return @pairs;
 6420:    }
 6421:    my %returnhash=();
 6422:    my $i=0;
 6423:    foreach my $item (@$storearr) {
 6424:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6425:       $i++;
 6426:    }
 6427:    return %returnhash;
 6428: }
 6429: 
 6430: # --------------------------------------------------------------- del interface
 6431: 
 6432: sub del {
 6433:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6434:    my $items='';
 6435:    foreach my $item (@$storearr) {
 6436:        $items.=&escape($item).'&';
 6437:    }
 6438: 
 6439:    $items=~s/\&$//;
 6440:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6441:    if (!$uname) { $uname=$env{'user.name'}; }
 6442:    my $uhome=&homeserver($uname,$udomain);
 6443:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6444: }
 6445: 
 6446: # -------------------------------------------------------------- dump interface
 6447: 
 6448: sub unserialize {
 6449:     my ($rep, $escapedkeys) = @_;
 6450: 
 6451:     return {} if $rep =~ /^error/;
 6452: 
 6453:     my %returnhash=();
 6454: 	foreach my $item (split(/\&/,$rep)) {
 6455: 	    my ($key, $value) = split(/=/, $item, 2);
 6456: 	    $key = unescape($key) unless $escapedkeys;
 6457: 	    next if $key =~ /^error: 2 /;
 6458: 	    $returnhash{$key} = &thaw_unescape($value);
 6459: 	}
 6460:     #return %returnhash;
 6461:     return \%returnhash;
 6462: }        
 6463: 
 6464: # see Lond::dump_with_regexp
 6465: # if $escapedkeys hash keys won't get unescaped.
 6466: sub dump {
 6467:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6468:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6469:     if (!$uname) { $uname=$env{'user.name'}; }
 6470:     my $uhome=&homeserver($uname,$udomain);
 6471: 
 6472:     if ($regexp) {
 6473:         $regexp=&escape($regexp);
 6474:     } else {
 6475:         $regexp='.';
 6476:     }
 6477:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6478:         # user is hosted on this machine
 6479:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6480:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6481:         return %{unserialize($reply, $escapedkeys)};
 6482:     }
 6483:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6484:     my @pairs=split(/\&/,$rep);
 6485:     my %returnhash=();
 6486:     if (!($rep =~ /^error/ )) {
 6487: 	foreach my $item (@pairs) {
 6488: 	    my ($key,$value)=split(/=/,$item,2);
 6489:         $key = unescape($key) unless $escapedkeys;
 6490:         #$key = &unescape($key);
 6491: 	    next if ($key =~ /^error: 2 /);
 6492: 	    $returnhash{$key}=&thaw_unescape($value);
 6493: 	}
 6494:     }
 6495:     return %returnhash;
 6496: }
 6497: 
 6498: 
 6499: # --------------------------------------------------------- dumpstore interface
 6500: 
 6501: sub dumpstore {
 6502:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6503:    # same as dump but keys must be escaped. They may contain colon separated
 6504:    # lists of values that may themself contain colons (e.g. symbs).
 6505:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6506: }
 6507: 
 6508: # -------------------------------------------------------------- keys interface
 6509: 
 6510: sub getkeys {
 6511:    my ($namespace,$udomain,$uname)=@_;
 6512:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6513:    if (!$uname) { $uname=$env{'user.name'}; }
 6514:    my $uhome=&homeserver($uname,$udomain);
 6515:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6516:    my @keyarray=();
 6517:    foreach my $key (split(/\&/,$rep)) {
 6518:       next if ($key =~ /^error: 2 /);
 6519:       push(@keyarray,&unescape($key));
 6520:    }
 6521:    return @keyarray;
 6522: }
 6523: 
 6524: # --------------------------------------------------------------- currentdump
 6525: sub currentdump {
 6526:    my ($courseid,$sdom,$sname)=@_;
 6527:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6528:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6529:    $sname    = $env{'user.name'}         if (! defined($sname));
 6530:    my $uhome = &homeserver($sname,$sdom);
 6531:    my $rep;
 6532: 
 6533:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6534:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6535:                    $courseid)));
 6536:    } else {
 6537:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6538:    }
 6539: 
 6540:    return if ($rep =~ /^(error:|no_such_host)/);
 6541:    #
 6542:    my %returnhash=();
 6543:    #
 6544:    if ($rep eq 'unknown_cmd') {
 6545:        # an old lond will not know currentdump
 6546:        # Do a dump and make it look like a currentdump
 6547:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6548:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6549:        my %hash = @tmp;
 6550:        @tmp=();
 6551:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6552:    } else {
 6553:        my @pairs=split(/\&/,$rep);
 6554:        foreach my $pair (@pairs) {
 6555:            my ($key,$value)=split(/=/,$pair,2);
 6556:            my ($symb,$param) = split(/:/,$key);
 6557:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6558:                                                         &thaw_unescape($value);
 6559:        }
 6560:    }
 6561:    return %returnhash;
 6562: }
 6563: 
 6564: sub convert_dump_to_currentdump{
 6565:     my %hash = %{shift()};
 6566:     my %returnhash;
 6567:     # Code ripped from lond, essentially.  The only difference
 6568:     # here is the unescaping done by lonnet::dump().  Conceivably
 6569:     # we might run in to problems with parameter names =~ /^v\./
 6570:     while (my ($key,$value) = each(%hash)) {
 6571:         my ($v,$symb,$param) = split(/:/,$key);
 6572: 	$symb  = &unescape($symb);
 6573: 	$param = &unescape($param);
 6574:         next if ($v eq 'version' || $symb eq 'keys');
 6575:         next if (exists($returnhash{$symb}) &&
 6576:                  exists($returnhash{$symb}->{$param}) &&
 6577:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6578:         $returnhash{$symb}->{$param}=$value;
 6579:         $returnhash{$symb}->{'v.'.$param}=$v;
 6580:     }
 6581:     #
 6582:     # Remove all of the keys in the hashes which keep track of
 6583:     # the version of the parameter.
 6584:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6585:         # use a foreach because we are going to delete from the hash.
 6586:         foreach my $key (keys(%$param_hash)) {
 6587:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6588:         }
 6589:     }
 6590:     return \%returnhash;
 6591: }
 6592: 
 6593: # ------------------------------------------------------ critical inc interface
 6594: 
 6595: sub cinc {
 6596:     return &inc(@_,'critical');
 6597: }
 6598: 
 6599: # --------------------------------------------------------------- inc interface
 6600: 
 6601: sub inc {
 6602:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6603:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6604:     if (!$uname) { $uname=$env{'user.name'}; }
 6605:     my $uhome=&homeserver($uname,$udomain);
 6606:     my $items='';
 6607:     if (! ref($store)) {
 6608:         # got a single value, so use that instead
 6609:         $items = &escape($store).'=&';
 6610:     } elsif (ref($store) eq 'SCALAR') {
 6611:         $items = &escape($$store).'=&';        
 6612:     } elsif (ref($store) eq 'ARRAY') {
 6613:         $items = join('=&',map {&escape($_);} @{$store});
 6614:     } elsif (ref($store) eq 'HASH') {
 6615:         while (my($key,$value) = each(%{$store})) {
 6616:             $items.= &escape($key).'='.&escape($value).'&';
 6617:         }
 6618:     }
 6619:     $items=~s/\&$//;
 6620:     if ($critical) {
 6621: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6622:     } else {
 6623: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6624:     }
 6625: }
 6626: 
 6627: # --------------------------------------------------------------- put interface
 6628: 
 6629: sub put {
 6630:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6631:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6632:    if (!$uname) { $uname=$env{'user.name'}; }
 6633:    my $uhome=&homeserver($uname,$udomain);
 6634:    my $items='';
 6635:    foreach my $item (keys(%$storehash)) {
 6636:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6637:    }
 6638:    $items=~s/\&$//;
 6639:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6640: }
 6641: 
 6642: # ------------------------------------------------------------ newput interface
 6643: 
 6644: sub newput {
 6645:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6646:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6647:    if (!$uname) { $uname=$env{'user.name'}; }
 6648:    my $uhome=&homeserver($uname,$udomain);
 6649:    my $items='';
 6650:    foreach my $key (keys(%$storehash)) {
 6651:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6652:    }
 6653:    $items=~s/\&$//;
 6654:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6655: }
 6656: 
 6657: # ---------------------------------------------------------  putstore interface
 6658: 
 6659: sub putstore {
 6660:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6661:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6662:    if (!$uname) { $uname=$env{'user.name'}; }
 6663:    my $uhome=&homeserver($uname,$udomain);
 6664:    my $items='';
 6665:    foreach my $key (keys(%$storehash)) {
 6666:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6667:    }
 6668:    $items=~s/\&$//;
 6669:    my $esc_symb=&escape($symb);
 6670:    my $esc_v=&escape($version);
 6671:    my $reply =
 6672:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6673: 	      $uhome);
 6674:    if (($tolog) && ($reply eq 'ok')) {
 6675:        my $namevalue='';
 6676:        foreach my $key (keys(%{$storehash})) {
 6677:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6678:        }
 6679:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6680:                      '&host='.&escape($perlvar{'lonHostID'}).
 6681:                      '&version='.$esc_v.
 6682:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6683:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6684:    }
 6685:    if ($reply eq 'unknown_cmd') {
 6686:        # gfall back to way things use to be done
 6687:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6688: 			    $uname);
 6689:    }
 6690:    return $reply;
 6691: }
 6692: 
 6693: sub old_putstore {
 6694:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6695:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6696:     if (!$uname) { $uname=$env{'user.name'}; }
 6697:     my $uhome=&homeserver($uname,$udomain);
 6698:     my %newstorehash;
 6699:     foreach my $item (keys(%$storehash)) {
 6700: 	my $key = $version.':'.&escape($symb).':'.$item;
 6701: 	$newstorehash{$key} = $storehash->{$item};
 6702:     }
 6703:     my $items='';
 6704:     my %allitems = ();
 6705:     foreach my $item (keys(%newstorehash)) {
 6706: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6707: 	    my $key = $1.':keys:'.$2;
 6708: 	    $allitems{$key} .= $3.':';
 6709: 	}
 6710: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6711:     }
 6712:     foreach my $item (keys(%allitems)) {
 6713: 	$allitems{$item} =~ s/\:$//;
 6714: 	$items.= $item.'='.$allitems{$item}.'&';
 6715:     }
 6716:     $items=~s/\&$//;
 6717:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6718: }
 6719: 
 6720: # ------------------------------------------------------ critical put interface
 6721: 
 6722: sub cput {
 6723:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6724:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6725:    if (!$uname) { $uname=$env{'user.name'}; }
 6726:    my $uhome=&homeserver($uname,$udomain);
 6727:    my $items='';
 6728:    foreach my $item (keys(%$storehash)) {
 6729:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6730:    }
 6731:    $items=~s/\&$//;
 6732:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6733: }
 6734: 
 6735: # -------------------------------------------------------------- eget interface
 6736: 
 6737: sub eget {
 6738:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6739:    my $items='';
 6740:    foreach my $item (@$storearr) {
 6741:        $items.=&escape($item).'&';
 6742:    }
 6743:    $items=~s/\&$//;
 6744:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6745:    if (!$uname) { $uname=$env{'user.name'}; }
 6746:    my $uhome=&homeserver($uname,$udomain);
 6747:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6748:    my @pairs=split(/\&/,$rep);
 6749:    my %returnhash=();
 6750:    my $i=0;
 6751:    foreach my $item (@$storearr) {
 6752:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6753:       $i++;
 6754:    }
 6755:    return %returnhash;
 6756: }
 6757: 
 6758: # ------------------------------------------------------------ tmpput interface
 6759: sub tmpput {
 6760:     my ($storehash,$server,$context)=@_;
 6761:     my $items='';
 6762:     foreach my $item (keys(%$storehash)) {
 6763: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6764:     }
 6765:     $items=~s/\&$//;
 6766:     if (defined($context)) {
 6767:         $items .= ':'.&escape($context);
 6768:     }
 6769:     return &reply("tmpput:$items",$server);
 6770: }
 6771: 
 6772: # ------------------------------------------------------------ tmpget interface
 6773: sub tmpget {
 6774:     my ($token,$server)=@_;
 6775:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6776:     my $rep=&reply("tmpget:$token",$server);
 6777:     my %returnhash;
 6778:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6779:         return %returnhash;
 6780:     }
 6781:     foreach my $item (split(/\&/,$rep)) {
 6782: 	my ($key,$value)=split(/=/,$item);
 6783: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6784:     }
 6785:     return %returnhash;
 6786: }
 6787: 
 6788: # ------------------------------------------------------------ tmpdel interface
 6789: sub tmpdel {
 6790:     my ($token,$server)=@_;
 6791:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6792:     return &reply("tmpdel:$token",$server);
 6793: }
 6794: 
 6795: # ------------------------------------------------------------ get_timebased_id 
 6796: 
 6797: sub get_timebased_id {
 6798:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6799:         $maxtries) = @_;
 6800:     my ($newid,$error,$dellock);
 6801:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6802:         return ('','ok','invalid call to get suffix');
 6803:     }
 6804: 
 6805: # set defaults for any optional args for which values were not supplied
 6806:     if ($who eq '') {
 6807:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6808:     }
 6809:     if (!$locktries) {
 6810:         $locktries = 3;
 6811:     }
 6812:     if (!$maxtries) {
 6813:         $maxtries = 10;
 6814:     }
 6815:     
 6816:     if (($cdom eq '') || ($cnum eq '')) {
 6817:         if ($env{'request.course.id'}) {
 6818:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6819:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6820:         }
 6821:         if (($cdom eq '') || ($cnum eq '')) {
 6822:             return ('','ok','call to get suffix not in course context');
 6823:         }
 6824:     }
 6825: 
 6826: # construct locking item
 6827:     my $lockhash = {
 6828:                       $prefix."\0".'locked_'.$keyid => $who,
 6829:                    };
 6830:     my $tries = 0;
 6831: 
 6832: # attempt to get lock on nohist_$namespace file
 6833:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6834:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6835:         $tries ++;
 6836:         sleep 1;
 6837:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6838:     }
 6839: 
 6840: # attempt to get unique identifier, based on current timestamp
 6841:     if ($gotlock eq 'ok') {
 6842:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6843:         my $id = time;
 6844:         $newid = $id;
 6845:         if ($idtype eq 'addcode') {
 6846:             $newid .= &sixnum_code();
 6847:         }
 6848:         my $idtries = 0;
 6849:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6850:             if ($idtype eq 'concat') {
 6851:                 $newid = $id.$idtries;
 6852:             } elsif ($idtype eq 'addcode') {
 6853:                 $newid = $newid.&sixnum_code();
 6854:             } else {
 6855:                 $newid ++;
 6856:             }
 6857:             $idtries ++;
 6858:         }
 6859:         if (!exists($inuse{$prefix."\0".$newid})) {
 6860:             my %new_item =  (
 6861:                               $prefix."\0".$newid => $who,
 6862:                             );
 6863:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6864:                                                  $cdom,$cnum);
 6865:             if ($putresult ne 'ok') {
 6866:                 undef($newid);
 6867:                 $error = 'error saving new item: '.$putresult;
 6868:             }
 6869:         } else {
 6870:              undef($newid);
 6871:              $error = ('error: no unique suffix available for the new item ');
 6872:         }
 6873: #  remove lock
 6874:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6875:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6876:     } else {
 6877:         $error = "error: could not obtain lockfile\n";
 6878:         $dellock = 'ok';
 6879:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6880:             $dellock = 'nolock';
 6881:         }
 6882:     }
 6883:     return ($newid,$dellock,$error);
 6884: }
 6885: 
 6886: sub sixnum_code {
 6887:     my $code;
 6888:     for (0..6) {
 6889:         $code .= int( rand(9) );
 6890:     }
 6891:     return $code;
 6892: }
 6893: 
 6894: # -------------------------------------------------- portfolio access checking
 6895: 
 6896: sub portfolio_access {
 6897:     my ($requrl,$clientip) = @_;
 6898:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6899:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6900:     if ($result) {
 6901:         my %setters;
 6902:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6903:             my ($startblock,$endblock) =
 6904:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6905:             if ($startblock && $endblock) {
 6906:                 return 'B';
 6907:             }
 6908:         } else {
 6909:             my ($startblock,$endblock) =
 6910:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6911:             if ($startblock && $endblock) {
 6912:                 return 'B';
 6913:             }
 6914:         }
 6915:     }
 6916:     if ($result eq 'ok') {
 6917:        return 'F';
 6918:     } elsif ($result =~ /^[^:]+:guest_/) {
 6919:        return 'A';
 6920:     }
 6921:     return '';
 6922: }
 6923: 
 6924: sub get_portfolio_access {
 6925:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6926: 
 6927:     if (!ref($access_hash)) {
 6928: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6929: 	my %access_controls = &get_access_controls($current_perms,$group,
 6930: 						   $file_name);
 6931: 	$access_hash = $access_controls{$file_name};
 6932:     }
 6933: 
 6934:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6935:     my $now = time;
 6936:     if (ref($access_hash) eq 'HASH') {
 6937:         foreach my $key (keys(%{$access_hash})) {
 6938:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6939:             if ($start > $now) {
 6940:                 next;
 6941:             }
 6942:             if ($end && $end<$now) {
 6943:                 next;
 6944:             }
 6945:             if ($scope eq 'public') {
 6946:                 $public = $key;
 6947:                 last;
 6948:             } elsif ($scope eq 'guest') {
 6949:                 $guest = $key;
 6950:             } elsif ($scope eq 'domains') {
 6951:                 push(@domains,$key);
 6952:             } elsif ($scope eq 'users') {
 6953:                 push(@users,$key);
 6954:             } elsif ($scope eq 'course') {
 6955:                 push(@courses,$key);
 6956:             } elsif ($scope eq 'group') {
 6957:                 push(@groups,$key);
 6958:             } elsif ($scope eq 'ip') {
 6959:                 push(@ips,$key);
 6960:             }
 6961:         }
 6962:         if ($public) {
 6963:             return 'ok';
 6964:         } elsif (@ips > 0) {
 6965:             my $allowed;
 6966:             foreach my $ipkey (@ips) {
 6967:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6968:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6969:                         $allowed = 1;
 6970:                         last; 
 6971:                     }
 6972:                 }
 6973:             }
 6974:             if ($allowed) {
 6975:                 return 'ok';
 6976:             }
 6977:         }
 6978:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6979:             if ($guest) {
 6980:                 return $guest;
 6981:             }
 6982:         } else {
 6983:             if (@domains > 0) {
 6984:                 foreach my $domkey (@domains) {
 6985:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6986:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6987:                             return 'ok';
 6988:                         }
 6989:                     }
 6990:                 }
 6991:             }
 6992:             if (@users > 0) {
 6993:                 foreach my $userkey (@users) {
 6994:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6995:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6996:                             if (ref($item) eq 'HASH') {
 6997:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6998:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6999:                                     return 'ok';
 7000:                                 }
 7001:                             }
 7002:                         }
 7003:                     } 
 7004:                 }
 7005:             }
 7006:             my %roleshash;
 7007:             my @courses_and_groups = @courses;
 7008:             push(@courses_and_groups,@groups); 
 7009:             if (@courses_and_groups > 0) {
 7010:                 my (%allgroups,%allroles); 
 7011:                 my ($start,$end,$role,$sec,$group);
 7012:                 foreach my $envkey (%env) {
 7013:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7014:                         my $cid = $2.'_'.$3; 
 7015:                         if ($1 eq 'gr') {
 7016:                             $group = $4;
 7017:                             $allgroups{$cid}{$group} = $env{$envkey};
 7018:                         } else {
 7019:                             if ($4 eq '') {
 7020:                                 $sec = 'none';
 7021:                             } else {
 7022:                                 $sec = $4;
 7023:                             }
 7024:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7025:                         }
 7026:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7027:                         my $cid = $2.'_'.$3;
 7028:                         if ($4 eq '') {
 7029:                             $sec = 'none';
 7030:                         } else {
 7031:                             $sec = $4;
 7032:                         }
 7033:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7034:                     }
 7035:                 }
 7036:                 if (keys(%allroles) == 0) {
 7037:                     return;
 7038:                 }
 7039:                 foreach my $key (@courses_and_groups) {
 7040:                     my %content = %{$$access_hash{$key}};
 7041:                     my $cnum = $content{'number'};
 7042:                     my $cdom = $content{'domain'};
 7043:                     my $cid = $cdom.'_'.$cnum;
 7044:                     if (!exists($allroles{$cid})) {
 7045:                         next;
 7046:                     }    
 7047:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7048:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7049:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7050:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7051:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7052:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7053:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7054:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7055:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7056:                                         if (grep/^all$/,@sections) {
 7057:                                             return 'ok';
 7058:                                         } else {
 7059:                                             if (grep/^$sec$/,@sections) {
 7060:                                                 return 'ok';
 7061:                                             }
 7062:                                         }
 7063:                                     }
 7064:                                 }
 7065:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7066:                                     if (grep/^none$/,@groups) {
 7067:                                         return 'ok';
 7068:                                     }
 7069:                                 } else {
 7070:                                     if (grep/^all$/,@groups) {
 7071:                                         return 'ok';
 7072:                                     } 
 7073:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7074:                                         if (grep/^$group$/,@groups) {
 7075:                                             return 'ok';
 7076:                                         }
 7077:                                     }
 7078:                                 } 
 7079:                             }
 7080:                         }
 7081:                     }
 7082:                 }
 7083:             }
 7084:             if ($guest) {
 7085:                 return $guest;
 7086:             }
 7087:         }
 7088:     }
 7089:     return;
 7090: }
 7091: 
 7092: sub course_group_datechecker {
 7093:     my ($dates,$now,$status) = @_;
 7094:     my ($start,$end) = split(/\./,$dates);
 7095:     if (!$start && !$end) {
 7096:         return 'ok';
 7097:     }
 7098:     if (grep/^active$/,@{$status}) {
 7099:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7100:             return 'ok';
 7101:         }
 7102:     }
 7103:     if (grep/^previous$/,@{$status}) {
 7104:         if ($end > $now ) {
 7105:             return 'ok';
 7106:         }
 7107:     }
 7108:     if (grep/^future$/,@{$status}) {
 7109:         if ($start > $now) {
 7110:             return 'ok';
 7111:         }
 7112:     }
 7113:     return; 
 7114: }
 7115: 
 7116: sub parse_portfolio_url {
 7117:     my ($url) = @_;
 7118: 
 7119:     my ($type,$udom,$unum,$group,$file_name);
 7120:     
 7121:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7122: 	$type = 1;
 7123:         $udom = $1;
 7124:         $unum = $2;
 7125:         $file_name = $3;
 7126:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7127: 	$type = 2;
 7128:         $udom = $1;
 7129:         $unum = $2;
 7130:         $group = $3;
 7131:         $file_name = $3.'/'.$4;
 7132:     }
 7133:     if (wantarray) {
 7134: 	return ($type,$udom,$unum,$file_name,$group);
 7135:     }
 7136:     return $type;
 7137: }
 7138: 
 7139: sub is_portfolio_url {
 7140:     my ($url) = @_;
 7141:     return scalar(&parse_portfolio_url($url));
 7142: }
 7143: 
 7144: sub is_portfolio_file {
 7145:     my ($file) = @_;
 7146:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7147:         return 1;
 7148:     }
 7149:     return;
 7150: }
 7151: 
 7152: sub usertools_access {
 7153:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7154:     my ($access,%tools);
 7155:     if ($context eq '') {
 7156:         $context = 'tools';
 7157:     }
 7158:     if ($context eq 'requestcourses') {
 7159:         %tools = (
 7160:                       official   => 1,
 7161:                       unofficial => 1,
 7162:                       community  => 1,
 7163:                       textbook   => 1,
 7164:                       placement  => 1,
 7165:                       lti        => 1,
 7166:                  );
 7167:     } elsif ($context eq 'requestauthor') {
 7168:         %tools = (
 7169:                       requestauthor => 1,
 7170:                  );
 7171:     } else {
 7172:         %tools = (
 7173:                       aboutme   => 1,
 7174:                       blog      => 1,
 7175:                       webdav    => 1,
 7176:                       portfolio => 1,
 7177:                  );
 7178:     }
 7179:     return if (!defined($tools{$tool}));
 7180: 
 7181:     if (($udom eq '') || ($uname eq '')) {
 7182:         $udom = $env{'user.domain'};
 7183:         $uname = $env{'user.name'};
 7184:     }
 7185: 
 7186:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7187:         if ($action ne 'reload') {
 7188:             if ($context eq 'requestcourses') {
 7189:                 return $env{'environment.canrequest.'.$tool};
 7190:             } elsif ($context eq 'requestauthor') {
 7191:                 return $env{'environment.canrequest.author'};
 7192:             } else {
 7193:                 return $env{'environment.availabletools.'.$tool};
 7194:             }
 7195:         }
 7196:     }
 7197: 
 7198:     my ($toolstatus,$inststatus,$envkey);
 7199:     if ($context eq 'requestauthor') {
 7200:         $envkey = $context; 
 7201:     } else {
 7202:         $envkey = $context.'.'.$tool;
 7203:     }
 7204: 
 7205:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7206:          ($action ne 'reload')) {
 7207:         $toolstatus = $env{'environment.'.$envkey};
 7208:         $inststatus = $env{'environment.inststatus'};
 7209:     } else {
 7210:         if (ref($userenvref) eq 'HASH') {
 7211:             $toolstatus = $userenvref->{$envkey};
 7212:             $inststatus = $userenvref->{'inststatus'};
 7213:         } else {
 7214:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7215:             $toolstatus = $userenv{$envkey};
 7216:             $inststatus = $userenv{'inststatus'};
 7217:         }
 7218:     }
 7219: 
 7220:     if ($toolstatus ne '') {
 7221:         if ($toolstatus) {
 7222:             $access = 1;
 7223:         } else {
 7224:             $access = 0;
 7225:         }
 7226:         return $access;
 7227:     }
 7228: 
 7229:     my ($is_adv,%domdef);
 7230:     if (ref($is_advref) eq 'HASH') {
 7231:         $is_adv = $is_advref->{'is_adv'};
 7232:     } else {
 7233:         $is_adv = &is_advanced_user($udom,$uname);
 7234:     }
 7235:     if (ref($domdefref) eq 'HASH') {
 7236:         %domdef = %{$domdefref};
 7237:     } else {
 7238:         %domdef = &get_domain_defaults($udom);
 7239:     }
 7240:     if (ref($domdef{$tool}) eq 'HASH') {
 7241:         if ($is_adv) {
 7242:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7243:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7244:                     $access = 1;
 7245:                 } else {
 7246:                     $access = 0;
 7247:                 }
 7248:                 return $access;
 7249:             }
 7250:         }
 7251:         if ($inststatus ne '') {
 7252:             my ($hasaccess,$hasnoaccess);
 7253:             foreach my $affiliation (split(/:/,$inststatus)) {
 7254:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7255:                     if ($domdef{$tool}{$affiliation}) {
 7256:                         $hasaccess = 1;
 7257:                     } else {
 7258:                         $hasnoaccess = 1;
 7259:                     }
 7260:                 }
 7261:             }
 7262:             if ($hasaccess || $hasnoaccess) {
 7263:                 if ($hasaccess) {
 7264:                     $access = 1;
 7265:                 } elsif ($hasnoaccess) {
 7266:                     $access = 0; 
 7267:                 }
 7268:                 return $access;
 7269:             }
 7270:         } else {
 7271:             if ($domdef{$tool}{'default'} ne '') {
 7272:                 if ($domdef{$tool}{'default'}) {
 7273:                     $access = 1;
 7274:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7275:                     $access = 0;
 7276:                 }
 7277:                 return $access;
 7278:             }
 7279:         }
 7280:     } else {
 7281:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7282:             $access = 1;
 7283:         } else {
 7284:             $access = 0;
 7285:         }
 7286:         return $access;
 7287:     }
 7288: }
 7289: 
 7290: sub is_course_owner {
 7291:     my ($cdom,$cnum,$udom,$uname) = @_;
 7292:     if (($udom eq '') || ($uname eq '')) {
 7293:         $udom = $env{'user.domain'};
 7294:         $uname = $env{'user.name'};
 7295:     }
 7296:     unless (($udom eq '') || ($uname eq '')) {
 7297:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7298:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7299:                 return 1;
 7300:             } else {
 7301:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7302:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7303:                     return 1;
 7304:                 }
 7305:             }
 7306:         }
 7307:     }
 7308:     return;
 7309: }
 7310: 
 7311: sub is_advanced_user {
 7312:     my ($udom,$uname) = @_;
 7313:     if ($udom ne '' && $uname ne '') {
 7314:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7315:             if (wantarray) {
 7316:                 return ($env{'user.adv'},$env{'user.author'});
 7317:             } else {
 7318:                 return $env{'user.adv'};
 7319:             }
 7320:         }
 7321:     }
 7322:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7323:     my %allroles;
 7324:     my ($is_adv,$is_author);
 7325:     foreach my $role (keys(%roleshash)) {
 7326:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7327:         my $area = '/'.$tdomain.'/'.$trest;
 7328:         if ($sec ne '') {
 7329:             $area .= '/'.$sec;
 7330:         }
 7331:         if (($area ne '') && ($trole ne '')) {
 7332:             my $spec=$trole.'.'.$area;
 7333:             if ($trole =~ /^cr\//) {
 7334:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7335:             } elsif ($trole ne 'gr') {
 7336:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7337:             }
 7338:             if ($trole eq 'au') {
 7339:                 $is_author = 1;
 7340:             }
 7341:         }
 7342:     }
 7343:     foreach my $role (keys(%allroles)) {
 7344:         last if ($is_adv);
 7345:         foreach my $item (split(/:/,$allroles{$role})) {
 7346:             if ($item ne '') {
 7347:                 my ($privilege,$restrictions)=split(/&/,$item);
 7348:                 if ($privilege eq 'adv') {
 7349:                     $is_adv = 1;
 7350:                     last;
 7351:                 }
 7352:             }
 7353:         }
 7354:     }
 7355:     if (wantarray) {
 7356:         return ($is_adv,$is_author);
 7357:     }
 7358:     return $is_adv;
 7359: }
 7360: 
 7361: sub check_can_request {
 7362:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7363:     my $canreq = 0;
 7364:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7365:         $uname = $env{'user.name'};
 7366:         $udom = $env{'user.domain'};
 7367:     }
 7368:     my ($types,$typename) = &Apache::loncommon::course_types();
 7369:     my @options = ('approval','validate','autolimit');
 7370:     my $optregex = join('|',@options);
 7371:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7372:         foreach my $type (@{$types}) {
 7373:             if (&usertools_access($uname,$udom,$type,undef,
 7374:                                   'requestcourses')) {
 7375:                 $canreq ++;
 7376:                 if (ref($request_domains) eq 'HASH') {
 7377:                     push(@{$request_domains->{$type}},$udom);
 7378:                 }
 7379:                 if ($dom eq $udom) {
 7380:                     $can_request->{$type} = 1;
 7381:                 }
 7382:             }
 7383:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7384:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7385:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7386:                 if (@curr > 0) {
 7387:                     foreach my $item (@curr) {
 7388:                         if (ref($request_domains) eq 'HASH') {
 7389:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7390:                             if ($otherdom ne '') {
 7391:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7392:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7393:                                         push(@{$request_domains->{$type}},$otherdom);
 7394:                                     }
 7395:                                 } else {
 7396:                                     push(@{$request_domains->{$type}},$otherdom);
 7397:                                 }
 7398:                             }
 7399:                         }
 7400:                     }
 7401:                     unless ($dom eq $env{'user.domain'}) {
 7402:                         $canreq ++;
 7403:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7404:                             $can_request->{$type} = 1;
 7405:                         }
 7406:                     }
 7407:                 }
 7408:             }
 7409:         }
 7410:     }
 7411:     return $canreq;
 7412: }
 7413: 
 7414: # ---------------------------------------------- Custom access rule evaluation
 7415: 
 7416: sub customaccess {
 7417:     my ($priv,$uri)=@_;
 7418:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7419:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7420:     $udom = &LONCAPA::clean_domain($udom);
 7421:     $ucrs = &LONCAPA::clean_username($ucrs);
 7422:     my $access=0;
 7423:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7424: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7425: 	if ($type eq 'user') {
 7426: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7427: 		my ($tdom,$tuname)=split(m{/},$scope);
 7428: 		if ($tdom) {
 7429: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7430: 		}
 7431: 		if ($tuname) {
 7432: 		    if ($tuname ne $env{'user.name'}) { next; }
 7433: 		}
 7434: 		$access=($effect eq 'allow');
 7435: 		last;
 7436: 	    }
 7437: 	} else {
 7438: 	    if ($role) {
 7439: 		if ($role ne $urole) { next; }
 7440: 	    }
 7441: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7442: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7443: 		if ($tdom) {
 7444: 		    if ($tdom ne $udom) { next; }
 7445: 		}
 7446: 		if ($tcrs) {
 7447: 		    if ($tcrs ne $ucrs) { next; }
 7448: 		}
 7449: 		if ($tsec) {
 7450: 		    if ($tsec ne $usec) { next; }
 7451: 		}
 7452: 		$access=($effect eq 'allow');
 7453: 		last;
 7454: 	    }
 7455: 	    if ($realm eq '' && $role eq '') {
 7456: 		$access=($effect eq 'allow');
 7457: 	    }
 7458: 	}
 7459:     }
 7460:     return $access;
 7461: }
 7462: 
 7463: # ------------------------------------------------- Check for a user privilege
 7464: 
 7465: sub allowed {
 7466:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7467:     my $ver_orguri=$uri;
 7468:     $uri=&deversion($uri);
 7469:     my $orguri=$uri;
 7470:     $uri=&declutter($uri);
 7471: 
 7472:     if ($priv eq 'evb') {
 7473: # Evade communication block restrictions for specified role in a course
 7474:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7475:             return $1;
 7476:         } else {
 7477:             return;
 7478:         }
 7479:     }
 7480: 
 7481:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7482: # Free bre access to adm and meta resources
 7483:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7484: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7485: 	&& ($priv eq 'bre')) {
 7486: 	return 'F';
 7487:     }
 7488: 
 7489: # Free bre access to user's own portfolio contents
 7490:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7491:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7492: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7493:         my %setters;
 7494:         my ($startblock,$endblock) = 
 7495:             &Apache::loncommon::blockcheck(\%setters,'port');
 7496:         if ($startblock && $endblock) {
 7497:             return 'B';
 7498:         } else {
 7499:             return 'F';
 7500:         }
 7501:     }
 7502: 
 7503: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7504:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7505:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7506:         if (exists($env{'request.course.id'})) {
 7507:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7508:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7509:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7510:                 my $courseprivid=$env{'request.course.id'};
 7511:                 $courseprivid=~s/\_/\//;
 7512:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7513:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7514:                     return $1; 
 7515:                 } else {
 7516:                     if ($env{'request.course.sec'}) {
 7517:                         $courseprivid.='/'.$env{'request.course.sec'};
 7518:                     }
 7519:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7520:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7521:                         return $2;
 7522:                     }
 7523:                 }
 7524:             }
 7525:         }
 7526:     }
 7527: 
 7528: # Free bre to public access
 7529: 
 7530:     if ($priv eq 'bre') {
 7531:         my $copyright;
 7532:         unless ($uri =~ /ext\.tool/) {
 7533:             $copyright=&metadata($uri,'copyright');
 7534:         }
 7535: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7536:            return 'F'; 
 7537:         }
 7538:         if ($copyright eq 'priv') {
 7539:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7540: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7541: 		return '';
 7542:             }
 7543:         }
 7544:         if ($copyright eq 'domain') {
 7545:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7546: 	    unless (($env{'user.domain'} eq $1) ||
 7547:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7548: 		return '';
 7549:             }
 7550:         }
 7551:         if ($env{'request.role'}=~ /li\.\//) {
 7552:             # Library role, so allow browsing of resources in this domain.
 7553:             return 'F';
 7554:         }
 7555:         if ($copyright eq 'custom') {
 7556: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7557:         }
 7558:     }
 7559:     # Domain coordinator is trying to create a course
 7560:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7561:         # uri is the requested domain in this case.
 7562:         # comparison to 'request.role.domain' shows if the user has selected
 7563:         # a role of dc for the domain in question.
 7564:         return 'F' if ($uri eq $env{'request.role.domain'});
 7565:     }
 7566: 
 7567:     my $thisallowed='';
 7568:     my $statecond=0;
 7569:     my $courseprivid='';
 7570: 
 7571:     my $ownaccess;
 7572:     # Community Coordinator or Assistant Co-author browsing resource space.
 7573:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7574:         if ($uri eq '') {
 7575:             $ownaccess = 1;
 7576:         } else {
 7577:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7578:                 my $udom = $env{'user.domain'};
 7579:                 my $uname = $env{'user.name'};
 7580:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7581:                     $ownaccess = 1;
 7582:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7583:                     unless ($uri =~ m{\.\./}) {
 7584:                         $ownaccess = 1;
 7585:                     }
 7586:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7587:                     my $now = time;
 7588:                     if ($uri =~ m{^([^/]+)/?$}) {
 7589:                         my $adom = $1;
 7590:                         foreach my $key (keys(%env)) {
 7591:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7592:                                 my ($start,$end) = split('.',$env{$key});
 7593:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7594:                                     $ownaccess = 1;
 7595:                                     last;
 7596:                                 }
 7597:                             }
 7598:                         }
 7599:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7600:                         my $adom = $1;
 7601:                         my $aname = $2;
 7602:                         foreach my $role ('ca','aa') { 
 7603:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7604:                                 my ($start,$end) =
 7605:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7606:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7607:                                     $ownaccess = 1;
 7608:                                     last;
 7609:                                 }
 7610:                             }
 7611:                         }
 7612:                     }
 7613:                 }
 7614:             }
 7615:         }
 7616:     }
 7617: 
 7618: # Course
 7619: 
 7620:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7621:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7622:             $thisallowed.=$1;
 7623:         }
 7624:     }
 7625: 
 7626: # Domain
 7627: 
 7628:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7629:        =~/\Q$priv\E\&([^\:]*)/) {
 7630:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7631:             $thisallowed.=$1;
 7632:         }
 7633:     }
 7634: 
 7635: # User who is not author or co-author might still be able to edit
 7636: # resource of an author in the domain (e.g., if Domain Coordinator).
 7637:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7638:         (&allowed('mdc',$env{'request.course.id'}))) {
 7639:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7640:             $thisallowed.=$1;
 7641:         }
 7642:     }
 7643: 
 7644: # Course: uri itself is a course
 7645:     my $courseuri=$uri;
 7646:     $courseuri=~s/\_(\d)/\/$1/;
 7647:     $courseuri=~s/^([^\/])/\/$1/;
 7648: 
 7649:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7650:        =~/\Q$priv\E\&([^\:]*)/) {
 7651:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7652:             $thisallowed.=$1;
 7653:         }
 7654:     }
 7655: 
 7656: # URI is an uploaded document for this course, default permissions don't matter
 7657: # not allowing 'edit' access (editupload) to uploaded course docs
 7658:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7659: 	$thisallowed='';
 7660:         my ($match)=&is_on_map($uri);
 7661:         if ($match) {
 7662:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7663:                   =~/\Q$priv\E\&([^\:]*)/) {
 7664:                 my $value = $1;
 7665:                 if ($noblockcheck) {
 7666:                     $thisallowed.=$value;
 7667:                 } else {
 7668:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7669:                     if (@blockers > 0) {
 7670:                         $thisallowed = 'B';
 7671:                     } else {
 7672:                         $thisallowed.=$value;
 7673:                     }
 7674:                 }
 7675:             }
 7676:         } else {
 7677:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7678:             if ($refuri) {
 7679:                 if ($refuri =~ m|^/adm/|) {
 7680:                     $thisallowed='F';
 7681:                 } else {
 7682:                     $refuri=&declutter($refuri);
 7683:                     my ($match) = &is_on_map($refuri);
 7684:                     if ($match) {
 7685:                         if ($noblockcheck) {
 7686:                             $thisallowed='F';
 7687:                         } else {
 7688:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7689:                             if (@blockers > 0) {
 7690:                                 $thisallowed = 'B';
 7691:                             } else {
 7692:                                 $thisallowed='F';
 7693:                             }
 7694:                         }
 7695:                     }
 7696:                 }
 7697:             }
 7698:         }
 7699:     }
 7700: 
 7701:     if ($priv eq 'bre'
 7702: 	&& $thisallowed ne 'F' 
 7703: 	&& $thisallowed ne '2'
 7704: 	&& &is_portfolio_url($uri)) {
 7705: 	$thisallowed = &portfolio_access($uri,$clientip);
 7706:     }
 7707: 
 7708: # Full access at system, domain or course-wide level? Exit.
 7709:     if ($thisallowed=~/F/) {
 7710: 	return 'F';
 7711:     }
 7712: 
 7713: # If this is generating or modifying users, exit with special codes
 7714: 
 7715:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7716: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7717: 	    my ($audom,$auname)=split('/',$uri);
 7718: # no author name given, so this just checks on the general right to make a co-author in this domain
 7719: 	    unless ($auname) { return $thisallowed; }
 7720: # an author name is given, so we are about to actually make a co-author for a certain account
 7721: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7722: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7723: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7724: 	}
 7725: 	return $thisallowed;
 7726:     }
 7727: #
 7728: # Gathered so far: system, domain and course wide privileges
 7729: #
 7730: # Course: See if uri or referer is an individual resource that is part of 
 7731: # the course
 7732: 
 7733:     if ($env{'request.course.id'}) {
 7734: 
 7735:        $courseprivid=$env{'request.course.id'};
 7736:        if ($env{'request.course.sec'}) {
 7737:           $courseprivid.='/'.$env{'request.course.sec'};
 7738:        }
 7739:        $courseprivid=~s/\_/\//;
 7740:        my $checkreferer=1;
 7741:        my ($match,$cond)=&is_on_map($uri);
 7742:        if ($match) {
 7743:            $statecond=$cond;
 7744:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7745:                =~/\Q$priv\E\&([^\:]*)/) {
 7746:                my $value = $1;
 7747:                if ($priv eq 'bre') {
 7748:                    if ($noblockcheck) {
 7749:                        $thisallowed.=$value;
 7750:                    } else {
 7751:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7752:                        if (@blockers > 0) {
 7753:                            $thisallowed = 'B';
 7754:                        } else {
 7755:                            $thisallowed.=$value;
 7756:                        }
 7757:                    }
 7758:                } else {
 7759:                    $thisallowed.=$value;
 7760:                }
 7761:                $checkreferer=0;
 7762:            }
 7763:        }
 7764:        
 7765:        if ($checkreferer) {
 7766: 	  my $refuri=$env{'httpref.'.$orguri};
 7767:             unless ($refuri) {
 7768:                 foreach my $key (keys(%env)) {
 7769: 		    if ($key=~/^httpref\..*\*/) {
 7770: 			my $pattern=$key;
 7771:                         $pattern=~s/^httpref\.\/res\///;
 7772:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7773:                         $pattern=~s/\//\\\//g;
 7774:                         if ($orguri=~/$pattern/) {
 7775: 			    $refuri=$env{$key};
 7776:                         }
 7777:                     }
 7778:                 }
 7779:             }
 7780: 
 7781:          if ($refuri) { 
 7782: 	  $refuri=&declutter($refuri);
 7783:           my ($match,$cond)=&is_on_map($refuri);
 7784:             if ($match) {
 7785:               my $refstatecond=$cond;
 7786:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7787:                   =~/\Q$priv\E\&([^\:]*)/) {
 7788:                   my $value = $1;
 7789:                   if ($priv eq 'bre') {
 7790:                       if ($noblockcheck) {
 7791:                           $thisallowed.=$value;
 7792:                       } else {
 7793:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7794:                           if (@blockers > 0) {
 7795:                               $thisallowed = 'B';
 7796:                           } else {
 7797:                               $thisallowed.=$value;
 7798:                           }
 7799:                       }
 7800:                   } else {
 7801:                       $thisallowed.=$value;
 7802:                   }
 7803:                   $uri=$refuri;
 7804:                   $statecond=$refstatecond;
 7805:               }
 7806:           }
 7807:         }
 7808:        }
 7809:    }
 7810: 
 7811: #
 7812: # Gathered now: all privileges that could apply, and condition number
 7813: # 
 7814: #
 7815: # Full or no access?
 7816: #
 7817: 
 7818:     if ($thisallowed=~/F/) {
 7819: 	return 'F';
 7820:     }
 7821: 
 7822:     unless ($thisallowed) {
 7823:         return '';
 7824:     }
 7825: 
 7826: # Restrictions exist, deal with them
 7827: #
 7828: #   C:according to course preferences
 7829: #   R:according to resource settings
 7830: #   L:unless locked
 7831: #   X:according to user session state
 7832: #
 7833: 
 7834: # Possibly locked functionality, check all courses
 7835: # Locks might take effect only after 10 minutes cache expiration for other
 7836: # courses, and 2 minutes for current course
 7837: 
 7838:     my $envkey;
 7839:     if ($thisallowed=~/L/) {
 7840:         foreach $envkey (keys(%env)) {
 7841:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7842:                my $courseid=$2;
 7843:                my $roleid=$1.'.'.$2;
 7844:                $courseid=~s/^\///;
 7845:                my $expiretime=600;
 7846:                if ($env{'request.role'} eq $roleid) {
 7847: 		  $expiretime=120;
 7848:                }
 7849: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7850:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7851:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7852: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7853:                }
 7854:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7855:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7856: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7857:                        &log($env{'user.domain'},$env{'user.name'},
 7858:                             $env{'user.home'},
 7859:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7860:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7861:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7862: 		       return '';
 7863:                    }
 7864:                }
 7865:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7866:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7867: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7868:                        &log($env{'user.domain'},$env{'user.name'},
 7869:                             $env{'user.home'},
 7870:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7871:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7872:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7873: 		       return '';
 7874:                    }
 7875:                }
 7876: 	   }
 7877:        }
 7878:     }
 7879:    
 7880: #
 7881: # Rest of the restrictions depend on selected course
 7882: #
 7883: 
 7884:     unless ($env{'request.course.id'}) {
 7885: 	if ($thisallowed eq 'A') {
 7886: 	    return 'A';
 7887:         } elsif ($thisallowed eq 'B') {
 7888:             return 'B';
 7889: 	} else {
 7890: 	    return '1';
 7891: 	}
 7892:     }
 7893: 
 7894: #
 7895: # Now user is definitely in a course
 7896: #
 7897: 
 7898: 
 7899: # Course preferences
 7900: 
 7901:    if ($thisallowed=~/C/) {
 7902:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7903:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7904:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7905: 	   =~/\Q$rolecode\E/) {
 7906: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7907: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7908: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7909: 			$env{'request.course.id'});
 7910: 	   }
 7911:            return '';
 7912:        }
 7913: 
 7914:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7915: 	   =~/\Q$unamedom\E/) {
 7916: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7917: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7918: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7919: 			$env{'request.course.id'});
 7920: 	   }
 7921:            return '';
 7922:        }
 7923:    }
 7924: 
 7925: # Resource preferences
 7926: 
 7927:    if ($thisallowed=~/R/) {
 7928:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7929:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7930: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7931: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7932: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7933: 	   }
 7934: 	   return '';
 7935:        }
 7936:    }
 7937: 
 7938: # Restricted by state or randomout?
 7939: 
 7940:    if ($thisallowed=~/X/) {
 7941:       if ($env{'acc.randomout'}) {
 7942: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7943:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7944:             return ''; 
 7945:          }
 7946:       }
 7947:       if (&condval($statecond)) {
 7948: 	 return '2';
 7949:       } else {
 7950:          return '';
 7951:       }
 7952:    }
 7953: 
 7954:     if ($thisallowed eq 'A') {
 7955: 	return 'A';
 7956:     } elsif ($thisallowed eq 'B') {
 7957:         return 'B';
 7958:     }
 7959:    return 'F';
 7960: }
 7961: 
 7962: # ------------------------------------------- Check construction space access
 7963: 
 7964: sub constructaccess {
 7965:     my ($url,$setpriv)=@_;
 7966: 
 7967: # We do not allow editing of previous versions of files
 7968:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7969: 
 7970: # Get username and domain from URL
 7971:     my ($ownername,$ownerdomain,$ownerhome);
 7972: 
 7973:     ($ownerdomain,$ownername) =
 7974:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 7975: 
 7976: # The URL does not really point to any authorspace, forget it
 7977:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7978: 
 7979: # Now we need to see if the user has access to the authorspace of
 7980: # $ownername at $ownerdomain
 7981: 
 7982:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7983: # Real author for this?
 7984:        $ownerhome = $env{'user.home'};
 7985:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7986:           return ($ownername,$ownerdomain,$ownerhome);
 7987:        }
 7988:     } else {
 7989: # Co-author for this?
 7990:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7991:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7992:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7993:             return ($ownername,$ownerdomain,$ownerhome);
 7994:         }
 7995:         if ($env{'request.course.id'}) {
 7996:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 7997:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 7998:                 if (&allowed('mdc',$env{'request.course.id'})) {
 7999:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8000:                     return ($ownername,$ownerdomain,$ownerhome);
 8001:                 }
 8002:             }
 8003:         }
 8004:     }
 8005: 
 8006: # We don't have any access right now. If we are not possibly going to do anything about this,
 8007: # we might as well leave
 8008:    unless ($setpriv) { return ''; }
 8009: 
 8010: # Backdoor access?
 8011:     my $allowed=&allowed('eco',$ownerdomain);
 8012: # Nope
 8013:     unless ($allowed) { return ''; }
 8014: # Looks like we may have access, but could be locked by the owner of the construction space
 8015:     if ($allowed eq 'U') {
 8016:         my %blocked=&get('environment',['domcoord.author'],
 8017:                          $ownerdomain,$ownername);
 8018: # Is blocked by owner
 8019:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8020:     }
 8021:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8022: # Grant temporary access
 8023:         my $then=$env{'user.login.time'};
 8024:         my $update=$env{'user.update.time'};
 8025:         if (!$update) { $update = $then; }
 8026:         my $refresh=$env{'user.refresh.time'};
 8027:         if (!$refresh) { $refresh = $update; }
 8028:         my $now = time;
 8029:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8030:                            $now,'ca','constructaccess');
 8031:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8032:         return($ownername,$ownerdomain,$ownerhome);
 8033:     }
 8034: # No business here
 8035:     return '';
 8036: }
 8037: 
 8038: # ----------------------------------------------------------- Content Blocking
 8039: 
 8040: {
 8041: # Caches for faster Course Contents display where content blocking
 8042: # is in operation (i.e., interval param set) for timed quiz.
 8043: #
 8044: # User for whom data are being temporarily cached.
 8045: my $cacheduser='';
 8046: # Cached blockers for this user (a hash of blocking items). 
 8047: my %cachedblockers=();
 8048: # When the data were last cached.
 8049: my $cachedlast='';
 8050: 
 8051: sub load_all_blockers {
 8052:     my ($uname,$udom,$blocks)=@_;
 8053:     if (($uname ne '') && ($udom ne '')) { 
 8054:         if (($cacheduser eq $uname.':'.$udom) &&
 8055:             (abs($cachedlast-time)<5)) {
 8056:             return;
 8057:         }
 8058:     }
 8059:     $cachedlast=time;
 8060:     $cacheduser=$uname.':'.$udom;
 8061:     %cachedblockers = &get_commblock_resources($blocks);
 8062: }
 8063: 
 8064: sub get_comm_blocks {
 8065:     my ($cdom,$cnum) = @_;
 8066:     if ($cdom eq '' || $cnum eq '') {
 8067:         return unless ($env{'request.course.id'});
 8068:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8069:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8070:     }
 8071:     my %commblocks;
 8072:     my $hashid=$cdom.'_'.$cnum;
 8073:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8074:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8075:         %commblocks = %{$blocksref};
 8076:     } else {
 8077:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8078:         my $cachetime = 600;
 8079:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8080:     }
 8081:     return %commblocks;
 8082: }
 8083: 
 8084: sub get_commblock_resources {
 8085:     my ($blocks) = @_;
 8086:     my %blockers = ();
 8087:     return %blockers unless ($env{'request.course.id'});
 8088:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8089:     my %commblocks;
 8090:     if (ref($blocks) eq 'HASH') {
 8091:         %commblocks = %{$blocks};
 8092:     } else {
 8093:         %commblocks = &get_comm_blocks();
 8094:     }
 8095:     return %blockers unless (keys(%commblocks) > 0); 
 8096:     my $navmap = Apache::lonnavmaps::navmap->new();
 8097:     return %blockers unless (ref($navmap));
 8098:     my $now = time;
 8099:     foreach my $block (keys(%commblocks)) {
 8100:         if ($block =~ /^(\d+)____(\d+)$/) {
 8101:             my ($start,$end) = ($1,$2);
 8102:             if ($start <= $now && $end >= $now) {
 8103:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8104:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8105:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8106:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8107:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8108:                             }
 8109:                         }
 8110:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8111:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8112:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8113:                             }
 8114:                         }
 8115:                     }
 8116:                 }
 8117:             }
 8118:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8119:             my $item = $1;
 8120:             my @to_test;
 8121:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8122:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8123:                     my @interval;
 8124:                     my $type = 'map';
 8125:                     if ($item eq 'course') {
 8126:                         $type = 'course';
 8127:                         @interval=&EXT("resource.0.interval");
 8128:                     } else {
 8129:                         if ($item =~ /___\d+___/) {
 8130:                             $type = 'resource';
 8131:                             @interval=&EXT("resource.0.interval",$item);
 8132:                             if (ref($navmap)) {                        
 8133:                                 my $res = $navmap->getBySymb($item); 
 8134:                                 push(@to_test,$res);
 8135:                             }
 8136:                         } else {
 8137:                             my $mapsymb = &symbread($item,1);
 8138:                             if ($mapsymb) {
 8139:                                 if (ref($navmap)) {
 8140:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8141:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8142:                                     foreach my $res (@to_test) {
 8143:                                         my $symb = $res->symb();
 8144:                                         next if ($symb eq $mapsymb);
 8145:                                         if ($symb ne '') {
 8146:                                             @interval=&EXT("resource.0.interval",$symb);
 8147:                                             if ($interval[1] eq 'map') {
 8148:                                                 last;
 8149:                                             }
 8150:                                         }
 8151:                                     }
 8152:                                 }
 8153:                             }
 8154:                         }
 8155:                     }
 8156:                     if ($interval[0] =~ /^(\d+)/) {
 8157:                         my $timelimit = $1; 
 8158:                         my $first_access;
 8159:                         if ($type eq 'resource') {
 8160:                             $first_access=&get_first_access($interval[1],$item);
 8161:                         } elsif ($type eq 'map') {
 8162:                             $first_access=&get_first_access($interval[1],undef,$item);
 8163:                         } else {
 8164:                             $first_access=&get_first_access($interval[1]);
 8165:                         }
 8166:                         if ($first_access) {
 8167:                             my $timesup = $first_access+$timelimit;
 8168:                             if ($timesup > $now) {
 8169:                                 my $activeblock;
 8170:                                 foreach my $res (@to_test) {
 8171:                                     if ($res->answerable()) {
 8172:                                         $activeblock = 1;
 8173:                                         last;
 8174:                                     }
 8175:                                 }
 8176:                                 if ($activeblock) {
 8177:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8178:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8179:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8180:                                          }
 8181:                                     }
 8182:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8183:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8184:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8185:                                         }
 8186:                                     }
 8187:                                 }
 8188:                             }
 8189:                         }
 8190:                     }
 8191:                 }
 8192:             }
 8193:         }
 8194:     }
 8195:     return %blockers;
 8196: }
 8197: 
 8198: sub has_comm_blocking {
 8199:     my ($priv,$symb,$uri,$blocks) = @_;
 8200:     my @blockers;
 8201:     return unless ($env{'request.course.id'});
 8202:     return unless ($priv eq 'bre');
 8203:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8204:     return if ($env{'request.state'} eq 'construct');
 8205:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8206:     return unless (keys(%cachedblockers) > 0);
 8207:     my (%possibles,@symbs);
 8208:     if (!$symb) {
 8209:         $symb = &symbread($uri,1,1,1,\%possibles);
 8210:     }
 8211:     if ($symb) {
 8212:         @symbs = ($symb);
 8213:     } elsif (keys(%possibles)) { 
 8214:         @symbs = keys(%possibles);
 8215:     }
 8216:     my $noblock;
 8217:     foreach my $symb (@symbs) {
 8218:         last if ($noblock);
 8219:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8220:         foreach my $block (keys(%cachedblockers)) {
 8221:             if ($block =~ /^firstaccess____(.+)$/) {
 8222:                 my $item = $1;
 8223:                 if (($item eq $map) || ($item eq $symb)) {
 8224:                     $noblock = 1;
 8225:                     last;
 8226:                 }
 8227:             }
 8228:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8229:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8230:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8231:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8232:                             push(@blockers,$block);
 8233:                         }
 8234:                     }
 8235:                 }
 8236:             }
 8237:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8238:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8239:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8240:                         push(@blockers,$block);
 8241:                     }
 8242:                 }
 8243:             }
 8244:         }
 8245:     }
 8246:     return if ($noblock);
 8247:     return @blockers;
 8248: }
 8249: }
 8250: 
 8251: # -------------------------------- Deversion and split uri into path an filename   
 8252: 
 8253: #
 8254: #   Removes the version from a URI and
 8255: #   splits it in to its filename and path to the filename.
 8256: #   Seems like File::Basename could have done this more clearly.
 8257: #   Parameters:
 8258: #      $uri   - input URI
 8259: #   Returns:
 8260: #     Two element list consisting of 
 8261: #     $pathname  - the URI up to and excluding the trailing /
 8262: #     $filename  - The part of the URI following the last /
 8263: #  NOTE:
 8264: #    Another realization of this is simply:
 8265: #    use File::Basename;
 8266: #    ...
 8267: #    $uri = shift;
 8268: #    $filename = basename($uri);
 8269: #    $path     = dirname($uri);
 8270: #    return ($filename, $path);
 8271: #
 8272: #     The implementation below is probably faster however.
 8273: #
 8274: sub split_uri_for_cond {
 8275:     my $uri=&deversion(&declutter(shift));
 8276:     my @uriparts=split(/\//,$uri);
 8277:     my $filename=pop(@uriparts);
 8278:     my $pathname=join('/',@uriparts);
 8279:     return ($pathname,$filename);
 8280: }
 8281: # --------------------------------------------------- Is a resource on the map?
 8282: 
 8283: sub is_on_map {
 8284:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8285:     #Trying to find the conditional for the file
 8286:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8287: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8288:     if ($match) {
 8289: 	return (1,$1);
 8290:     } else {
 8291: 	return (0,0);
 8292:     }
 8293: }
 8294: 
 8295: # --------------------------------------------------------- Get symb from alias
 8296: 
 8297: sub get_symb_from_alias {
 8298:     my $symb=shift;
 8299:     my ($map,$resid,$url)=&decode_symb($symb);
 8300: # Already is a symb
 8301:     if ($url) { return $symb; }
 8302: # Must be an alias
 8303:     my $aliassymb='';
 8304:     my %bighash;
 8305:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8306:                             &GDBM_READER(),0640)) {
 8307:         my $rid=$bighash{'mapalias_'.$symb};
 8308: 	if ($rid) {
 8309: 	    my ($mapid,$resid)=split(/\./,$rid);
 8310: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8311: 				    $resid,$bighash{'src_'.$rid});
 8312: 	}
 8313:         untie %bighash;
 8314:     }
 8315:     return $aliassymb;
 8316: }
 8317: 
 8318: # ----------------------------------------------------------------- Define Role
 8319: 
 8320: sub definerole {
 8321:   if (allowed('mcr','/')) {
 8322:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8323:     foreach my $role (split(':',$sysrole)) {
 8324: 	my ($crole,$cqual)=split(/\&/,$role);
 8325:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8326:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8327: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8328:                return "refused:s:$crole&$cqual"; 
 8329:             }
 8330:         }
 8331:     }
 8332:     foreach my $role (split(':',$domrole)) {
 8333: 	my ($crole,$cqual)=split(/\&/,$role);
 8334:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8335:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8336: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8337:                return "refused:d:$crole&$cqual"; 
 8338:             }
 8339:         }
 8340:     }
 8341:     foreach my $role (split(':',$courole)) {
 8342: 	my ($crole,$cqual)=split(/\&/,$role);
 8343:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8344:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8345: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8346:                return "refused:c:$crole&$cqual"; 
 8347:             }
 8348:         }
 8349:     }
 8350:     my $uhome;
 8351:     if (($uname ne '') && ($udom ne '')) {
 8352:         $uhome = &homeserver($uname,$udom);
 8353:         return $uhome if ($uhome eq 'no_host');
 8354:     } else {
 8355:         $uname = $env{'user.name'};
 8356:         $udom = $env{'user.domain'};
 8357:         $uhome = $env{'user.home'};
 8358:     }
 8359:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8360:                 "$udom:$uname:rolesdef_$rolename=".
 8361:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8362:     return reply($command,$uhome);
 8363:   } else {
 8364:     return 'refused';
 8365:   }
 8366: }
 8367: 
 8368: # ---------------- Make a metadata query against the network of library servers
 8369: 
 8370: sub metadata_query {
 8371:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8372:     my %rhash;
 8373:     my %libserv = &all_library();
 8374:     my @server_list = (defined($server_array) ? @$server_array
 8375:                                               : keys(%libserv) );
 8376:     for my $server (@server_list) {
 8377:         my $domains = ''; 
 8378:         if (ref($domains_hash) eq 'HASH') {
 8379:             $domains = $domains_hash->{$server}; 
 8380:         }
 8381: 	unless ($custom or $customshow) {
 8382: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8383: 	    $rhash{$server}=$reply;
 8384: 	}
 8385: 	else {
 8386: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8387: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8388: 			     $server);
 8389: 	    $rhash{$server}=$reply;
 8390: 	}
 8391:     }
 8392:     return \%rhash;
 8393: }
 8394: 
 8395: # ----------------------------------------- Send log queries and wait for reply
 8396: 
 8397: sub log_query {
 8398:     my ($uname,$udom,$query,%filters)=@_;
 8399:     my $uhome=&homeserver($uname,$udom);
 8400:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8401:     my $uhost=&hostname($uhome);
 8402:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8403:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8404:                        $uhome);
 8405:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8406:     return get_query_reply($queryid);
 8407: }
 8408: 
 8409: # -------------------------- Update MySQL table for portfolio file
 8410: 
 8411: sub update_portfolio_table {
 8412:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8413:     if ($group ne '') {
 8414:         $file_name =~s /^\Q$group\E//;
 8415:     }
 8416:     my $homeserver = &homeserver($uname,$udom);
 8417:     my $queryid=
 8418:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8419:                ':'.&escape($file_name).':'.$action,$homeserver);
 8420:     my $reply = &get_query_reply($queryid);
 8421:     return $reply;
 8422: }
 8423: 
 8424: # -------------------------- Update MySQL allusers table
 8425: 
 8426: sub update_allusers_table {
 8427:     my ($uname,$udom,$names) = @_;
 8428:     my $homeserver = &homeserver($uname,$udom);
 8429:     my $queryid=
 8430:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8431:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8432:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8433:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8434:                'generation='.&escape($names->{'generation'}).'%%'.
 8435:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8436:                'id='.&escape($names->{'id'}),$homeserver);
 8437:     return;
 8438: }
 8439: 
 8440: # ------- Request retrieval of institutional classlists for course(s)
 8441: 
 8442: sub fetch_enrollment_query {
 8443:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8444:     my ($homeserver,$sleep,$loopmax);
 8445:     my $maxtries = 1;
 8446:     if ($context eq 'automated') {
 8447:         $homeserver = $perlvar{'lonHostID'};
 8448:         $sleep = 2;
 8449:         $loopmax = 100;
 8450:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8451:     } else {
 8452:         $homeserver = &homeserver($cnum,$dom);
 8453:     }
 8454:     my $host=&hostname($homeserver);
 8455:     my $cmd = '';
 8456:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8457:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8458:     }
 8459:     $cmd =~ s/%%$//;
 8460:     $cmd = &escape($cmd);
 8461:     my $query = 'fetchenrollment';
 8462:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8463:     unless ($queryid=~/^\Q$host\E\_/) { 
 8464:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8465:         return 'error: '.$queryid;
 8466:     }
 8467:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8468:     my $tries = 1;
 8469:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8470:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8471:         $tries ++;
 8472:     }
 8473:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8474:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8475:     } else {
 8476:         my @responses = split(/:/,$reply);
 8477:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8478:             foreach my $line (@responses) {
 8479:                 my ($key,$value) = split(/=/,$line,2);
 8480:                 $$replyref{$key} = $value;
 8481:             }
 8482:         } else {
 8483:             my $pathname = LONCAPA::tempdir();
 8484:             foreach my $line (@responses) {
 8485:                 my ($key,$value) = split(/=/,$line);
 8486:                 $$replyref{$key} = $value;
 8487:                 if ($value > 0) {
 8488:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8489:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8490:                         my $destname = $pathname.'/'.$filename;
 8491:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8492:                         if ($xml_classlist =~ /^error/) {
 8493:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8494:                         } else {
 8495:                             if ( open(FILE,">",$destname) ) {
 8496:                                 print FILE &unescape($xml_classlist);
 8497:                                 close(FILE);
 8498:                             } else {
 8499:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8500:                             }
 8501:                         }
 8502:                     }
 8503:                 }
 8504:             }
 8505:         }
 8506:         return 'ok';
 8507:     }
 8508:     return 'error';
 8509: }
 8510: 
 8511: sub get_query_reply {
 8512:     my ($queryid,$sleep,$loopmax) = @_;;
 8513:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8514:         $sleep = 0.2;
 8515:     }
 8516:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8517:         $loopmax = 100;
 8518:     }
 8519:     my $replyfile=LONCAPA::tempdir().$queryid;
 8520:     my $reply='';
 8521:     for (1..$loopmax) {
 8522: 	sleep($sleep);
 8523:         if (-e $replyfile.'.end') {
 8524: 	    if (open(my $fh,"<",$replyfile)) {
 8525: 		$reply = join('',<$fh>);
 8526: 		close($fh);
 8527: 	   } else { return 'error: reply_file_error'; }
 8528:            return &unescape($reply);
 8529: 	}
 8530:     }
 8531:     return 'timeout:'.$queryid;
 8532: }
 8533: 
 8534: sub courselog_query {
 8535: #
 8536: # possible filters:
 8537: # url: url or symb
 8538: # username
 8539: # domain
 8540: # action: view, submit, grade
 8541: # start: timestamp
 8542: # end: timestamp
 8543: #
 8544:     my (%filters)=@_;
 8545:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8546:     if ($filters{'url'}) {
 8547: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8548:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8549:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8550:     }
 8551:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8552:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8553:     return &log_query($cname,$cdom,'courselog',%filters);
 8554: }
 8555: 
 8556: sub userlog_query {
 8557: #
 8558: # possible filters:
 8559: # action: log check role
 8560: # start: timestamp
 8561: # end: timestamp
 8562: #
 8563:     my ($uname,$udom,%filters)=@_;
 8564:     return &log_query($uname,$udom,'userlog',%filters);
 8565: }
 8566: 
 8567: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8568: 
 8569: sub auto_run {
 8570:     my ($cnum,$cdom) = @_;
 8571:     my $response = 0;
 8572:     my $settings;
 8573:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8574:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8575:         $settings = $domconfig{'autoenroll'};
 8576:         if ($settings->{'run'} eq '1') {
 8577:             $response = 1;
 8578:         }
 8579:     } else {
 8580:         my $homeserver;
 8581:         if (&is_course($cdom,$cnum)) {
 8582:             $homeserver = &homeserver($cnum,$cdom);
 8583:         } else {
 8584:             $homeserver = &domain($cdom,'primary');
 8585:         }
 8586:         if ($homeserver ne 'no_host') {
 8587:             $response = &reply('autorun:'.$cdom,$homeserver);
 8588:         }
 8589:     }
 8590:     return $response;
 8591: }
 8592: 
 8593: sub auto_get_sections {
 8594:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8595:     my $homeserver;
 8596:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8597:         $homeserver = &homeserver($cnum,$cdom);
 8598:     }
 8599:     if (!defined($homeserver)) { 
 8600:         if ($cdom =~ /^$match_domain$/) {
 8601:             $homeserver = &domain($cdom,'primary');
 8602:         }
 8603:     }
 8604:     my @secs;
 8605:     if (defined($homeserver)) {
 8606:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8607:         unless ($response eq 'refused') {
 8608:             @secs = split(/:/,$response);
 8609:         }
 8610:     }
 8611:     return @secs;
 8612: }
 8613: 
 8614: sub auto_new_course {
 8615:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8616:     my $homeserver = &homeserver($cnum,$cdom);
 8617:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8618:     return $response;
 8619: }
 8620: 
 8621: sub auto_validate_courseID {
 8622:     my ($cnum,$cdom,$inst_course_id) = @_;
 8623:     my $homeserver = &homeserver($cnum,$cdom);
 8624:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8625:     return $response;
 8626: }
 8627: 
 8628: sub auto_validate_instcode {
 8629:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8630:     my ($homeserver,$response);
 8631:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8632:         $homeserver = &homeserver($cnum,$cdom);
 8633:     }
 8634:     if (!defined($homeserver)) {
 8635:         if ($cdom =~ /^$match_domain$/) {
 8636:             $homeserver = &domain($cdom,'primary');
 8637:         }
 8638:     }
 8639:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8640:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8641:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8642:     return ($outcome,$description,$defaultcredits);
 8643: }
 8644: 
 8645: sub auto_create_password {
 8646:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8647:     my ($homeserver,$response);
 8648:     my $create_passwd = 0;
 8649:     my $authchk = '';
 8650:     if ($udom =~ /^$match_domain$/) {
 8651:         $homeserver = &domain($udom,'primary');
 8652:     }
 8653:     if ($homeserver eq '') {
 8654:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8655:             $homeserver = &homeserver($cnum,$cdom);
 8656:         }
 8657:     }
 8658:     if ($homeserver eq '') {
 8659:         $authchk = 'nodomain';
 8660:     } else {
 8661:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8662:         if ($response eq 'refused') {
 8663:             $authchk = 'refused';
 8664:         } else {
 8665:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8666:         }
 8667:     }
 8668:     return ($authparam,$create_passwd,$authchk);
 8669: }
 8670: 
 8671: sub auto_photo_permission {
 8672:     my ($cnum,$cdom,$students) = @_;
 8673:     my $homeserver = &homeserver($cnum,$cdom);
 8674:     my ($outcome,$perm_reqd,$conditions) = 
 8675: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8676:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8677: 	return (undef,undef);
 8678:     }
 8679:     return ($outcome,$perm_reqd,$conditions);
 8680: }
 8681: 
 8682: sub auto_checkphotos {
 8683:     my ($uname,$udom,$pid) = @_;
 8684:     my $homeserver = &homeserver($uname,$udom);
 8685:     my ($result,$resulttype);
 8686:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8687: 				   &escape($uname).':'.&escape($pid),
 8688: 				   $homeserver));
 8689:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8690: 	return (undef,undef);
 8691:     }
 8692:     if ($outcome) {
 8693:         ($result,$resulttype) = split(/:/,$outcome);
 8694:     } 
 8695:     return ($result,$resulttype);
 8696: }
 8697: 
 8698: sub auto_photochoice {
 8699:     my ($cnum,$cdom) = @_;
 8700:     my $homeserver = &homeserver($cnum,$cdom);
 8701:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8702: 						       &escape($cdom),
 8703: 						       $homeserver)));
 8704:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8705: 	return (undef,undef);
 8706:     }
 8707:     return ($update,$comment);
 8708: }
 8709: 
 8710: sub auto_photoupdate {
 8711:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8712:     my $homeserver = &homeserver($cnum,$dom);
 8713:     my $host=&hostname($homeserver);
 8714:     my $cmd = '';
 8715:     my $maxtries = 1;
 8716:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8717:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8718:     }
 8719:     $cmd =~ s/%%$//;
 8720:     $cmd = &escape($cmd);
 8721:     my $query = 'institutionalphotos';
 8722:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8723:     unless ($queryid=~/^\Q$host\E\_/) {
 8724:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8725:         return 'error: '.$queryid;
 8726:     }
 8727:     my $reply = &get_query_reply($queryid);
 8728:     my $tries = 1;
 8729:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8730:         $reply = &get_query_reply($queryid);
 8731:         $tries ++;
 8732:     }
 8733:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8734:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8735:     } else {
 8736:         my @responses = split(/:/,$reply);
 8737:         my $outcome = shift(@responses); 
 8738:         foreach my $item (@responses) {
 8739:             my ($key,$value) = split(/=/,$item);
 8740:             $$photo{$key} = $value;
 8741:         }
 8742:         return $outcome;
 8743:     }
 8744:     return 'error';
 8745: }
 8746: 
 8747: sub auto_instcode_format {
 8748:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8749: 	$cat_order) = @_;
 8750:     my $courses = '';
 8751:     my @homeservers;
 8752:     if ($caller eq 'global') {
 8753: 	my %servers = &get_servers($codedom,'library');
 8754: 	foreach my $tryserver (keys(%servers)) {
 8755: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8756: 		push(@homeservers,$tryserver);
 8757: 	    }
 8758:         }
 8759:     } elsif ($caller eq 'requests') {
 8760:         if ($codedom =~ /^$match_domain$/) {
 8761:             my $chome = &domain($codedom,'primary');
 8762:             unless ($chome eq 'no_host') {
 8763:                 push(@homeservers,$chome);
 8764:             }
 8765:         }
 8766:     } else {
 8767:         push(@homeservers,&homeserver($caller,$codedom));
 8768:     }
 8769:     foreach my $code (keys(%{$instcodes})) {
 8770:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8771:     }
 8772:     chop($courses);
 8773:     my $ok_response = 0;
 8774:     my $response;
 8775:     while (@homeservers > 0 && $ok_response == 0) {
 8776:         my $server = shift(@homeservers); 
 8777:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8778:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8779:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8780: 		split(/:/,$response);
 8781:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8782:             push(@{$codetitles},&str2array($codetitles_str));
 8783:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8784:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8785:             $ok_response = 1;
 8786:         }
 8787:     }
 8788:     if ($ok_response) {
 8789:         return 'ok';
 8790:     } else {
 8791:         return $response;
 8792:     }
 8793: }
 8794: 
 8795: sub auto_instcode_defaults {
 8796:     my ($domain,$returnhash,$code_order) = @_;
 8797:     my @homeservers;
 8798: 
 8799:     my %servers = &get_servers($domain,'library');
 8800:     foreach my $tryserver (keys(%servers)) {
 8801: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8802: 	    push(@homeservers,$tryserver);
 8803: 	}
 8804:     }
 8805: 
 8806:     my $response;
 8807:     foreach my $server (@homeservers) {
 8808:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8809:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8810: 	
 8811: 	foreach my $pair (split(/\&/,$response)) {
 8812: 	    my ($name,$value)=split(/\=/,$pair);
 8813: 	    if ($name eq 'code_order') {
 8814: 		@{$code_order} = split(/\&/,&unescape($value));
 8815: 	    } else {
 8816: 		$returnhash->{&unescape($name)}=&unescape($value);
 8817: 	    }
 8818: 	}
 8819: 	return 'ok';
 8820:     }
 8821: 
 8822:     return $response;
 8823: }
 8824: 
 8825: sub auto_possible_instcodes {
 8826:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8827:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8828:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8829:         return;
 8830:     }
 8831:     my (@homeservers,$uhome);
 8832:     if (defined(&domain($domain,'primary'))) {
 8833:         $uhome=&domain($domain,'primary');
 8834:         push(@homeservers,&domain($domain,'primary'));
 8835:     } else {
 8836:         my %servers = &get_servers($domain,'library');
 8837:         foreach my $tryserver (keys(%servers)) {
 8838:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8839:                 push(@homeservers,$tryserver);
 8840:             }
 8841:         }
 8842:     }
 8843:     my $response;
 8844:     foreach my $server (@homeservers) {
 8845:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8846:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8847:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8848:             split(':',$response);
 8849:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8850:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8851:         foreach my $item (split('&',$cat_title)) {   
 8852:             my ($name,$value)=split('=',$item);
 8853:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8854:         }
 8855:         foreach my $item (split('&',$cat_order)) {
 8856:             my ($name,$value)=split('=',$item);
 8857:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8858:         }
 8859:         return 'ok';
 8860:     }
 8861:     return $response;
 8862: }
 8863: 
 8864: sub auto_courserequest_checks {
 8865:     my ($dom) = @_;
 8866:     my ($homeserver,%validations);
 8867:     if ($dom =~ /^$match_domain$/) {
 8868:         $homeserver = &domain($dom,'primary');
 8869:     }
 8870:     unless ($homeserver eq 'no_host') {
 8871:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8872:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8873:             my @items = split(/&/,$response);
 8874:             foreach my $item (@items) {
 8875:                 my ($key,$value) = split('=',$item);
 8876:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8877:             }
 8878:         }
 8879:     }
 8880:     return %validations; 
 8881: }
 8882: 
 8883: sub auto_courserequest_validation {
 8884:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8885:     my ($homeserver,$response);
 8886:     if ($dom =~ /^$match_domain$/) {
 8887:         $homeserver = &domain($dom,'primary');
 8888:     }
 8889:     unless ($homeserver eq 'no_host') {
 8890:         my $customdata;
 8891:         if (ref($custominfo) eq 'HASH') {
 8892:             $customdata = &freeze_escape($custominfo);
 8893:         }
 8894:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8895:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8896:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8897:                                     $customdata,$homeserver));
 8898:     }
 8899:     return $response;
 8900: }
 8901: 
 8902: sub auto_validate_class_sec {
 8903:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8904:     my $homeserver = &homeserver($cnum,$cdom);
 8905:     my $ownerlist;
 8906:     if (ref($owners) eq 'ARRAY') {
 8907:         $ownerlist = join(',',@{$owners});
 8908:     } else {
 8909:         $ownerlist = $owners;
 8910:     }
 8911:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8912:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8913:     return $response;
 8914: }
 8915: 
 8916: sub auto_validate_instclasses {
 8917:     my ($cdom,$cnum,$owners,$classesref) = @_;
 8918:     my ($homeserver,%validations);
 8919:     $homeserver = &homeserver($cnum,$cdom);
 8920:     unless ($homeserver eq 'no_host') {
 8921:         my $ownerlist;
 8922:         if (ref($owners) eq 'ARRAY') {
 8923:             $ownerlist = join(',',@{$owners});
 8924:         } else {
 8925:             $ownerlist = $owners;
 8926:         }
 8927:         if (ref($classesref) eq 'HASH') {
 8928:             my $classes = &freeze_escape($classesref);
 8929:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 8930:                                 ':'.$cdom.':'.$classes,$homeserver);
 8931:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8932:                 my @items = split(/&/,$response);
 8933:                 foreach my $item (@items) {
 8934:                     my ($key,$value) = split('=',$item);
 8935:                     $validations{&unescape($key)} = &thaw_unescape($value);
 8936:                 }
 8937:             }
 8938:         }
 8939:     }
 8940:     return %validations;
 8941: }
 8942: 
 8943: sub auto_crsreq_update {
 8944:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8945:         $code,$accessstart,$accessend,$inbound) = @_;
 8946:     my ($homeserver,%crsreqresponse);
 8947:     if ($cdom =~ /^$match_domain$/) {
 8948:         $homeserver = &domain($cdom,'primary');
 8949:     }
 8950:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8951:         my $info;
 8952:         if (ref($inbound) eq 'HASH') {
 8953:             $info = &freeze_escape($inbound);
 8954:         }
 8955:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8956:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8957:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8958:                             &escape($title).':'.&escape($code).':'.
 8959:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8960:                             $homeserver);
 8961:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8962:             my @items = split(/&/,$response);
 8963:             foreach my $item (@items) {
 8964:                 my ($key,$value) = split('=',$item);
 8965:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8966:             }
 8967:         }
 8968:     }
 8969:     return \%crsreqresponse;
 8970: }
 8971: 
 8972: sub auto_export_grades {
 8973:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 8974:     my ($homeserver,%exportresponse);
 8975:     if ($cdom =~ /^$match_domain$/) {
 8976:         $homeserver = &domain($cdom,'primary');
 8977:     }
 8978:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8979:         my $info;
 8980:         if (ref($inforef) eq 'HASH') {
 8981:             $info = &freeze_escape($inforef);
 8982:         }
 8983:         if (ref($gradesref) eq 'HASH') {
 8984:             my $grades = &freeze_escape($gradesref);
 8985:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 8986:                                 $info.':'.$grades,$homeserver);
 8987:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 8988:                 my @items = split(/&/,$response);
 8989:                 foreach my $item (@items) {
 8990:                     my ($key,$value) = split('=',$item);
 8991:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 8992:                 }
 8993:             }
 8994:         }
 8995:     }
 8996:     return \%exportresponse;
 8997: }
 8998: 
 8999: sub check_instcode_cloning {
 9000:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9001:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9002:         return;
 9003:     }
 9004:     my $canclone;
 9005:     if (@{$code_order} > 0) {
 9006:         my $instcoderegexp ='^';
 9007:         my @clonecodes = split(/\&/,$cloner);
 9008:         foreach my $item (@{$code_order}) {
 9009:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9010:                 foreach my $pair (@clonecodes) {
 9011:                     my ($key,$val) = split(/\=/,$pair,2);
 9012:                     $val = &unescape($val);
 9013:                     if ($key eq $item) {
 9014:                         $instcoderegexp .= '('.$val.')';
 9015:                         last;
 9016:                     }
 9017:                 }
 9018:             } else {
 9019:                 $instcoderegexp .= $codedefaults->{$item};
 9020:             }
 9021:         }
 9022:         $instcoderegexp .= '$';
 9023:         my (@from,@to);
 9024:         eval {
 9025:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9026:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9027:         };
 9028:         if ((@from > 0) && (@to > 0)) {
 9029:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9030:             if (!@diffs) {
 9031:                 $canclone = 1;
 9032:             }
 9033:         }
 9034:     }
 9035:     return $canclone;
 9036: }
 9037: 
 9038: sub default_instcode_cloning {
 9039:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9040:     my (%codedefaults,@code_order,$canclone);
 9041:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9042:         %codedefaults = %{$codedefaultsref};
 9043:         @code_order = @{$codeorderref};
 9044:     } elsif ($clonedom) {
 9045:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9046:     }
 9047:     if (($domdefclone) && (@code_order)) {
 9048:         my @clonecodes = split(/\+/,$domdefclone);
 9049:         my $instcoderegexp ='^';
 9050:         foreach my $item (@code_order) {
 9051:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9052:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9053:             } else {
 9054:                 $instcoderegexp .= $codedefaults{$item};
 9055:             }
 9056:         }
 9057:         $instcoderegexp .= '$';
 9058:         my (@from,@to);
 9059:         eval {
 9060:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9061:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9062:         };
 9063:         if ((@from > 0) && (@to > 0)) {
 9064:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9065:             if (!@diffs) {
 9066:                 $canclone = 1;
 9067:             }
 9068:         }
 9069:     }
 9070:     return $canclone;
 9071: }
 9072: 
 9073: # ------------------------------------------------------- Course Group routines
 9074: 
 9075: sub get_coursegroups {
 9076:     my ($cdom,$cnum,$group,$namespace) = @_;
 9077:     return(&dump($namespace,$cdom,$cnum,$group));
 9078: }
 9079: 
 9080: sub modify_coursegroup {
 9081:     my ($cdom,$cnum,$groupsettings) = @_;
 9082:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9083: }
 9084: 
 9085: sub toggle_coursegroup_status {
 9086:     my ($cdom,$cnum,$group,$action) = @_;
 9087:     my ($from_namespace,$to_namespace);
 9088:     if ($action eq 'delete') {
 9089:         $from_namespace = 'coursegroups';
 9090:         $to_namespace = 'deleted_groups';
 9091:     } else {
 9092:         $from_namespace = 'deleted_groups';
 9093:         $to_namespace = 'coursegroups';
 9094:     }
 9095:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9096:     if (my $tmp = &error(%curr_group)) {
 9097:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9098:         return ('read error',$tmp);
 9099:     } else {
 9100:         my %savedsettings = %curr_group; 
 9101:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9102:         my $deloutcome;
 9103:         if ($result eq 'ok') {
 9104:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9105:         } else {
 9106:             return ('write error',$result);
 9107:         }
 9108:         if ($deloutcome eq 'ok') {
 9109:             return 'ok';
 9110:         } else {
 9111:             return ('delete error',$deloutcome);
 9112:         }
 9113:     }
 9114: }
 9115: 
 9116: sub modify_group_roles {
 9117:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9118:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9119:     my $role = 'gr/'.&escape($userprivs);
 9120:     my ($uname,$udom) = split(/:/,$user);
 9121:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9122:     if ($result eq 'ok') {
 9123:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9124:     }
 9125:     return $result;
 9126: }
 9127: 
 9128: sub modify_coursegroup_membership {
 9129:     my ($cdom,$cnum,$membership) = @_;
 9130:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9131:     return $result;
 9132: }
 9133: 
 9134: sub get_active_groups {
 9135:     my ($udom,$uname,$cdom,$cnum) = @_;
 9136:     my $now = time;
 9137:     my %groups = ();
 9138:     foreach my $key (keys(%env)) {
 9139:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9140:             my ($start,$end) = split(/\./,$env{$key});
 9141:             if (($end!=0) && ($end<$now)) { next; }
 9142:             if (($start!=0) && ($start>$now)) { next; }
 9143:             if ($1 eq $cdom && $2 eq $cnum) {
 9144:                 $groups{$3} = $env{$key} ;
 9145:             }
 9146:         }
 9147:     }
 9148:     return %groups;
 9149: }
 9150: 
 9151: sub get_group_membership {
 9152:     my ($cdom,$cnum,$group) = @_;
 9153:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9154: }
 9155: 
 9156: sub get_users_groups {
 9157:     my ($udom,$uname,$courseid) = @_;
 9158:     my @usersgroups;
 9159:     my $cachetime=1800;
 9160: 
 9161:     my $hashid="$udom:$uname:$courseid";
 9162:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9163:     if (defined($cached)) {
 9164:         @usersgroups = split(/:/,$grouplist);
 9165:     } else {  
 9166:         $grouplist = '';
 9167:         my $courseurl = &courseid_to_courseurl($courseid);
 9168:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9169:         my $access_end = $env{'course.'.$courseid.
 9170:                               '.default_enrollment_end_date'};
 9171:         my $now = time;
 9172:         foreach my $key (keys(%roleshash)) {
 9173:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9174:                 my $group = $1;
 9175:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9176:                     my $start = $2;
 9177:                     my $end = $1;
 9178:                     if ($start == -1) { next; } # deleted from group
 9179:                     if (($start!=0) && ($start>$now)) { next; }
 9180:                     if (($end!=0) && ($end<$now)) {
 9181:                         if ($access_end && $access_end < $now) {
 9182:                             if ($access_end - $end < 86400) {
 9183:                                 push(@usersgroups,$group);
 9184:                             }
 9185:                         }
 9186:                         next;
 9187:                     }
 9188:                     push(@usersgroups,$group);
 9189:                 }
 9190:             }
 9191:         }
 9192:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9193:         $grouplist = join(':',@usersgroups);
 9194:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9195:     }
 9196:     return @usersgroups;
 9197: }
 9198: 
 9199: sub devalidate_getgroups_cache {
 9200:     my ($udom,$uname,$cdom,$cnum)=@_;
 9201:     my $courseid = $cdom.'_'.$cnum;
 9202: 
 9203:     my $hashid="$udom:$uname:$courseid";
 9204:     &devalidate_cache_new('getgroups',$hashid);
 9205: }
 9206: 
 9207: # ------------------------------------------------------------------ Plain Text
 9208: 
 9209: sub plaintext {
 9210:     my ($short,$type,$cid,$forcedefault) = @_;
 9211:     if ($short =~ m{^cr/}) {
 9212: 	return (split('/',$short))[-1];
 9213:     }
 9214:     if (!defined($cid)) {
 9215:         $cid = $env{'request.course.id'};
 9216:     }
 9217:     my %rolenames = (
 9218:                       Course    => 'std',
 9219:                       Community => 'alt1',
 9220:                       Placement => 'std',
 9221:                     );
 9222:     if ($cid ne '') {
 9223:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9224:             unless ($forcedefault) {
 9225:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9226:                 &Apache::lonlocal::mt_escape(\$roletext);
 9227:                 return &Apache::lonlocal::mt($roletext);
 9228:             }
 9229:         }
 9230:     }
 9231:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9232:         (defined($rolenames{$type})) && 
 9233:         (defined($prp{$short}{$rolenames{$type}}))) {
 9234:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9235:     } elsif ($cid ne '') {
 9236:         my $crstype = $env{'course.'.$cid.'.type'};
 9237:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9238:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9239:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9240:         }
 9241:     }
 9242:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9243: }
 9244: 
 9245: # ----------------------------------------------------------------- Assign Role
 9246: 
 9247: sub assignrole {
 9248:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9249:         $context)=@_;
 9250:     my $mrole;
 9251:     if ($role =~ /^cr\//) {
 9252:         my $cwosec=$url;
 9253:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9254: 	unless (&allowed('ccr',$cwosec)) {
 9255:            my $refused = 1;
 9256:            if ($context eq 'requestcourses') {
 9257:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9258:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9259:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9260:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9261:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9262:                            if ($crsenv{'internal.courseowner'} eq
 9263:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9264:                                $refused = '';
 9265:                            }
 9266:                        }
 9267:                    }
 9268:                }
 9269:            }
 9270:            if ($refused) {
 9271:                &logthis('Refused custom assignrole: '.
 9272:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9273:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9274:                return 'refused';
 9275:            }
 9276:         }
 9277:         $mrole='cr';
 9278:     } elsif ($role =~ /^gr\//) {
 9279:         my $cwogrp=$url;
 9280:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9281:         unless (&allowed('mdg',$cwogrp)) {
 9282:             &logthis('Refused group assignrole: '.
 9283:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9284:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9285:             return 'refused';
 9286:         }
 9287:         $mrole='gr';
 9288:     } else {
 9289:         my $cwosec=$url;
 9290:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9291:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9292:             my $refused;
 9293:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9294:                 if (!(&allowed('c'.$role,$url))) {
 9295:                     $refused = 1;
 9296:                 }
 9297:             } else {
 9298:                 $refused = 1;
 9299:             }
 9300:             if ($refused) {
 9301:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9302:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9303:                     my %crsenv;
 9304:                     if ($role eq 'cc' || $role eq 'co') {
 9305:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9306:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9307:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9308:                                 if ($crsenv{'internal.courseowner'} eq 
 9309:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9310:                                     $refused = '';
 9311:                                 }
 9312:                             }
 9313:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9314:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9315:                                 if ($crsenv{'internal.courseowner'} eq 
 9316:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9317:                                     $refused = '';
 9318:                                 }
 9319:                             }
 9320:                         }
 9321:                     }
 9322:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9323:                     if ($role eq 'st') {
 9324:                         $refused = '';
 9325:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9326:                         $refused = '';
 9327:                     }
 9328:                 } elsif ($context eq 'requestcourses') {
 9329:                     my @possroles = ('st','ta','ep','in','cc','co');
 9330:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9331:                         my $wrongcc;
 9332:                         if ($cnum =~ /^$match_community$/) {
 9333:                             $wrongcc = 1 if ($role eq 'cc');
 9334:                         } else {
 9335:                             $wrongcc = 1 if ($role eq 'co');
 9336:                         }
 9337:                         unless ($wrongcc) {
 9338:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9339:                             if ($crsenv{'internal.courseowner'} eq 
 9340:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9341:                                 $refused = '';
 9342:                             }
 9343:                         }
 9344:                     }
 9345:                 } elsif ($context eq 'requestauthor') {
 9346:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9347:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9348:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9349:                             $refused = '';
 9350:                         } else {
 9351:                             my %domdefaults = &get_domain_defaults($udom);
 9352:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9353:                                 my $checkbystatus;
 9354:                                 if ($env{'user.adv'}) { 
 9355:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9356:                                     if ($disposition eq 'automatic') {
 9357:                                         $refused = '';
 9358:                                     } elsif ($disposition eq '') {
 9359:                                         $checkbystatus = 1;
 9360:                                     } 
 9361:                                 } else {
 9362:                                     $checkbystatus = 1;
 9363:                                 }
 9364:                                 if ($checkbystatus) {
 9365:                                     if ($env{'environment.inststatus'}) {
 9366:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9367:                                         foreach my $type (@inststatuses) {
 9368:                                             if (($type ne '') &&
 9369:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9370:                                                 $refused = '';
 9371:                                             }
 9372:                                         }
 9373:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9374:                                         $refused = '';
 9375:                                     }
 9376:                                 }
 9377:                             }
 9378:                         }
 9379:                     }
 9380:                 }
 9381:                 if ($refused) {
 9382:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9383:                              ' '.$role.' '.$end.' '.$start.' by '.
 9384: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9385:                     return 'refused';
 9386:                 }
 9387:             }
 9388:         } elsif ($role eq 'au') {
 9389:             if ($url ne '/'.$udom.'/') {
 9390:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9391:                          ' to assign author role for '.$uname.':'.$udom.
 9392:                          ' in domain: '.$url.' refused (wrong domain).');
 9393:                 return 'refused';
 9394:             }
 9395:         }
 9396:         $mrole=$role;
 9397:     }
 9398:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9399:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9400:     if ($end) { $command.='_'.$end; }
 9401:     if ($start) {
 9402: 	if ($end) { 
 9403:            $command.='_'.$start; 
 9404:         } else {
 9405:            $command.='_0_'.$start;
 9406:         }
 9407:     }
 9408:     my $origstart = $start;
 9409:     my $origend = $end;
 9410:     my $delflag;
 9411: # actually delete
 9412:     if ($deleteflag) {
 9413: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9414: # modify command to delete the role
 9415:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9416:                 "$udom:$uname:$url".'_'."$mrole";
 9417: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9418: # set start and finish to negative values for userrolelog
 9419:            $start=-1;
 9420:            $end=-1;
 9421:            $delflag = 1;
 9422:         }
 9423:     }
 9424: # send command
 9425:     my $answer=&reply($command,&homeserver($uname,$udom));
 9426: # log new user role if status is ok
 9427:     if ($answer eq 'ok') {
 9428: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9429:         if (($role eq 'cc') || ($role eq 'in') ||
 9430:             ($role eq 'ep') || ($role eq 'ad') ||
 9431:             ($role eq 'ta') || ($role eq 'st') ||
 9432:             ($role=~/^cr/) || ($role eq 'gr') ||
 9433:             ($role eq 'co')) {
 9434: # for course roles, perform group memberships changes triggered by role change.
 9435:             unless ($role =~ /^gr/) {
 9436:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9437:                                                  $origstart,$selfenroll,$context);
 9438:             }
 9439:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9440:                            $selfenroll,$context);
 9441:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9442:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9443:                  ($role eq 'da')) {
 9444:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9445:                            $context);
 9446:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9447:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9448:                              $context); 
 9449:         }
 9450:         if ($role eq 'cc') {
 9451:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9452:         }
 9453:     }
 9454:     return $answer;
 9455: }
 9456: 
 9457: sub autoupdate_coowners {
 9458:     my ($url,$end,$start,$uname,$udom) = @_;
 9459:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9460:     if (($cdom ne '') && ($cnum ne '')) {
 9461:         my $now = time;
 9462:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9463:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9464:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9465:             my $instcode = $coursehash{'internal.coursecode'};
 9466:             if ($instcode ne '') {
 9467:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9468:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9469:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9470:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9471:                         if ($result eq 'valid') {
 9472:                             if ($coursehash{'internal.co-owners'}) {
 9473:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9474:                                     push(@newcoowners,$coowner);
 9475:                                 }
 9476:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9477:                                     push(@newcoowners,$uname.':'.$udom);
 9478:                                 }
 9479:                                 @newcoowners = sort(@newcoowners);
 9480:                             } else {
 9481:                                 push(@newcoowners,$uname.':'.$udom);
 9482:                             }
 9483:                         } else {
 9484:                             if ($coursehash{'internal.co-owners'}) {
 9485:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9486:                                     unless ($coowner eq $uname.':'.$udom) {
 9487:                                         push(@newcoowners,$coowner);
 9488:                                     }
 9489:                                 }
 9490:                                 unless (@newcoowners > 0) {
 9491:                                     $delcoowners = 1;
 9492:                                     $coowners = '';
 9493:                                 }
 9494:                             }
 9495:                         }
 9496:                         if (@newcoowners || $delcoowners) {
 9497:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9498:                                             $delcoowners,@newcoowners);
 9499:                         }
 9500:                     }
 9501:                 }
 9502:             }
 9503:         }
 9504:     }
 9505: }
 9506: 
 9507: sub store_coowners {
 9508:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9509:     my $cid = $cdom.'_'.$cnum;
 9510:     my ($coowners,$delresult,$putresult);
 9511:     if (@newcoowners) {
 9512:         $coowners = join(',',@newcoowners);
 9513:         my %coownershash = (
 9514:                             'internal.co-owners' => $coowners,
 9515:                            );
 9516:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9517:         if ($putresult eq 'ok') {
 9518:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9519:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9520:             }
 9521:         }
 9522:     }
 9523:     if ($delcoowners) {
 9524:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9525:         if ($delresult eq 'ok') {
 9526:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9527:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9528:             }
 9529:         }
 9530:     }
 9531:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9532:         my %crsinfo =
 9533:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9534:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9535:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9536:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9537:         }
 9538:     }
 9539: }
 9540: 
 9541: # -------------------------------------------------- Modify user authentication
 9542: # Overrides without validation
 9543: 
 9544: sub modifyuserauth {
 9545:     my ($udom,$uname,$umode,$upass)=@_;
 9546:     my $uhome=&homeserver($uname,$udom);
 9547:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9548:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9549:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9550:              ' in domain '.$env{'request.role.domain'});  
 9551:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9552: 		     &escape($upass),$uhome);
 9553:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9554:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9555:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9556:     &log($udom,,$uname,$uhome,
 9557:         'Authentication changed by '.$env{'user.domain'}.', '.
 9558:                                      $env{'user.name'}.', '.$umode.
 9559:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9560:     unless ($reply eq 'ok') {
 9561:         &logthis('Authentication mode error: '.$reply);
 9562: 	return 'error: '.$reply;
 9563:     }   
 9564:     return 'ok';
 9565: }
 9566: 
 9567: # --------------------------------------------------------------- Modify a user
 9568: 
 9569: sub modifyuser {
 9570:     my ($udom,    $uname, $uid,
 9571:         $umode,   $upass, $first,
 9572:         $middle,  $last,  $gene,
 9573:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9574:     $udom= &LONCAPA::clean_domain($udom);
 9575:     $uname=&LONCAPA::clean_username($uname);
 9576:     my $showcandelete = 'none';
 9577:     if (ref($candelete) eq 'ARRAY') {
 9578:         if (@{$candelete} > 0) {
 9579:             $showcandelete = join(', ',@{$candelete});
 9580:         }
 9581:     }
 9582:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9583:              $umode.', '.$first.', '.$middle.', '.
 9584: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9585:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9586:                                      ' desiredhome not specified'). 
 9587:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9588:              ' in domain '.$env{'request.role.domain'});
 9589:     my $uhome=&homeserver($uname,$udom,'true');
 9590:     my $newuser;
 9591:     if ($uhome eq 'no_host') {
 9592:         $newuser = 1;
 9593:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
 9594:                 ($umode eq 'lti')) {
 9595:             return 'error: more information needed to create new user';
 9596:         }
 9597:     }
 9598: # ----------------------------------------------------------------- Create User
 9599:     if (($uhome eq 'no_host') && 
 9600: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
 9601:         my $unhome='';
 9602:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9603:             $unhome = $desiredhome;
 9604: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9605: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9606:         } else { # load balancing routine for determining $unhome
 9607:             my $loadm=10000000;
 9608: 	    my %servers = &get_servers($udom,'library');
 9609: 	    foreach my $tryserver (keys(%servers)) {
 9610: 		my $answer=reply('load',$tryserver);
 9611: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9612: 		    $loadm=$answer;
 9613: 		    $unhome=$tryserver;
 9614: 		}
 9615: 	    }
 9616:         }
 9617:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9618: 	    return 'error: unable to find a home server for '.$uname.
 9619:                    ' in domain '.$udom;
 9620:         }
 9621:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9622:                          &escape($upass),$unhome);
 9623: 	unless ($reply eq 'ok') {
 9624:             return 'error: '.$reply;
 9625:         }   
 9626:         $uhome=&homeserver($uname,$udom,'true');
 9627:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9628: 	    return 'error: unable verify users home machine.';
 9629:         }
 9630:     }   # End of creation of new user
 9631: # ---------------------------------------------------------------------- Add ID
 9632:     if ($uid) {
 9633:        $uid=~tr/A-Z/a-z/;
 9634:        my %uidhash=&idrget($udom,$uname);
 9635:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9636:          && (!$forceid)) {
 9637: 	  unless ($uid eq $uidhash{$uname}) {
 9638: 	      return 'error: user id "'.$uid.'" does not match '.
 9639:                   'current user id "'.$uidhash{$uname}.'".';
 9640:           }
 9641:        } else {
 9642: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9643:        }
 9644:     }
 9645: # -------------------------------------------------------------- Add names, etc
 9646:     my @tmp=&get('environment',
 9647: 		   ['firstname','middlename','lastname','generation','id',
 9648:                     'permanentemail','inststatus'],
 9649: 		   $udom,$uname);
 9650:     my (%names,%oldnames);
 9651:     if ($tmp[0] =~ m/^error:.*/) { 
 9652:         %names=(); 
 9653:     } else {
 9654:         %names = @tmp;
 9655:         %oldnames = %names;
 9656:     }
 9657: #
 9658: # If name, email and/or uid are blank (e.g., because an uploaded file
 9659: # of users did not contain them), do not overwrite existing values
 9660: # unless field is in $candelete array ref.  
 9661: #
 9662: 
 9663:     my @fields = ('firstname','middlename','lastname','generation',
 9664:                   'permanentemail','id');
 9665:     my %newvalues;
 9666:     if (ref($candelete) eq 'ARRAY') {
 9667:         foreach my $field (@fields) {
 9668:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9669:                 if ($field eq 'firstname') {
 9670:                     $names{$field} = $first;
 9671:                 } elsif ($field eq 'middlename') {
 9672:                     $names{$field} = $middle;
 9673:                 } elsif ($field eq 'lastname') {
 9674:                     $names{$field} = $last;
 9675:                 } elsif ($field eq 'generation') { 
 9676:                     $names{$field} = $gene;
 9677:                 } elsif ($field eq 'permanentemail') {
 9678:                     $names{$field} = $email;
 9679:                 } elsif ($field eq 'id') {
 9680:                     $names{$field}  = $uid;
 9681:                 }
 9682:             }
 9683:         }
 9684:     }
 9685:     if ($first)  { $names{'firstname'}  = $first; }
 9686:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9687:     if ($last)   { $names{'lastname'}   = $last; }
 9688:     if (defined($gene))   { $names{'generation'} = $gene; }
 9689:     if ($email) {
 9690:        $email=~s/[^\w\@\.\-\,]//gs;
 9691:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9692:     }
 9693:     if ($uid) { $names{'id'}  = $uid; }
 9694:     if (defined($inststatus)) {
 9695:         $names{'inststatus'} = '';
 9696:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9697:         if (ref($usertypes) eq 'HASH') {
 9698:             my @okstatuses; 
 9699:             foreach my $item (split(/:/,$inststatus)) {
 9700:                 if (defined($usertypes->{$item})) {
 9701:                     push(@okstatuses,$item);  
 9702:                 }
 9703:             }
 9704:             if (@okstatuses) {
 9705:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9706:             }
 9707:         }
 9708:     }
 9709:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9710:                  $umode.', '.$first.', '.$middle.', '.
 9711:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9712:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9713:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9714:     } else {
 9715:         $logmsg .= ' during self creation';
 9716:     }
 9717:     my $changed;
 9718:     if ($newuser) {
 9719:         $changed = 1;
 9720:     } else {
 9721:         foreach my $field (@fields) {
 9722:             if ($names{$field} ne $oldnames{$field}) {
 9723:                 $changed = 1;
 9724:                 last;
 9725:             }
 9726:         }
 9727:     }
 9728:     unless ($changed) {
 9729:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9730:         &logthis($logmsg);
 9731:         return 'ok';
 9732:     }
 9733:     my $reply = &put('environment', \%names, $udom,$uname);
 9734:     if ($reply ne 'ok') { 
 9735:         return 'error: '.$reply;
 9736:     }
 9737:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9738:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9739:     }
 9740:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9741:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9742:     $logmsg = 'Success modifying user '.$logmsg;
 9743:     &logthis($logmsg);
 9744:     return 'ok';
 9745: }
 9746: 
 9747: # -------------------------------------------------------------- Modify student
 9748: 
 9749: sub modifystudent {
 9750:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9751:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9752:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9753:     if (!$cid) {
 9754: 	unless ($cid=$env{'request.course.id'}) {
 9755: 	    return 'not_in_class';
 9756: 	}
 9757:     }
 9758: # --------------------------------------------------------------- Make the user
 9759:     my $reply=&modifyuser
 9760: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9761:          $desiredhome,$email,$inststatus);
 9762:     unless ($reply eq 'ok') { return $reply; }
 9763:     # This will cause &modify_student_enrollment to get the uid from the
 9764:     # student's environment
 9765:     $uid = undef if (!$forceid);
 9766:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9767:                                         $gene,$usec,$end,$start,$type,$locktype,
 9768:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9769:     return $reply;
 9770: }
 9771: 
 9772: sub modify_student_enrollment {
 9773:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9774:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9775:     my ($cdom,$cnum,$chome);
 9776:     if (!$cid) {
 9777: 	unless ($cid=$env{'request.course.id'}) {
 9778: 	    return 'not_in_class';
 9779: 	}
 9780: 	$cdom=$env{'course.'.$cid.'.domain'};
 9781: 	$cnum=$env{'course.'.$cid.'.num'};
 9782:     } else {
 9783: 	($cdom,$cnum)=split(/_/,$cid);
 9784:     }
 9785:     $chome=$env{'course.'.$cid.'.home'};
 9786:     if (!$chome) {
 9787: 	$chome=&homeserver($cnum,$cdom);
 9788:     }
 9789:     if (!$chome) { return 'unknown_course'; }
 9790:     # Make sure the user exists
 9791:     my $uhome=&homeserver($uname,$udom);
 9792:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9793: 	return 'error: no such user';
 9794:     }
 9795:     # Get student data if we were not given enough information
 9796:     if (!defined($first)  || $first  eq '' || 
 9797:         !defined($last)   || $last   eq '' || 
 9798:         !defined($uid)    || $uid    eq '' || 
 9799:         !defined($middle) || $middle eq '' || 
 9800:         !defined($gene)   || $gene   eq '') {
 9801:         # They did not supply us with enough data to enroll the student, so
 9802:         # we need to pick up more information.
 9803:         my %tmp = &get('environment',
 9804:                        ['firstname','middlename','lastname', 'generation','id']
 9805:                        ,$udom,$uname);
 9806: 
 9807:         #foreach my $key (keys(%tmp)) {
 9808:         #    &logthis("key $key = ".$tmp{$key});
 9809:         #}
 9810:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9811:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9812:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9813:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9814:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9815:     }
 9816:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9817:     my $user = "$uname:$udom";
 9818:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9819:     my $reply=cput('classlist',
 9820: 		   {$user => 
 9821: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9822: 		   $cdom,$cnum);
 9823:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9824:         &devalidate_getsection_cache($udom,$uname,$cid);
 9825:     } else { 
 9826: 	return 'error: '.$reply;
 9827:     }
 9828:     # Add student role to user
 9829:     my $uurl='/'.$cid;
 9830:     $uurl=~s/\_/\//g;
 9831:     if ($usec) {
 9832: 	$uurl.='/'.$usec;
 9833:     }
 9834:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9835:                              $selfenroll,$context);
 9836:     if ($result ne 'ok') {
 9837:         if ($old_entry{$user} ne '') {
 9838:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9839:         } else {
 9840:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9841:         }
 9842:     }
 9843:     return $result; 
 9844: }
 9845: 
 9846: sub format_name {
 9847:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9848:     my $name;
 9849:     if ($first ne 'lastname') {
 9850: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9851:     } else {
 9852: 	if ($lastname=~/\S/) {
 9853: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9854: 	    $name=~s/\s+,/,/;
 9855: 	} else {
 9856: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9857: 	}
 9858:     }
 9859:     $name=~s/^\s+//;
 9860:     $name=~s/\s+$//;
 9861:     $name=~s/\s+/ /g;
 9862:     return $name;
 9863: }
 9864: 
 9865: # ------------------------------------------------- Write to course preferences
 9866: 
 9867: sub writecoursepref {
 9868:     my ($courseid,%prefs)=@_;
 9869:     $courseid=~s/^\///;
 9870:     $courseid=~s/\_/\//g;
 9871:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9872:     my $chome=homeserver($cnum,$cdomain);
 9873:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9874: 	return 'error: no such course';
 9875:     }
 9876:     my $cstring='';
 9877:     foreach my $pref (keys(%prefs)) {
 9878: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9879:     }
 9880:     $cstring=~s/\&$//;
 9881:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9882: }
 9883: 
 9884: # ---------------------------------------------------------- Make/modify course
 9885: 
 9886: sub createcourse {
 9887:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9888:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9889:     $url=&declutter($url);
 9890:     my $cid='';
 9891:     if ($context eq 'requestcourses') {
 9892:         my $can_create = 0;
 9893:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9894:         if ($udom eq $ownerdom) {
 9895:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9896:                                   $context)) {
 9897:                 $can_create = 1;
 9898:             }
 9899:         } else {
 9900:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9901:                                            $category);
 9902:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9903:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9904:                 if (@curr > 0) {
 9905:                     my @options = qw(approval validate autolimit);
 9906:                     my $optregex = join('|',@options);
 9907:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9908:                         $can_create = 1;
 9909:                     }
 9910:                 }
 9911:             }
 9912:         }
 9913:         if ($can_create) {
 9914:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 9915:                 unless (&allowed('ccc',$udom)) {
 9916:                     return 'refused'; 
 9917:                 }
 9918:             }
 9919:         } else {
 9920:             return 'refused';
 9921:         }
 9922:     } elsif (!&allowed('ccc',$udom)) {
 9923:         return 'refused';
 9924:     }
 9925: # --------------------------------------------------------------- Get Unique ID
 9926:     my $uname;
 9927:     if ($cnum =~ /^$match_courseid$/) {
 9928:         my $chome=&homeserver($cnum,$udom,'true');
 9929:         if (($chome eq '') || ($chome eq 'no_host')) {
 9930:             $uname = $cnum;
 9931:         } else {
 9932:             $uname = &generate_coursenum($udom,$crstype);
 9933:         }
 9934:     } else {
 9935:         $uname = &generate_coursenum($udom,$crstype);
 9936:     }
 9937:     return $uname if ($uname =~ /^error/);
 9938: # -------------------------------------------------- Check supplied server name
 9939:     if (!defined($course_server)) {
 9940:         if (defined(&domain($udom,'primary'))) {
 9941:             $course_server = &domain($udom,'primary');
 9942:         } else {
 9943:             $course_server = $env{'user.home'}; 
 9944:         }
 9945:     }
 9946:     my %host_servers =
 9947:         &Apache::lonnet::get_servers($udom,'library');
 9948:     unless ($host_servers{$course_server}) {
 9949:         return 'error: invalid home server for course: '.$course_server;
 9950:     }
 9951: # ------------------------------------------------------------- Make the course
 9952:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 9953:                       $course_server);
 9954:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 9955:     my $uhome=&homeserver($uname,$udom,'true');
 9956:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9957: 	return 'error: no such course';
 9958:     }
 9959: # ----------------------------------------------------------------- Course made
 9960: # log existence
 9961:     my $now = time;
 9962:     my $newcourse = {
 9963:                     $udom.'_'.$uname => {
 9964:                                      description => $description,
 9965:                                      inst_code   => $inst_code,
 9966:                                      owner       => $course_owner,
 9967:                                      type        => $crstype,
 9968:                                      creator     => $env{'user.name'}.':'.
 9969:                                                     $env{'user.domain'},
 9970:                                      created     => $now,
 9971:                                      context     => $context,
 9972:                                                 },
 9973:                     };
 9974:     &courseidput($udom,$newcourse,$uhome,'notime');
 9975: # set toplevel url
 9976:     my $topurl=$url;
 9977:     unless ($nonstandard) {
 9978: # ------------------------------------------ For standard courses, make top url
 9979:         my $mapurl=&clutter($url);
 9980:         if ($mapurl eq '/res/') { $mapurl=''; }
 9981:         $env{'form.initmap'}=(<<ENDINITMAP);
 9982: <map>
 9983: <resource id="1" type="start"></resource>
 9984: <resource id="2" src="$mapurl"></resource>
 9985: <resource id="3" type="finish"></resource>
 9986: <link index="1" from="1" to="2"></link>
 9987: <link index="2" from="2" to="3"></link>
 9988: </map>
 9989: ENDINITMAP
 9990:         $topurl=&declutter(
 9991:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 9992:                           );
 9993:     }
 9994: # ----------------------------------------------------------- Write preferences
 9995:     &writecoursepref($udom.'_'.$uname,
 9996:                      ('description'              => $description,
 9997:                       'url'                      => $topurl,
 9998:                       'internal.creator'         => $env{'user.name'}.':'.
 9999:                                                     $env{'user.domain'},
10000:                       'internal.created'         => $now,
10001:                       'internal.creationcontext' => $context)
10002:                     );
10003:     return '/'.$udom.'/'.$uname;
10004: }
10005: 
10006: # ------------------------------------------------------------------- Create ID
10007: sub generate_coursenum {
10008:     my ($udom,$crstype) = @_;
10009:     my $domdesc = &domain($udom);
10010:     return 'error: invalid domain' if ($domdesc eq '');
10011:     my $first;
10012:     if ($crstype eq 'Community') {
10013:         $first = '0';
10014:     } else {
10015:         $first = int(1+rand(9)); 
10016:     } 
10017:     my $uname=$first.
10018:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10019:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10020:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10021: # ----------------------------------------------- Make sure that does not exist
10022:     my $uhome=&homeserver($uname,$udom,'true');
10023:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10024:         if ($crstype eq 'Community') {
10025:             $first = '0';
10026:         } else {
10027:             $first = int(1+rand(9));
10028:         }
10029:         $uname=$first.
10030:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10031:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10032:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10033:         $uhome=&homeserver($uname,$udom,'true');
10034:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10035:             return 'error: unable to generate unique course-ID';
10036:         }
10037:     }
10038:     return $uname;
10039: }
10040: 
10041: sub is_course {
10042:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10043:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10044: 
10045:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10046:     my $uhome=&homeserver($cnum,$cdom);
10047:     my $iscourse;
10048:     if (grep { $_ eq $uhome } current_machine_ids()) {
10049:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10050:     } else {
10051:         my $hashid = $cdom.':'.$cnum;
10052:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10053:         unless (defined($cached)) {
10054:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10055:                                         $cnum,undef,undef,'.');
10056:             $iscourse = 0;
10057:             if (exists($courses{$cdom.'_'.$cnum})) {
10058:                 $iscourse = 1;
10059:             }
10060:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10061:         }
10062:     }
10063:     return unless ($iscourse);
10064:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10065: }
10066: 
10067: sub store_userdata {
10068:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10069:     my $result;
10070:     if ($datakey ne '') {
10071:         if (ref($storehash) eq 'HASH') {
10072:             if ($udom eq '' || $uname eq '') {
10073:                 $udom = $env{'user.domain'};
10074:                 $uname = $env{'user.name'};
10075:             }
10076:             my $uhome=&homeserver($uname,$udom);
10077:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10078:                 $result = 'error: no_host';
10079:             } else {
10080:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10081:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10082: 
10083:                 my $namevalue='';
10084:                 foreach my $key (keys(%{$storehash})) {
10085:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10086:                 }
10087:                 $namevalue=~s/\&$//;
10088:                 unless ($namespace eq 'courserequests') {
10089:                     $datakey = &escape($datakey);
10090:                 }
10091:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10092:                                   $namevalue,$uhome);
10093:             }
10094:         } else {
10095:             $result = 'error: data to store was not a hash reference'; 
10096:         }
10097:     } else {
10098:         $result= 'error: invalid requestkey'; 
10099:     }
10100:     return $result;
10101: }
10102: 
10103: # ---------------------------------------------------------- Assign Custom Role
10104: 
10105: sub assigncustomrole {
10106:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10107:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10108:                        $end,$start,$deleteflag,$selfenroll,$context);
10109: }
10110: 
10111: # ----------------------------------------------------------------- Revoke Role
10112: 
10113: sub revokerole {
10114:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10115:     my $now=time;
10116:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10117: }
10118: 
10119: # ---------------------------------------------------------- Revoke Custom Role
10120: 
10121: sub revokecustomrole {
10122:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10123:     my $now=time;
10124:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10125:            $deleteflag,$selfenroll,$context);
10126: }
10127: 
10128: # ------------------------------------------------------------ Disk usage
10129: sub diskusage {
10130:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10131:     $directorypath =~ s/\/$//;
10132:     my $listing=&reply('du2:'.&escape($directorypath).':'
10133:                        .&escape($getpropath).':'.&escape($uname).':'
10134:                        .&escape($udom),homeserver($uname,$udom));
10135:     if ($listing eq 'unknown_cmd') {
10136:         if ($getpropath) {
10137:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10138:         }
10139:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10140:     }
10141:     return $listing;
10142: }
10143: 
10144: sub is_locked {
10145:     my ($file_name, $domain, $user, $which) = @_;
10146:     my @check;
10147:     my $is_locked;
10148:     push (@check,$file_name);
10149:     my %locked = &get('file_permissions',\@check,
10150: 		      $env{'user.domain'},$env{'user.name'});
10151:     my ($tmp)=keys(%locked);
10152:     if ($tmp=~/^error:/) { undef(%locked); }
10153:     
10154:     if (ref($locked{$file_name}) eq 'ARRAY') {
10155:         $is_locked = 'false';
10156:         foreach my $entry (@{$locked{$file_name}}) {
10157:            if (ref($entry) eq 'ARRAY') {
10158:                $is_locked = 'true';
10159:                if (ref($which) eq 'ARRAY') {
10160:                    push(@{$which},$entry);
10161:                } else {
10162:                    last;
10163:                }
10164:            }
10165:        }
10166:     } else {
10167:         $is_locked = 'false';
10168:     }
10169:     return $is_locked;
10170: }
10171: 
10172: sub declutter_portfile {
10173:     my ($file) = @_;
10174:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10175:     return $file;
10176: }
10177: 
10178: # ------------------------------------------------------------- Mark as Read Only
10179: 
10180: sub mark_as_readonly {
10181:     my ($domain,$user,$files,$what) = @_;
10182:     my %current_permissions = &dump('file_permissions',$domain,$user);
10183:     my ($tmp)=keys(%current_permissions);
10184:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10185:     foreach my $file (@{$files}) {
10186: 	$file = &declutter_portfile($file);
10187:         push(@{$current_permissions{$file}},$what);
10188:     }
10189:     &put('file_permissions',\%current_permissions,$domain,$user);
10190:     return;
10191: }
10192: 
10193: # ------------------------------------------------------------Save Selected Files
10194: 
10195: sub save_selected_files {
10196:     my ($user, $path, @files) = @_;
10197:     my $filename = $user."savedfiles";
10198:     my @other_files = &files_not_in_path($user, $path);
10199:     open (OUT,'>',LONCAPA::tempdir().$filename);
10200:     foreach my $file (@files) {
10201:         print (OUT $env{'form.currentpath'}.$file."\n");
10202:     }
10203:     foreach my $file (@other_files) {
10204:         print (OUT $file."\n");
10205:     }
10206:     close (OUT);
10207:     return 'ok';
10208: }
10209: 
10210: sub clear_selected_files {
10211:     my ($user) = @_;
10212:     my $filename = $user."savedfiles";
10213:     open (OUT,'>',LONCAPA::tempdir().$filename);
10214:     print (OUT undef);
10215:     close (OUT);
10216:     return ("ok");    
10217: }
10218: 
10219: sub files_in_path {
10220:     my ($user, $path) = @_;
10221:     my $filename = $user."savedfiles";
10222:     my %return_files;
10223:     open (IN,'<',LONCAPA::tempdir().$filename);
10224:     while (my $line_in = <IN>) {
10225:         chomp ($line_in);
10226:         my @paths_and_file = split (m!/!, $line_in);
10227:         my $file_part = pop (@paths_and_file);
10228:         my $path_part = join ('/', @paths_and_file);
10229:         $path_part.='/';
10230:         my $path_and_file = $path_part.$file_part;
10231:         if ($path_part eq $path) {
10232:             $return_files{$file_part}= 'selected';
10233:         }
10234:     }
10235:     close (IN);
10236:     return (\%return_files);
10237: }
10238: 
10239: # called in portfolio select mode, to show files selected NOT in current directory
10240: sub files_not_in_path {
10241:     my ($user, $path) = @_;
10242:     my $filename = $user."savedfiles";
10243:     my @return_files;
10244:     my $path_part;
10245:     open(IN, '<',LONCAPA::tempdir().$filename);
10246:     while (my $line = <IN>) {
10247:         #ok, I know it's clunky, but I want it to work
10248:         my @paths_and_file = split(m|/|, $line);
10249:         my $file_part = pop(@paths_and_file);
10250:         chomp($file_part);
10251:         my $path_part = join('/', @paths_and_file);
10252:         $path_part .= '/';
10253:         my $path_and_file = $path_part.$file_part;
10254:         if ($path_part ne $path) {
10255:             push(@return_files, ($path_and_file));
10256:         }
10257:     }
10258:     close(OUT);
10259:     return (@return_files);
10260: }
10261: 
10262: #------------------------------Submitted/Handedback Portfolio Files Versioning
10263:  
10264: sub portfiles_versioning {
10265:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10266:     my $portfolio_root = '/userfiles/portfolio';
10267:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10268:     foreach my $file (@{$portfiles}) {
10269:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10270:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10271:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10272:         my $getpropath = 1;
10273:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10274:                                              $stu_name,$getpropath);
10275:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10276:         my $new_answer = 
10277:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10278:         if ($new_answer ne 'problem getting file') {
10279:             push(@{$versioned_portfiles}, $directory.$new_answer);
10280:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10281:                               [$symb,$env{'request.course.id'},'graded']);
10282:         }
10283:     }
10284: }
10285: 
10286: sub get_next_version {
10287:     my ($answer_name, $answer_ext, $dir_list) = @_;
10288:     my $version;
10289:     if (ref($dir_list) eq 'ARRAY') {
10290:         foreach my $row (@{$dir_list}) {
10291:             my ($file) = split(/\&/,$row,2);
10292:             my ($file_name,$file_version,$file_ext) =
10293:                 &file_name_version_ext($file);
10294:             if (($file_name eq $answer_name) &&
10295:                 ($file_ext eq $answer_ext)) {
10296:                      # gets here if filename and extension match,
10297:                      # regardless of version
10298:                 if ($file_version ne '') {
10299:                     # a versioned file is found  so save it for later
10300:                     if ($file_version > $version) {
10301:                         $version = $file_version;
10302:                     }
10303:                 }
10304:             }
10305:         }
10306:     }
10307:     $version ++;
10308:     return($version);
10309: }
10310: 
10311: sub version_selected_portfile {
10312:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10313:     my ($answer_name,$answer_ver,$answer_ext) =
10314:         &file_name_version_ext($file_name);
10315:     my $new_answer;
10316:     $env{'form.copy'} =
10317:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10318:     if($env{'form.copy'} eq '-1') {
10319:         $new_answer = 'problem getting file';
10320:     } else {
10321:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10322:         my $copy_result = 
10323:             &finishuserfileupload($stu_name,$domain,'copy',
10324:                                   '/portfolio'.$directory.$new_answer);
10325:     }
10326:     undef($env{'form.copy'});
10327:     return ($new_answer);
10328: }
10329: 
10330: sub file_name_version_ext {
10331:     my ($file)=@_;
10332:     my @file_parts = split(/\./, $file);
10333:     my ($name,$version,$ext);
10334:     if (@file_parts > 1) {
10335:         $ext=pop(@file_parts);
10336:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10337:             $version=pop(@file_parts);
10338:         }
10339:         $name=join('.',@file_parts);
10340:     } else {
10341:         $name=join('.',@file_parts);
10342:     }
10343:     return($name,$version,$ext);
10344: }
10345: 
10346: #----------------------------------------------Get portfolio file permissions
10347: 
10348: sub get_portfile_permissions {
10349:     my ($domain,$user) = @_;
10350:     my %current_permissions = &dump('file_permissions',$domain,$user);
10351:     my ($tmp)=keys(%current_permissions);
10352:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10353:     return \%current_permissions;
10354: }
10355: 
10356: #---------------------------------------------Get portfolio file access controls
10357: 
10358: sub get_access_controls {
10359:     my ($current_permissions,$group,$file) = @_;
10360:     my %access;
10361:     my $real_file = $file;
10362:     $file =~ s/\.meta$//;
10363:     if (defined($file)) {
10364:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10365:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10366:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10367:             }
10368:         }
10369:     } else {
10370:         foreach my $key (keys(%{$current_permissions})) {
10371:             if ($key =~ /\0accesscontrol$/) {
10372:                 if (defined($group)) {
10373:                     if ($key !~ m-^\Q$group\E/-) {
10374:                         next;
10375:                     }
10376:                 }
10377:                 my ($fullpath) = split(/\0/,$key);
10378:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10379:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10380:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10381:                     }
10382:                 }
10383:             }
10384:         }
10385:     }
10386:     return %access;
10387: }
10388: 
10389: sub modify_access_controls {
10390:     my ($file_name,$changes,$domain,$user)=@_;
10391:     my ($outcome,$deloutcome);
10392:     my %store_permissions;
10393:     my %new_values;
10394:     my %new_control;
10395:     my %translation;
10396:     my @deletions = ();
10397:     my $now = time;
10398:     if (exists($$changes{'activate'})) {
10399:         if (ref($$changes{'activate'}) eq 'HASH') {
10400:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10401:             my $numnew = scalar(@newitems);
10402:             for (my $i=0; $i<$numnew; $i++) {
10403:                 my $newkey = $newitems[$i];
10404:                 my $newid = &Apache::loncommon::get_cgi_id();
10405:                 if ($newkey =~ /^\d+:/) { 
10406:                     $newkey =~ s/^(\d+)/$newid/;
10407:                     $translation{$1} = $newid;
10408:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10409:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10410:                     $translation{$1} = $newid;
10411:                 }
10412:                 $new_values{$file_name."\0".$newkey} = 
10413:                                           $$changes{'activate'}{$newitems[$i]};
10414:                 $new_control{$newkey} = $now;
10415:             }
10416:         }
10417:     }
10418:     my %todelete;
10419:     my %changed_items;
10420:     foreach my $action ('delete','update') {
10421:         if (exists($$changes{$action})) {
10422:             if (ref($$changes{$action}) eq 'HASH') {
10423:                 foreach my $key (keys(%{$$changes{$action}})) {
10424:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10425:                     if ($action eq 'delete') { 
10426:                         $todelete{$itemnum} = 1;
10427:                     } else {
10428:                         $changed_items{$itemnum} = $key;
10429:                     }
10430:                 }
10431:             }
10432:         }
10433:     }
10434:     # get lock on access controls for file.
10435:     my $lockhash = {
10436:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10437:                                                        ':'.$env{'user.domain'},
10438:                    }; 
10439:     my $tries = 0;
10440:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10441:    
10442:     while (($gotlock ne 'ok') && $tries < 10) {
10443:         $tries ++;
10444:         sleep(0.1);
10445:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10446:     }
10447:     if ($gotlock eq 'ok') {
10448:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10449:         my ($tmp)=keys(%curr_permissions);
10450:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10451:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10452:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10453:             if (ref($curr_controls) eq 'HASH') {
10454:                 foreach my $control_item (keys(%{$curr_controls})) {
10455:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10456:                     if (defined($todelete{$itemnum})) {
10457:                         push(@deletions,$file_name."\0".$control_item);
10458:                     } else {
10459:                         if (defined($changed_items{$itemnum})) {
10460:                             $new_control{$changed_items{$itemnum}} = $now;
10461:                             push(@deletions,$file_name."\0".$control_item);
10462:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10463:                         } else {
10464:                             $new_control{$control_item} = $$curr_controls{$control_item};
10465:                         }
10466:                     }
10467:                 }
10468:             }
10469:         }
10470:         my ($group);
10471:         if (&is_course($domain,$user)) {
10472:             ($group,my $file) = split(/\//,$file_name,2);
10473:         }
10474:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10475:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10476:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10477:         #  remove lock
10478:         my @del_lock = ($file_name."\0".'locked_access_records');
10479:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10480:         my $sqlresult =
10481:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10482:                                     $group);
10483:     } else {
10484:         $outcome = "error: could not obtain lockfile\n";  
10485:     }
10486:     return ($outcome,$deloutcome,\%new_values,\%translation);
10487: }
10488: 
10489: sub make_public_indefinitely {
10490:     my (@requrl) = @_;
10491:     return &automated_portfile_access('public',\@requrl);
10492: }
10493: 
10494: sub automated_portfile_access {
10495:     my ($accesstype,$addsref,$delsref,$info) = @_;
10496:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10497:         return 'invalid';
10498:     }
10499:     my %urls;
10500:     if (ref($addsref) eq 'ARRAY') {
10501:         foreach my $requrl (@{$addsref}) {
10502:             if (&is_portfolio_url($requrl)) {
10503:                 unless (exists($urls{$requrl})) {
10504:                     $urls{$requrl} = 'add';
10505:                 }
10506:             }
10507:         }
10508:     }
10509:     if (ref($delsref) eq 'ARRAY') {
10510:         foreach my $requrl (@{$delsref}) { 
10511:             if (&is_portfolio_url($requrl)) {
10512:                 unless (exists($urls{$requrl})) {
10513:                     $urls{$requrl} = 'delete'; 
10514:                 }
10515:             }
10516:         }
10517:     }
10518:     unless (keys(%urls)) {
10519:         return 'invalid';
10520:     }
10521:     my $ip;
10522:     if ($accesstype eq 'ip') {
10523:         if (ref($info) eq 'HASH') {
10524:             if ($info->{'ip'} ne '') {
10525:                 $ip = $info->{'ip'};
10526:             }
10527:         }
10528:         if ($ip eq '') {
10529:             return 'invalid';
10530:         }
10531:     }
10532:     my $errors;
10533:     my $now = time;
10534:     my %current_perms;
10535:     foreach my $requrl (sort(keys(%urls))) {
10536:         my $action;
10537:         if ($urls{$requrl} eq 'add') {
10538:             $action = 'activate';
10539:         } else {
10540:             $action = 'none';
10541:         }
10542:         my $aclnum = 0;
10543:         my (undef,$udom,$unum,$file_name,$group) =
10544:             &parse_portfolio_url($requrl);
10545:         unless (exists($current_perms{$unum.':'.$udom})) {
10546:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10547:         }
10548:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10549:                                                    $group,$file_name);
10550:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10551:             my ($num,$scope,$end,$start) = 
10552:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10553:             if ($scope eq $accesstype) {
10554:                 if (($start <= $now) && ($end == 0)) {
10555:                     if ($accesstype eq 'ip') {
10556:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10557:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10558:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10559:                                     if ($urls{$requrl} eq 'add') {
10560:                                         $action = 'none';
10561:                                         last;
10562:                                     } else {
10563:                                         $action = 'delete';
10564:                                         $aclnum = $num;
10565:                                         last;
10566:                                     }
10567:                                 }
10568:                             }
10569:                         }
10570:                     } elsif ($accesstype eq 'public') {
10571:                         if ($urls{$requrl} eq 'add') {
10572:                             $action = 'none';
10573:                             last;
10574:                         } else {
10575:                             $action = 'delete';
10576:                             $aclnum = $num;
10577:                             last;
10578:                         }
10579:                     }
10580:                 } elsif ($accesstype eq 'public') {
10581:                     $action = 'update';
10582:                     $aclnum = $num;
10583:                     last;
10584:                 }
10585:             }
10586:         }
10587:         if ($action eq 'none') {
10588:             next;
10589:         } else {
10590:             my %changes;
10591:             my $newend = 0;
10592:             my $newstart = $now;
10593:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10594:             $changes{$action}{$newkey} = {
10595:                 type => $accesstype,
10596:                 time => {
10597:                     start => $newstart,
10598:                     end   => $newend,
10599:                 },
10600:             };
10601:             if ($accesstype eq 'ip') {
10602:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10603:             }
10604:             my ($outcome,$deloutcome,$new_values,$translation) =
10605:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10606:             unless ($outcome eq 'ok') {
10607:                 $errors .= $outcome.' ';
10608:             }
10609:         }
10610:     }
10611:     if ($errors) {
10612:         $errors =~ s/\s$//;
10613:         return $errors;
10614:     } else {
10615:         return 'ok';
10616:     }
10617: }
10618: 
10619: #------------------------------------------------------Get Marked as Read Only
10620: 
10621: sub get_marked_as_readonly {
10622:     my ($domain,$user,$what,$group) = @_;
10623:     my $current_permissions = &get_portfile_permissions($domain,$user);
10624:     my @readonly_files;
10625:     my $cmp1=$what;
10626:     if (ref($what)) { $cmp1=join('',@{$what}) };
10627:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10628:         if (defined($group)) {
10629:             if ($file_name !~ m-^\Q$group\E/-) {
10630:                 next;
10631:             }
10632:         }
10633:         if (ref($value) eq "ARRAY"){
10634:             foreach my $stored_what (@{$value}) {
10635:                 my $cmp2=$stored_what;
10636:                 if (ref($stored_what) eq 'ARRAY') {
10637:                     $cmp2=join('',@{$stored_what});
10638:                 }
10639:                 if ($cmp1 eq $cmp2) {
10640:                     push(@readonly_files, $file_name);
10641:                     last;
10642:                 } elsif (!defined($what)) {
10643:                     push(@readonly_files, $file_name);
10644:                     last;
10645:                 }
10646:             }
10647:         }
10648:     }
10649:     return @readonly_files;
10650: }
10651: #-----------------------------------------------------------Get Marked as Read Only Hash
10652: 
10653: sub get_marked_as_readonly_hash {
10654:     my ($current_permissions,$group,$what) = @_;
10655:     my %readonly_files;
10656:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10657:         if (defined($group)) {
10658:             if ($file_name !~ m-^\Q$group\E/-) {
10659:                 next;
10660:             }
10661:         }
10662:         if (ref($value) eq "ARRAY"){
10663:             foreach my $stored_what (@{$value}) {
10664:                 if (ref($stored_what) eq 'ARRAY') {
10665:                     foreach my $lock_descriptor(@{$stored_what}) {
10666:                         if ($lock_descriptor eq 'graded') {
10667:                             $readonly_files{$file_name} = 'graded';
10668:                         } elsif ($lock_descriptor eq 'handback') {
10669:                             $readonly_files{$file_name} = 'handback';
10670:                         } else {
10671:                             if (!exists($readonly_files{$file_name})) {
10672:                                 $readonly_files{$file_name} = 'locked';
10673:                             }
10674:                         }
10675:                     }
10676:                 } 
10677:             }
10678:         } 
10679:     }
10680:     return %readonly_files;
10681: }
10682: # ------------------------------------------------------------ Unmark as Read Only
10683: 
10684: sub unmark_as_readonly {
10685:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10686:     # for portfolio submissions, $what contains [$symb,$crsid] 
10687:     my ($domain,$user,$what,$file_name,$group) = @_;
10688:     $file_name = &declutter_portfile($file_name);
10689:     my $symb_crs = $what;
10690:     if (ref($what)) { $symb_crs=join('',@$what); }
10691:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10692:     my ($tmp)=keys(%current_permissions);
10693:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10694:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10695:     foreach my $file (@readonly_files) {
10696: 	my $clean_file = &declutter_portfile($file);
10697: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10698: 	my $current_locks = $current_permissions{$file};
10699:         my @new_locks;
10700:         my @del_keys;
10701:         if (ref($current_locks) eq "ARRAY"){
10702:             foreach my $locker (@{$current_locks}) {
10703:                 my $compare=$locker;
10704:                 if (ref($locker) eq 'ARRAY') {
10705:                     $compare=join('',@{$locker});
10706:                     if ($compare ne $symb_crs) {
10707:                         push(@new_locks, $locker);
10708:                     }
10709:                 }
10710:             }
10711:             if (scalar(@new_locks) > 0) {
10712:                 $current_permissions{$file} = \@new_locks;
10713:             } else {
10714:                 push(@del_keys, $file);
10715:                 &del('file_permissions',\@del_keys, $domain, $user);
10716:                 delete($current_permissions{$file});
10717:             }
10718:         }
10719:     }
10720:     &put('file_permissions',\%current_permissions,$domain,$user);
10721:     return;
10722: }
10723: 
10724: # ------------------------------------------------------------ Directory lister
10725: 
10726: sub dirlist {
10727:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10728:     $uri=~s/^\///;
10729:     $uri=~s/\/$//;
10730:     my ($udom, $uname);
10731:     if ($getuserdir) {
10732:         $udom = $userdomain;
10733:         $uname = $username;
10734:     } else {
10735:         (undef,$udom,$uname)=split(/\//,$uri);
10736:         if(defined($userdomain)) {
10737:             $udom = $userdomain;
10738:         }
10739:         if(defined($username)) {
10740:             $uname = $username;
10741:         }
10742:     }
10743:     my ($dirRoot,$listing,@listing_results);
10744: 
10745:     $dirRoot = $perlvar{'lonDocRoot'};
10746:     if (defined($getpropath)) {
10747:         $dirRoot = &propath($udom,$uname);
10748:         $dirRoot =~ s/\/$//;
10749:     } elsif (defined($getuserdir)) {
10750:         my $subdir=$uname.'__';
10751:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10752:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10753:                    ."/$udom/$subdir/$uname";
10754:     } elsif (defined($alternateRoot)) {
10755:         $dirRoot = $alternateRoot;
10756:     }
10757: 
10758:     if($udom) {
10759:         if($uname) {
10760:             my $uhome = &homeserver($uname,$udom);
10761:             if ($uhome eq 'no_host') {
10762:                 return ([],'no_host');
10763:             }
10764:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10765:                               .$getuserdir.':'.&escape($dirRoot)
10766:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10767:             if ($listing eq 'unknown_cmd') {
10768:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10769:             } else {
10770:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10771:             }
10772:             if ($listing eq 'unknown_cmd') {
10773:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10774:                 @listing_results = split(/:/,$listing);
10775:             } else {
10776:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10777:             }
10778:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10779:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10780:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10781:                 return ([],$listing);
10782:             } else {
10783:                 return (\@listing_results);
10784:             }
10785:         } elsif(!$alternateRoot) {
10786:             my (%allusers,%listerror);
10787: 	    my %servers = &get_servers($udom,'library');
10788:  	    foreach my $tryserver (keys(%servers)) {
10789:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10790:                                   &escape($udom),$tryserver);
10791:                 if ($listing eq 'unknown_cmd') {
10792: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10793: 				      $udom, $tryserver);
10794:                 } else {
10795:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10796:                 }
10797: 		if ($listing eq 'unknown_cmd') {
10798: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10799: 				      $udom, $tryserver);
10800: 		    @listing_results = split(/:/,$listing);
10801: 		} else {
10802: 		    @listing_results =
10803: 			map { &unescape($_); } split(/:/,$listing);
10804: 		}
10805:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10806:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10807:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10808:                     $listerror{$tryserver} = $listing;
10809:                 } else {
10810: 		    foreach my $line (@listing_results) {
10811: 			my ($entry) = split(/&/,$line,2);
10812: 			$allusers{$entry} = 1;
10813: 		    }
10814: 		}
10815:             }
10816:             my @alluserslist=();
10817:             foreach my $user (sort(keys(%allusers))) {
10818:                 push(@alluserslist,$user.'&user');
10819:             }
10820: 
10821:             if (!%listerror) {
10822:                 # no errors
10823:                 return (\@alluserslist);
10824:             } elsif (scalar(keys(%servers)) == 1) {
10825:                 # one library server, one error 
10826:                 my ($key) = keys(%listerror);
10827:                 return (\@alluserslist, $listerror{$key});
10828:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10829:                 # con_lost indicates that we might miss data from at least one
10830:                 # library server
10831:                 return (\@alluserslist, 'con_lost');
10832:             } else {
10833:                 # multiple library servers and no con_lost -> data should be
10834:                 # complete. 
10835:                 return (\@alluserslist);
10836:             }
10837: 
10838:         } else {
10839:             return ([],'missing username');
10840:         }
10841:     } elsif(!defined($getpropath)) {
10842:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10843:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10844:         return (\@all_domains);
10845:     } else {
10846:         return ([],'missing domain');
10847:     }
10848: }
10849: 
10850: # --------------------------------------------- GetFileTimestamp
10851: # This function utilizes dirlist and returns the date stamp for
10852: # when it was last modified.  It will also return an error of -1
10853: # if an error occurs
10854: 
10855: sub GetFileTimestamp {
10856:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10857:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10858:     $studentName   = &LONCAPA::clean_username($studentName);
10859:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10860:                                     undef,$getuserdir);
10861:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10862:         return -1;
10863:     }
10864:     if (ref($fileref) eq 'ARRAY') {
10865:         my @stats = split('&',$fileref->[0]);
10866:         # @stats contains first the filename, then the stat output
10867:         return $stats[10]; # so this is 10 instead of 9.
10868:     } else {
10869:         return -1;
10870:     }
10871: }
10872: 
10873: sub stat_file {
10874:     my ($uri) = @_;
10875:     $uri = &clutter_with_no_wrapper($uri);
10876: 
10877:     my ($udom,$uname,$file);
10878:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10879: 	($udom,$uname,$file) =
10880: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10881: 	$file = 'userfiles/'.$file;
10882:     }
10883:     if ($uri =~ m-^/res/-) {
10884: 	($udom,$uname) = 
10885: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10886: 	$file = $uri;
10887:     }
10888: 
10889:     if (!$udom || !$uname || !$file) {
10890: 	# unable to handle the uri
10891: 	return ();
10892:     }
10893:     my $getpropath;
10894:     if ($file =~ /^userfiles\//) {
10895:         $getpropath = 1;
10896:     }
10897:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10898:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10899:         return ();
10900:     } else {
10901:         if (ref($listref) eq 'ARRAY') {
10902:             my @stats = split('&',$listref->[0]);
10903: 	    shift(@stats); #filename is first
10904: 	    return @stats;
10905:         }
10906:     }
10907:     return ();
10908: }
10909: 
10910: # --------------------------------------------------------- recursedirs
10911: # Recursive function to traverse either a specific user's Authoring Space
10912: # or corresponding Published Resource Space, and populate the hash ref:
10913: # $dirhashref with URLs of all directories, and if $filehashref hash
10914: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10915: # or .rights files in resource space, and .meta, .save, .log, and .bak
10916: # files in Authoring Space.
10917: #
10918: # Inputs:
10919: #
10920: # $is_home - true if current server is home server for user's space
10921: # $context - either: priv, or res respectively for Authoring or Resource Space.
10922: # $docroot - Document root (i.e., /home/httpd/html
10923: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10924: # $relpath - Current path (relative to top level).
10925: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10926: # $filehashref - reference to hash to populate with URLs of files (Optional)
10927: #
10928: # Returns: nothing
10929: #
10930: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10931: #
10932: # Currently used by interface/londocs.pm to create linked select boxes for
10933: # directory and filename to import a Course "Author" resource into a course, and
10934: # also to create linked select boxes for Authoring Space and Directory to choose
10935: # save location for creation of a new "standard" problem from the Course Editor.
10936: #
10937: 
10938: sub recursedirs {
10939:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10940:     return unless (ref($dirhashref) eq 'HASH');
10941:     my $currpath = $docroot.$toppath;
10942:     if ($relpath) {
10943:         $currpath .= "/$relpath";
10944:     }
10945:     my $savefile;
10946:     if (ref($filehashref)) {
10947:         $savefile = 1;
10948:     }
10949:     if ($is_home) {
10950:         if (opendir(my $dirh,$currpath)) {
10951:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10952:                 next if ($item eq '');
10953:                 if (-d "$currpath/$item") {
10954:                     my $newpath;
10955:                     if ($relpath) {
10956:                         $newpath = "$relpath/$item";
10957:                     } else {
10958:                         $newpath = $item;
10959:                     }
10960:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10961:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10962:                 } elsif ($savefile) {
10963:                     if ($context eq 'priv') {
10964:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10965:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10966:                         }
10967:                     } else {
10968:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10969:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10970:                         }
10971:                     }
10972:                 }
10973:             }
10974:             closedir($dirh);
10975:         }
10976:     } else {
10977:         my ($dirlistref,$listerror) =
10978:             &dirlist($toppath.$relpath);
10979:         my @dir_lines;
10980:         my $dirptr=16384;
10981:         if (ref($dirlistref) eq 'ARRAY') {
10982:             foreach my $dir_line (sort
10983:                               {
10984:                                   my ($afile)=split('&',$a,2);
10985:                                   my ($bfile)=split('&',$b,2);
10986:                                   return (lc($afile) cmp lc($bfile));
10987:                               } (@{$dirlistref})) {
10988:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10989:                     split(/\&/,$dir_line,16);
10990:                 $item =~ s/\s+$//;
10991:                 next if (($item =~ /^\.\.?$/) || ($obs));
10992:                 if ($dirptr&$testdir) {
10993:                     my $newpath;
10994:                     if ($relpath) {
10995:                         $newpath = "$relpath/$item";
10996:                     } else {
10997:                         $relpath = '/';
10998:                         $newpath = $item;
10999:                     }
11000:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11001:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11002:                 } elsif ($savefile) {
11003:                     if ($context eq 'priv') {
11004:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11005:                             $filehashref->{$relpath}{$item} = 1;
11006:                         }
11007:                     } else {
11008:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11009:                             $filehashref->{$relpath}{$item} = 1;
11010:                         }
11011:                     }
11012:                 }
11013:             }
11014:         }
11015:     }
11016:     return;
11017: }
11018: 
11019: # -------------------------------------------------------- Value of a Condition
11020: 
11021: # gets the value of a specific preevaluated condition
11022: #    stored in the string  $env{user.state.<cid>}
11023: # or looks up a condition reference in the bighash and if if hasn't
11024: # already been evaluated recurses into docondval to get the value of
11025: # the condition, then memoizing it to 
11026: #   $env{user.state.<cid>.<condition>}
11027: sub directcondval {
11028:     my $number=shift;
11029:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11030: 	&Apache::lonuserstate::evalstate();
11031:     }
11032:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11033: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11034:     } elsif ($number =~ /^_/) {
11035: 	my $sub_condition;
11036: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11037: 		&GDBM_READER(),0640)) {
11038: 	    $sub_condition=$bighash{'conditions'.$number};
11039: 	    untie(%bighash);
11040: 	}
11041: 	my $value = &docondval($sub_condition);
11042: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11043: 	return $value;
11044:     }
11045:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11046:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11047:     } else {
11048:        return 2;
11049:     }
11050: }
11051: 
11052: # get the collection of conditions for this resource
11053: sub condval {
11054:     my $condidx=shift;
11055:     my $allpathcond='';
11056:     foreach my $cond (split(/\|/,$condidx)) {
11057: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11058: 	    $allpathcond.=
11059: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11060: 	}
11061:     }
11062:     $allpathcond=~s/\|$//;
11063:     return &docondval($allpathcond);
11064: }
11065: 
11066: #evaluates an expression of conditions
11067: sub docondval {
11068:     my ($allpathcond) = @_;
11069:     my $result=0;
11070:     if ($env{'request.course.id'}
11071: 	&& defined($allpathcond)) {
11072: 	my $operand='|';
11073: 	my @stack;
11074: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11075: 	    if ($chunk eq '(') {
11076: 		push @stack,($operand,$result);
11077: 	    } elsif ($chunk eq ')') {
11078: 		my $before=pop @stack;
11079: 		if (pop @stack eq '&') {
11080: 		    $result=$result>$before?$before:$result;
11081: 		} else {
11082: 		    $result=$result>$before?$result:$before;
11083: 		}
11084: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11085: 		$operand=$chunk;
11086: 	    } else {
11087: 		my $new=directcondval($chunk);
11088: 		if ($operand eq '&') {
11089: 		    $result=$result>$new?$new:$result;
11090: 		} else {
11091: 		    $result=$result>$new?$result:$new;
11092: 		}
11093: 	    }
11094: 	}
11095:     }
11096:     return $result;
11097: }
11098: 
11099: # ---------------------------------------------------- Devalidate courseresdata
11100: 
11101: sub devalidatecourseresdata {
11102:     my ($coursenum,$coursedomain)=@_;
11103:     my $hashid=$coursenum.':'.$coursedomain;
11104:     &devalidate_cache_new('courseres',$hashid);
11105: }
11106: 
11107: 
11108: # --------------------------------------------------- Course Resourcedata Query
11109: #
11110: #  Parameters:
11111: #      $coursenum    - Number of the course.
11112: #      $coursedomain - Domain at which the course was created.
11113: #  Returns:
11114: #     A hash of the course parameters along (I think) with timestamps
11115: #     and version info.
11116: 
11117: sub get_courseresdata {
11118:     my ($coursenum,$coursedomain)=@_;
11119:     my $coursehom=&homeserver($coursenum,$coursedomain);
11120:     my $hashid=$coursenum.':'.$coursedomain;
11121:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11122:     my %dumpreply;
11123:     unless (defined($cached)) {
11124: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11125: 	$result=\%dumpreply;
11126: 	my ($tmp) = keys(%dumpreply);
11127: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11128: 	    &do_cache_new('courseres',$hashid,$result,600);
11129: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11130: 	    return $tmp;
11131: 	} elsif ($tmp =~ /^(error)/) {
11132: 	    $result=undef;
11133: 	    &do_cache_new('courseres',$hashid,$result,600);
11134: 	}
11135:     }
11136:     return $result;
11137: }
11138: 
11139: sub devalidateuserresdata {
11140:     my ($uname,$udom)=@_;
11141:     my $hashid="$udom:$uname";
11142:     &devalidate_cache_new('userres',$hashid);
11143: }
11144: 
11145: sub get_userresdata {
11146:     my ($uname,$udom)=@_;
11147:     #most student don\'t have any data set, check if there is some data
11148:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11149: 
11150:     my $hashid="$udom:$uname";
11151:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11152:     if (!defined($cached)) {
11153: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11154: 	$result=\%resourcedata;
11155: 	&do_cache_new('userres',$hashid,$result,600);
11156:     }
11157:     my ($tmp)=keys(%$result);
11158:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11159: 	return $result;
11160:     }
11161:     #error 2 occurs when the .db doesn't exist
11162:     if ($tmp!~/error: 2 /) {
11163:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11164: 	    &logthis("<font color=\"blue\">WARNING:".
11165: 		     " Trying to get resource data for ".
11166: 		     $uname." at ".$udom.": ".
11167: 		     $tmp."</font>");
11168:         }
11169:     } elsif ($tmp=~/error: 2 /) {
11170: 	#&EXT_cache_set($udom,$uname);
11171: 	&do_cache_new('userres',$hashid,undef,600);
11172: 	undef($tmp); # not really an error so don't send it back
11173:     }
11174:     return $tmp;
11175: }
11176: #----------------------------------------------- resdata - return resource data
11177: #  Purpose:
11178: #    Return resource data for either users or for a course.
11179: #  Parameters:
11180: #     $name      - Course/user name.
11181: #     $domain    - Name of the domain the user/course is registered on.
11182: #     $type      - Type of thing $name is (must be 'course' or 'user')
11183: #     $mapp      - decluttered URL of enclosing map  
11184: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11185: #     $recurseup - Ref to array of map URLs, starting with map containing
11186: #                  $mapp up through hierarchy of nested maps to top level map.  
11187: #     $courseid  - CourseID (first part of param identifier).
11188: #     $modifier  - Middle part of param identifier.
11189: #     $what      - Last part of param identifier.
11190: #     @which     - Array of names of resources desired.
11191: #  Returns:
11192: #     The value of the first reasource in @which that is found in the
11193: #     resource hash.
11194: #  Exceptional Conditions:
11195: #     If the $type passed in is not valid (not the string 'course' or 
11196: #     'user', an undefined  reference is returned.
11197: #     If none of the resources are found, an undef is returned
11198: sub resdata {
11199:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11200:         $modifier,$what,@which)=@_;
11201:     my $result;
11202:     if ($type eq 'course') {
11203: 	$result=&get_courseresdata($name,$domain);
11204:     } elsif ($type eq 'user') {
11205: 	$result=&get_userresdata($name,$domain);
11206:     }
11207:     if (!ref($result)) { return $result; }    
11208:     foreach my $item (@which) {
11209:         if ($item->[1] eq 'course') {
11210:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11211:                 unless ($$recursed) {
11212:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11213:                     $$recursed = 1;
11214:                 }
11215:                 foreach my $item (@${recurseup}) {
11216:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11217:                     last if (defined($result->{$norecursechk}));
11218:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11219:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11220:                 }
11221:             }
11222:         }
11223:         if (defined($result->{$item->[0]})) {
11224: 	    return [$result->{$item->[0]},$item->[1]];
11225: 	}
11226:     }
11227:     return undef;
11228: }
11229: 
11230: sub get_domain_lti {
11231:     my ($cdom,$context) = @_;
11232:     my ($name,%lti);
11233:     if ($context eq 'consumer') {
11234:         $name = 'ltitools';
11235:     } elsif ($context eq 'provider') {
11236:         $name = 'lti';
11237:     } else {
11238:         return %lti;
11239:     }
11240:     my ($result,$cached)=&is_cached_new($name,$cdom);
11241:     if (defined($cached)) {
11242:         if (ref($result) eq 'HASH') {
11243:             %lti = %{$result};
11244:         }
11245:     } else {
11246:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11247:         if (ref($domconfig{$name}) eq 'HASH') {
11248:             %lti = %{$domconfig{$name}};
11249:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11250:             if (ref($encdomconfig{$name}) eq 'HASH') {
11251:                 foreach my $id (keys(%lti)) {
11252:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11253:                         foreach my $item ('key','secret') {
11254:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11255:                         }
11256:                     }
11257:                 }
11258:             }
11259:         }
11260:         my $cachetime = 24*60*60;
11261:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11262:     }
11263:     return %lti;
11264: }
11265: 
11266: sub get_numsuppfiles {
11267:     my ($cnum,$cdom,$ignorecache)=@_;
11268:     my $hashid=$cnum.':'.$cdom;
11269:     my ($suppcount,$cached);
11270:     unless ($ignorecache) {
11271:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11272:     }
11273:     unless (defined($cached)) {
11274:         my $chome=&homeserver($cnum,$cdom);
11275:         unless ($chome eq 'no_host') {
11276:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11277:             my $suppmap = 'supplemental.sequence';
11278:             ($suppcount,$supptools,$errors) =
11279:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11280:                                                          $supptools,$errors);
11281:         }
11282:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11283:     }
11284:     return $suppcount;
11285: }
11286: 
11287: #
11288: # EXT resource caching routines
11289: #
11290: 
11291: {
11292: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11293: #
11294: # The course for which we cache
11295: my $cachedmapkey='';
11296: # The cached recursive maps for this course
11297: my %cachedmaps=();
11298: # When this was last done
11299: my $cachedmaptime='';
11300: 
11301: sub clear_EXT_cache_status {
11302:     &delenv('cache.EXT.');
11303: }
11304: 
11305: sub EXT_cache_status {
11306:     my ($target_domain,$target_user) = @_;
11307:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11308:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11309:         # We know already the user has no data
11310:         return 1;
11311:     } else {
11312:         return 0;
11313:     }
11314: }
11315: 
11316: sub EXT_cache_set {
11317:     my ($target_domain,$target_user) = @_;
11318:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11319:     #&appenv({$cachename => time});
11320: }
11321: 
11322: # --------------------------------------------------------- Value of a Variable
11323: sub EXT {
11324: 
11325:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11326:     unless ($varname) { return ''; }
11327:     #get real user name/domain, courseid and symb
11328:     my $courseid;
11329:     my $publicuser;
11330:     if ($symbparm) {
11331: 	$symbparm=&get_symb_from_alias($symbparm);
11332:     }
11333:     if (!($uname && $udom)) {
11334:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11335:       if (!$symbparm) {	$symbparm=$cursymb; }
11336:     } else {
11337: 	$courseid=$env{'request.course.id'};
11338:     }
11339:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11340:     my $rest;
11341:     if (defined($therest[0])) {
11342:        $rest=join('.',@therest);
11343:     } else {
11344:        $rest='';
11345:     }
11346: 
11347:     my $qualifierrest=$qualifier;
11348:     if ($rest) { $qualifierrest.='.'.$rest; }
11349:     my $spacequalifierrest=$space;
11350:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11351:     if ($realm eq 'user') {
11352: # --------------------------------------------------------------- user.resource
11353: 	if ($space eq 'resource') {
11354: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11355: 		  || defined($Apache::lonhomework::parsing_a_task))
11356: 		 &&
11357: 		 ($symbparm eq &symbread()) ) {	
11358: 		# if we are in the middle of processing the resource the
11359: 		# get the value we are planning on committing
11360:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11361:                     return $Apache::lonhomework::results{$qualifierrest};
11362:                 } else {
11363:                     return $Apache::lonhomework::history{$qualifierrest};
11364:                 }
11365: 	    } else {
11366: 		my %restored;
11367: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11368: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11369: 		} else {
11370: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11371: 		}
11372: 		return $restored{$qualifierrest};
11373: 	    }
11374: # ----------------------------------------------------------------- user.access
11375:         } elsif ($space eq 'access') {
11376: 	    # FIXME - not supporting calls for a specific user
11377:             return &allowed($qualifier,$rest);
11378: # ------------------------------------------ user.preferences, user.environment
11379:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11380: 	    if (($uname eq $env{'user.name'}) &&
11381: 		($udom eq $env{'user.domain'})) {
11382: 		return $env{join('.',('environment',$qualifierrest))};
11383: 	    } else {
11384: 		my %returnhash;
11385: 		if (!$publicuser) {
11386: 		    %returnhash=&userenvironment($udom,$uname,
11387: 						 $qualifierrest);
11388: 		}
11389: 		return $returnhash{$qualifierrest};
11390: 	    }
11391: # ----------------------------------------------------------------- user.course
11392:         } elsif ($space eq 'course') {
11393: 	    # FIXME - not supporting calls for a specific user
11394:             return $env{join('.',('request.course',$qualifier))};
11395: # ------------------------------------------------------------------- user.role
11396:         } elsif ($space eq 'role') {
11397: 	    # FIXME - not supporting calls for a specific user
11398:             my ($role,$where)=split(/\./,$env{'request.role'});
11399:             if ($qualifier eq 'value') {
11400: 		return $role;
11401:             } elsif ($qualifier eq 'extent') {
11402:                 return $where;
11403:             }
11404: # ----------------------------------------------------------------- user.domain
11405:         } elsif ($space eq 'domain') {
11406:             return $udom;
11407: # ------------------------------------------------------------------- user.name
11408:         } elsif ($space eq 'name') {
11409:             return $uname;
11410: # ---------------------------------------------------- Any other user namespace
11411:         } else {
11412: 	    my %reply;
11413: 	    if (!$publicuser) {
11414: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11415: 	    }
11416: 	    return $reply{$qualifierrest};
11417:         }
11418:     } elsif ($realm eq 'query') {
11419: # ---------------------------------------------- pull stuff out of query string
11420:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11421: 						[$spacequalifierrest]);
11422: 	return $env{'form.'.$spacequalifierrest}; 
11423:    } elsif ($realm eq 'request') {
11424: # ------------------------------------------------------------- request.browser
11425:         if ($space eq 'browser') {
11426:             return $env{'browser.'.$qualifier};
11427: # ------------------------------------------------------------ request.filename
11428:         } else {
11429:             return $env{'request.'.$spacequalifierrest};
11430:         }
11431:     } elsif ($realm eq 'course') {
11432: # ---------------------------------------------------------- course.description
11433:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11434:     } elsif ($realm eq 'resource') {
11435: 
11436: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11437: 	    if (!$symbparm) { $symbparm=&symbread(); }
11438: 	}
11439: 
11440:         if ($qualifier eq '') {
11441: 	    if ($space eq 'title') {
11442: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11443: 	        return &gettitle($symbparm);
11444: 	    }
11445: 	
11446: 	    if ($space eq 'map') {
11447: 	        my ($map) = &decode_symb($symbparm);
11448: 	        return &symbread($map);
11449: 	    }
11450:             if ($space eq 'maptitle') {
11451:                 my ($map) = &decode_symb($symbparm);
11452:                 return &gettitle($map);
11453:             }
11454: 	    if ($space eq 'filename') {
11455: 	        if ($symbparm) {
11456: 		    return &clutter((&decode_symb($symbparm))[2]);
11457: 	        }
11458: 	        return &hreflocation('',$env{'request.filename'});
11459: 	    }
11460: 
11461:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11462:                 if ($space eq 'visibleparts') {
11463:                     my $navmap = Apache::lonnavmaps::navmap->new();
11464:                     my $item;
11465:                     if (ref($navmap)) {
11466:                         my $res = $navmap->getBySymb($symbparm);
11467:                         my $parts = $res->parts();
11468:                         if (ref($parts) eq 'ARRAY') {
11469:                             $item = join(',',@{$parts});
11470:                         }
11471:                         undef($navmap);
11472:                     }
11473:                     return $item;
11474:                 }
11475:             }
11476:         }
11477: 
11478: 	my ($section, $group, @groups, @recurseup, $recursed);
11479: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11480:         if (($courseid eq '') && ($cid)) {
11481:             $courseid = $cid;
11482:         }
11483: 	if (($symbparm && $courseid) && 
11484: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11485: 
11486: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11487: 
11488: # ----------------------------------------------------- Cascading lookup scheme
11489: 	    my $symbp=$symbparm;
11490: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11491: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11492:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11493: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11494: 	    if (($env{'user.name'} eq $uname) &&
11495: 		($env{'user.domain'} eq $udom)) {
11496: 		$section=$env{'request.course.sec'};
11497:                 @groups = split(/:/,$env{'request.course.groups'});  
11498:                 @groups=&sort_course_groups($courseid,@groups); 
11499: 	    } else {
11500: 		if (! defined($usection)) {
11501: 		    $section=&getsection($udom,$uname,$courseid);
11502: 		} else {
11503: 		    $section = $usection;
11504: 		}
11505:                 @groups = &get_users_groups($udom,$uname,$courseid);
11506: 	    }
11507: 
11508: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11509: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11510:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11511: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11512: 
11513: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11514: 	    my $courselevelr=$courseid.'.'.$symbparm;
11515:             $courseleveli=$courseid.'.'.$recurseparm;
11516: 	    $courselevelm=$courseid.'.'.$mapparm;
11517: 
11518: # ----------------------------------------------------------- first, check user
11519: 
11520: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11521:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11522: 				       ([$courselevelr,'resource'],
11523: 					[$courselevelm,'map'     ],
11524:                                         [$courseleveli,'map'     ],
11525: 					[$courselevel, 'course'  ]));
11526: 	    if (defined($userreply)) { return &get_reply($userreply); }
11527: 
11528: # ------------------------------------------------ second, check some of course
11529:             my $coursereply;
11530:             if (@groups > 0) {
11531:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11532:                                        $recurseparm,$mapparm,$spacequalifierrest,
11533:                                        $mapp,\$recursed,\@recurseup);
11534:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11535:             }
11536: 
11537: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11538: 				  $env{'course.'.$courseid.'.domain'},
11539: 				  'course',$mapp,\$recursed,\@recurseup,
11540:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11541: 				  ([$seclevelr,   'resource'],
11542: 				   [$seclevelm,   'map'     ],
11543:                                    [$secleveli,   'map'     ],
11544: 				   [$seclevel,    'course'  ],
11545: 				   [$courselevelr,'resource']));
11546: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11547: 
11548: # ------------------------------------------------------ third, check map parms
11549: 	    my %parmhash=();
11550: 	    my $thisparm='';
11551: 	    if (tie(%parmhash,'GDBM_File',
11552: 		    $env{'request.course.fn'}.'_parms.db',
11553: 		    &GDBM_READER(),0640)) {
11554: 		$thisparm=$parmhash{$symbparm};
11555: 		untie(%parmhash);
11556: 	    }
11557: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11558: 	}
11559: # ------------------------------------------ fourth, look in resource metadata
11560:  
11561:         my $what = $spacequalifierrest;
11562: 	$what=~s/\./\_/;
11563: 	my $filename;
11564: 	if (!$symbparm) { $symbparm=&symbread(); }
11565: 	if ($symbparm) {
11566: 	    $filename=(&decode_symb($symbparm))[2];
11567: 	} else {
11568: 	    $filename=$env{'request.filename'};
11569: 	}
11570:         my $toolsymb;
11571:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
11572:             $toolsymb = $symbparm;
11573:         }
11574: 	my $metadata=&metadata($filename,$what,$toolsymb);
11575: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11576: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
11577: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11578: 
11579: # ----------------------------------------------- fifth, look in rest of course
11580: 	if ($symbparm && defined($courseid) && 
11581: 	    $courseid eq $env{'request.course.id'}) {
11582: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11583: 				     $env{'course.'.$courseid.'.domain'},
11584: 				     'course',$mapp,\$recursed,\@recurseup,
11585:                                      $courseid,'.',$spacequalifierrest,
11586: 				     ([$courselevelm,'map'   ],
11587:                                       [$courseleveli,'map'   ],
11588: 				      [$courselevel, 'course']));
11589: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11590: 	}
11591: # ------------------------------------------------------------------ Cascade up
11592: 	unless ($space eq '0') {
11593: 	    my @parts=split(/_/,$space);
11594: 	    my $id=pop(@parts);
11595: 	    my $part=join('_',@parts);
11596: 	    if ($part eq '') { $part='0'; }
11597: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11598: 				 $symbparm,$udom,$uname,$section,1);
11599: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11600: 	}
11601: 	if ($recurse) { return undef; }
11602: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
11603: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11604: # ---------------------------------------------------- Any other user namespace
11605:     } elsif ($realm eq 'environment') {
11606: # ----------------------------------------------------------------- environment
11607: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11608: 	    return $env{'environment.'.$spacequalifierrest};
11609: 	} else {
11610: 	    if ($uname eq 'anonymous' && $udom eq '') {
11611: 		return '';
11612: 	    }
11613: 	    my %returnhash=&userenvironment($udom,$uname,
11614: 					    $spacequalifierrest);
11615: 	    return $returnhash{$spacequalifierrest};
11616: 	}
11617:     } elsif ($realm eq 'system') {
11618: # ----------------------------------------------------------------- system.time
11619: 	if ($space eq 'time') {
11620: 	    return time;
11621:         }
11622:     } elsif ($realm eq 'server') {
11623: # ----------------------------------------------------------------- system.time
11624: 	if ($space eq 'name') {
11625: 	    return $ENV{'SERVER_NAME'};
11626:         }
11627:     }
11628:     return '';
11629: }
11630: 
11631: sub get_reply {
11632:     my ($reply_value) = @_;
11633:     if (ref($reply_value) eq 'ARRAY') {
11634:         if (wantarray) {
11635: 	    return @$reply_value;
11636:         }
11637:         return $reply_value->[0];
11638:     } else {
11639:         return $reply_value;
11640:     }
11641: }
11642: 
11643: sub check_group_parms {
11644:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11645:         $recursed,$recurseupref) = @_;
11646:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11647:                   [$what,'course']);
11648:     my $coursereply;
11649:     foreach my $group (@{$groups}) {
11650:         my @groupitems = ();
11651:         foreach my $level (@levels) {
11652:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11653:              push(@groupitems,[$item,$level->[1]]);
11654:         }
11655:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11656:                                    $env{'course.'.$courseid.'.domain'},
11657:                                    'course',$mapp,$recursed,$recurseupref,
11658:                                    $courseid,'.['.$group.'].',$what,
11659:                                    @groupitems);
11660:         last if (defined($coursereply));
11661:     }
11662:     return $coursereply;
11663: }
11664: 
11665: sub get_map_hierarchy {
11666:     my ($mapname,$courseid) = @_;
11667:     my @recurseup = ();
11668:     if ($mapname) {
11669:         if (($cachedmapkey eq $courseid) &&
11670:             (abs($cachedmaptime-time)<5)) {
11671:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11672:                 return @{$cachedmaps{$mapname}};
11673:             }
11674:         }
11675:         my $navmap = Apache::lonnavmaps::navmap->new();
11676:         if (ref($navmap)) {
11677:             @recurseup = $navmap->recurseup_maps($mapname);
11678:             undef($navmap);
11679:             $cachedmaps{$mapname} = \@recurseup;
11680:             $cachedmaptime=time;
11681:             $cachedmapkey=$courseid;
11682:         }
11683:     }
11684:     return @recurseup;
11685: }
11686: 
11687: }
11688: 
11689: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11690:     my ($courseid,@groups) = @_;
11691:     @groups = sort(@groups);
11692:     return @groups;
11693: }
11694: 
11695: sub packages_tab_default {
11696:     my ($uri,$varname,$toolsymb)=@_;
11697:     my (undef,$part,$name)=split(/\./,$varname);
11698: 
11699:     my (@extension,@specifics,$do_default);
11700:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
11701: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11702: 	if ($pack_type eq 'default') {
11703: 	    $do_default=1;
11704: 	} elsif ($pack_type eq 'extension') {
11705: 	    push(@extension,[$package,$pack_type,$pack_part]);
11706: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11707: 	    # only look at packages defaults for packages that this id is
11708: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11709: 	}
11710:     }
11711:     # first look for a package that matches the requested part id
11712:     foreach my $package (@specifics) {
11713: 	my (undef,$pack_type,$pack_part)=@{$package};
11714: 	next if ($pack_part ne $part);
11715: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11716: 	    return $packagetab{"$pack_type&$name&default"};
11717: 	}
11718:     }
11719:     # look for any possible matching non extension_ package
11720:     foreach my $package (@specifics) {
11721: 	my (undef,$pack_type,$pack_part)=@{$package};
11722: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11723: 	    return $packagetab{"$pack_type&$name&default"};
11724: 	}
11725: 	if ($pack_type eq 'part') { $pack_part='0'; }
11726: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11727: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11728: 	}
11729:     }
11730:     # look for any posible extension_ match
11731:     foreach my $package (@extension) {
11732: 	my ($package,$pack_type)=@{$package};
11733: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11734: 	    return $packagetab{"$pack_type&$name&default"};
11735: 	}
11736: 	if (defined($packagetab{$package."&$name&default"})) {
11737: 	    return $packagetab{$package."&$name&default"};
11738: 	}
11739:     }
11740:     # look for a global default setting
11741:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11742: 	return $packagetab{"default&$name&default"};
11743:     }
11744:     return undef;
11745: }
11746: 
11747: sub add_prefix_and_part {
11748:     my ($prefix,$part)=@_;
11749:     my $keyroot;
11750:     if (defined($prefix) && $prefix !~ /^__/) {
11751: 	# prefix that has a part already
11752: 	$keyroot=$prefix;
11753:     } elsif (defined($prefix)) {
11754: 	# prefix that is missing a part
11755: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11756:     } else {
11757: 	# no prefix at all
11758: 	if (defined($part)) { $keyroot='_'.$part; }
11759:     }
11760:     return $keyroot;
11761: }
11762: 
11763: # ---------------------------------------------------------------- Get metadata
11764: 
11765: my %metaentry;
11766: my %importedpartids;
11767: my %importedrespids;
11768: sub metadata {
11769:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
11770:     $uri=&declutter($uri);
11771:     # if it is a non metadata possible uri return quickly
11772:     if (($uri eq '') || 
11773: 	(($uri =~ m|^/*adm/|) && 
11774: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11775:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11776: 	return undef;
11777:     }
11778:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11779: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11780: 	return undef;
11781:     }
11782:     my $filename=$uri;
11783:     $uri=~s/\.meta$//;
11784: #
11785: # Is the metadata already cached?
11786: # Look at timestamp of caching
11787: # Everything is cached by the main uri, libraries are never directly cached
11788: #
11789:     if (!defined($liburi)) {
11790: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11791: 	if (defined($cached)) { return $result->{':'.$what}; }
11792:     }
11793: 
11794: #
11795: # If the uri is for an external tool the file from
11796: # which metadata should be retrieved depends on whether
11797: # the tool had been configured to be gradable (set in the Course
11798: # Editor or Resource Editor).
11799: #
11800: # If a valid symb has been included as the third arg in the call
11801: # to &metadata() that can be used to retrieve the value of
11802: # parameter_0_gradable set for the resource, and included in the
11803: # uploaded map containing the tool. The value is retrieved via
11804: # &EXT(), if a valid symb is available.  Otherwise the value of
11805: # gradable in the exttool_$marker.db file for the tool instance
11806: # is retrieved via &get().
11807: #
11808: # When lonuserstate::traceroute() calls lonnet::EXT() for 
11809: # hiddenresource and encrypturl (during course initialization)
11810: # the map-level parameter for resource.0.gradable included in the 
11811: # uploaded map containing the tool will not yet have been stored
11812: # in the user_course_parms.db file for the user's session, so in 
11813: # this case fall back to retrieving gradable status from the
11814: # exttool_$marker.db file.
11815: #
11816: # In order to avoid an infinite loop, &metadata() will return
11817: # before a call to &EXT(), if the uri is for an external tool
11818: # and the $what for which metadata is being requested is
11819: # parameter_0_gradable or 0_gradable.
11820: #
11821: 
11822:     if ($uri =~ /ext\.tool$/) {
11823:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
11824:             return;
11825:         } else {
11826:             my ($checked,$use_passback);
11827:             if ($toolsymb ne '') {
11828:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
11829:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
11830:                     $checked = 1;
11831:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
11832:                         $use_passback = 1;
11833:                     }
11834:                 }
11835:             }
11836:             unless ($checked) {
11837:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
11838:                 $marker=~s/\D//g;
11839:                 if ($marker) {
11840:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
11841:                     $use_passback = $toolsettings{'gradable'};
11842:                 }
11843:             }
11844:             if ($use_passback) {
11845:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
11846:             } else {
11847:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
11848:             }
11849:         }
11850:     }
11851: 
11852:     {
11853: # Imported parts would go here
11854:         my @origfiletagids=();
11855:         my $importedparts=0;
11856: 
11857: # Imported responseids would go here
11858:         my $importedresponses=0;
11859: #
11860: # Is this a recursive call for a library?
11861: #
11862: #	if (! exists($metacache{$uri})) {
11863: #	    $metacache{$uri}={};
11864: #	}
11865: 	my $cachetime = 60*60;
11866:         if ($liburi) {
11867: 	    $liburi=&declutter($liburi);
11868:             $filename=$liburi;
11869:         } else {
11870: 	    &devalidate_cache_new('meta',$uri);
11871: 	    undef(%metaentry);
11872: 	}
11873:         my %metathesekeys=();
11874:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11875: 	my $metastring;
11876: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11877: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11878: 	    $metastring = 
11879: 		&Apache::lonnet::ssi_body($which,
11880: 					  ('grade_target' => 'meta'));
11881: 	    $cachetime = 1; # only want this cached in the child not long term
11882: 	} elsif (($uri !~ m -^(editupload)/-) && 
11883:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11884: 	    my $file=&filelocation('',&clutter($filename));
11885: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11886: 	    $metastring=&getfile($file);
11887: 	}
11888:         my $parser=HTML::LCParser->new(\$metastring);
11889:         my $token;
11890:         undef %metathesekeys;
11891:         while ($token=$parser->get_token) {
11892: 	    if ($token->[0] eq 'S') {
11893: 		if (defined($token->[2]->{'package'})) {
11894: #
11895: # This is a package - get package info
11896: #
11897: 		    my $package=$token->[2]->{'package'};
11898: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11899: 		    if (defined($token->[2]->{'id'})) { 
11900: 			$keyroot.='_'.$token->[2]->{'id'}; 
11901: 		    }
11902: 		    if ($metaentry{':packages'}) {
11903: 			$metaentry{':packages'}.=','.$package.$keyroot;
11904: 		    } else {
11905: 			$metaentry{':packages'}=$package.$keyroot;
11906: 		    }
11907: 		    foreach my $pack_entry (keys(%packagetab)) {
11908: 			my $part=$keyroot;
11909: 			$part=~s/^\_//;
11910: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11911: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11912: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11913: 			    # ignore package.tab specified default values
11914:                             # here &package_tab_default() will fetch those
11915: 			    if ($subp eq 'default') { next; }
11916: 			    my $value=$packagetab{$pack_entry};
11917: 			    my $unikey;
11918: 			    if ($pack =~ /_0$/) {
11919: 				$unikey='parameter_0_'.$name;
11920: 				$part=0;
11921: 			    } else {
11922: 				$unikey='parameter'.$keyroot.'_'.$name;
11923: 			    }
11924: 			    if ($subp eq 'display') {
11925: 				$value.=' [Part: '.$part.']';
11926: 			    }
11927: 			    $metaentry{':'.$unikey.'.part'}=$part;
11928: 			    $metathesekeys{$unikey}=1;
11929: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11930: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11931: 			    }
11932: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11933: 				$metaentry{':'.$unikey}=
11934: 				    $metaentry{':'.$unikey.'.default'};
11935: 			    }
11936: 			}
11937: 		    }
11938: 		} else {
11939: #
11940: # This is not a package - some other kind of start tag
11941: #
11942: 		    my $entry=$token->[1];
11943: 		    my $unikey='';
11944: 
11945: 		    if ($entry eq 'import') {
11946: #
11947: # Importing a library here
11948: #
11949:                         my $location=$parser->get_text('/import');
11950:                         my $dir=$filename;
11951:                         $dir=~s|[^/]*$||;
11952:                         $location=&filelocation($dir,$location);
11953: 
11954:                         my $importid=$token->[2]->{'id'};
11955:                         my $importmode=$token->[2]->{'importmode'};
11956: #
11957: # Check metadata for imported file to
11958: # see if it contained response items
11959: #
11960:                         my ($origfile,@libfilekeys);
11961:                         my %currmetaentry = %metaentry;
11962:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
11963:                                                            $depthcount+1));
11964:                         if (grep(/^responseorder$/,@libfilekeys)) {
11965:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
11966:                                                              undef,$depthcount+1);
11967:                             if ($libresponseorder ne '') {
11968:                                 if ($#origfiletagids<0) {
11969:                                     undef(%importedrespids);
11970:                                     undef(%importedpartids);
11971:                                 }
11972:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
11973:                                 if (@respids) {
11974:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
11975:                                 }
11976:                                 if ($importedrespids{$importid} ne '') {
11977:                                     $importedresponses = 1;
11978: # We need to get the original file and the imported file to get the response order correct
11979: # Load and inspect original file
11980:                                     if ($#origfiletagids<0) {
11981:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11982:                                         $origfile=&getfile($origfilelocation);
11983:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11984:                                     }
11985:                                 }
11986:                             }
11987:                         }
11988: # Do not overwrite contents of %metaentry hash for resource itself with 
11989: # hash populated for imported library file
11990:                         %metaentry = %currmetaentry;
11991:                         undef(%currmetaentry);
11992:                         if ($importmode eq 'part') {
11993: # Import as part(s)
11994:                            $importedparts=1;
11995: # We need to get the original file and the imported file to get the part order correct
11996: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11997: # Load and inspect original file if we didn't do that already
11998:                            if ($#origfiletagids<0) {
11999:                                undef(%importedrespids);
12000:                                undef(%importedpartids);
12001:                                if ($origfile eq '') {
12002:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12003:                                    $origfile=&getfile($origfilelocation);
12004:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12005:                                }
12006:                            }
12007:                            my @impfilepartids;
12008: # If <partorder> tag is included in metadata for the imported file
12009: # get the parts in the imported file from that.
12010:                            if (grep(/^partorder$/,@libfilekeys)) {
12011:                                %currmetaentry = %metaentry;
12012:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12013:                                                             $depthcount+1);
12014:                                %metaentry = %currmetaentry;
12015:                                undef(%currmetaentry);
12016:                                if ($libpartorder ne '') {
12017:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12018:                                }
12019:                            } else {
12020: # If no <partorder> tag available, load and inspect imported file
12021:                                my $impfile=&getfile($location);
12022:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12023:                            }
12024:                            if ($#impfilepartids>=0) {
12025: # This problem had parts
12026:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12027:                            } else {
12028: # Importing by turning a single problem into a problem part
12029: # It gets the import-tags ID as part-ID
12030:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12031:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12032:                            }
12033:                         } else {
12034: # Import as problem or as normal import
12035:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12036:                             unless ($importmode eq 'problem') {
12037: # Normal import
12038:                                 if (defined($token->[2]->{'id'})) {
12039:                                     $unikey.='_'.$token->[2]->{'id'};
12040:                                 }
12041:                             }
12042: # Check metadata for imported file to
12043: # see if it contained parts
12044:                             if (grep(/^partorder$/,@libfilekeys)) {
12045:                                 %currmetaentry = %metaentry;
12046:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12047:                                                              $depthcount+1);
12048:                                 %metaentry = %currmetaentry;
12049:                                 undef(%currmetaentry);
12050:                                 if ($libpartorder ne '') {
12051:                                     $importedparts = 1;
12052:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12053:                                 }
12054:                             }
12055:                         }
12056: 			if ($depthcount<20) {
12057: 			    my $metadata = 
12058: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12059: 					  $depthcount+1);
12060: 			    foreach my $meta (split(',',$metadata)) {
12061: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12062: 				$metathesekeys{$meta}=1;
12063: 			    }
12064:                         }
12065: 		    } else {
12066: #
12067: # Not importing, some other kind of non-package, non-library start tag
12068: # 
12069:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12070:                         if (defined($token->[2]->{'id'})) {
12071:                             $unikey.='_'.$token->[2]->{'id'};
12072:                         }
12073: 			if (defined($token->[2]->{'name'})) { 
12074: 			    $unikey.='_'.$token->[2]->{'name'}; 
12075: 			}
12076: 			$metathesekeys{$unikey}=1;
12077: 			foreach my $param (@{$token->[3]}) {
12078: 			    $metaentry{':'.$unikey.'.'.$param} =
12079: 				$token->[2]->{$param};
12080: 			}
12081: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12082: 			my $default=$metaentry{':'.$unikey.'.default'};
12083: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12084: 		 # only ws inside the tag, and not in default, so use default
12085: 		 # as value
12086: 			    $metaentry{':'.$unikey}=$default;
12087: 			} elsif ( $internaltext =~ /\S/ ) {
12088: 		  # something interesting inside the tag
12089: 			    $metaentry{':'.$unikey}=$internaltext;
12090: 			} else {
12091: 		  # no interesting values, don't set a default
12092: 			}
12093: # end of not-a-package not-a-library import
12094: 		    }
12095: # end of not-a-package start tag
12096: 		}
12097: # the next is the end of "start tag"
12098: 	    }
12099: 	}
12100: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12101: 	$extension = lc($extension);
12102: 	if ($extension eq 'htm') { $extension='html'; }
12103: 
12104: 	foreach my $key (keys(%packagetab)) {
12105: 	    #no specific packages #how's our extension
12106: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12107: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12108: 					 \%metathesekeys);
12109: 	}
12110: 
12111: 	if (!exists($metaentry{':packages'})
12112: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12113: 	    foreach my $key (keys(%packagetab)) {
12114: 		#no specific packages well let's get default then
12115: 		if ($key!~/^default&/) { next; }
12116: 		&metadata_create_package_def($uri,$key,'default',
12117: 					     \%metathesekeys);
12118: 	    }
12119: 	}
12120: # are there custom rights to evaluate
12121: 	if ($metaentry{':copyright'} eq 'custom') {
12122: 
12123:     #
12124:     # Importing a rights file here
12125:     #
12126: 	    unless ($depthcount) {
12127: 		my $location=$metaentry{':customdistributionfile'};
12128: 		my $dir=$filename;
12129: 		$dir=~s|[^/]*$||;
12130: 		$location=&filelocation($dir,$location);
12131: 		my $rights_metadata =
12132: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12133: 			      $depthcount+1);
12134: 		foreach my $rights (split(',',$rights_metadata)) {
12135: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12136: 		    $metathesekeys{$rights}=1;
12137: 		}
12138: 	    }
12139: 	}
12140: 	# uniqifiy package listing
12141: 	my %seen;
12142: 	my @uniq_packages =
12143: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12144: 	$metaentry{':packages'} = join(',',@uniq_packages);
12145: 
12146:         if (($importedresponses) || ($importedparts)) {
12147:             if ($importedparts) {
12148: # We had imported parts and need to rebuild partorder
12149:                 $metaentry{':partorder'}='';
12150:                 $metathesekeys{'partorder'}=1;
12151:             }
12152:             if ($importedresponses) {
12153: # We had imported responses and need to rebuil responseorder
12154:                 $metaentry{':responseorder'}='';
12155:                 $metathesekeys{'responseorder'}=1;
12156:             }
12157:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12158:                 my $origid = $origfiletagids[$index+1];
12159:                 if ($origfiletagids[$index] eq 'part') {
12160: # Original part, part of the problem
12161:                     if ($importedparts) {
12162:                         $metaentry{':partorder'}.=','.$origid;
12163:                     }
12164:                 } elsif ($origfiletagids[$index] eq 'import') {
12165:                     if ($importedparts) {
12166: # We have imported parts at this position
12167:                         if ($importedpartids{$origid} ne '') {
12168:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12169:                         }
12170:                     }
12171:                     if ($importedresponses) {
12172: # We have imported responses at this position
12173:                         if ($importedrespids{$origid} ne '') {
12174:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12175:                         }
12176:                     }
12177:                 } else {
12178: # Original response item, part of the problem
12179:                     if ($importedresponses) {
12180:                         $metaentry{':responseorder'}.=','.$origid;
12181:                     }
12182:                 }
12183:             }
12184:             if ($importedparts) {
12185:                 $metaentry{':partorder'}=~s/^\,//;
12186:             }
12187:             if ($importedresponses) {
12188:                 $metaentry{':responseorder'}=~s/^\,//;
12189:             }
12190:         }
12191: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12192: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12193: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12194:         unless ($liburi) {
12195: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12196:         }
12197: # this is the end of "was not already recently cached
12198:     }
12199:     return $metaentry{':'.$what};
12200: }
12201: 
12202: sub metadata_create_package_def {
12203:     my ($uri,$key,$package,$metathesekeys)=@_;
12204:     my ($pack,$name,$subp)=split(/\&/,$key);
12205:     if ($subp eq 'default') { next; }
12206:     
12207:     if (defined($metaentry{':packages'})) {
12208: 	$metaentry{':packages'}.=','.$package;
12209:     } else {
12210: 	$metaentry{':packages'}=$package;
12211:     }
12212:     my $value=$packagetab{$key};
12213:     my $unikey;
12214:     $unikey='parameter_0_'.$name;
12215:     $metaentry{':'.$unikey.'.part'}=0;
12216:     $$metathesekeys{$unikey}=1;
12217:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12218: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12219:     }
12220:     if (defined($metaentry{':'.$unikey.'.default'})) {
12221: 	$metaentry{':'.$unikey}=
12222: 	    $metaentry{':'.$unikey.'.default'};
12223:     }
12224: }
12225: 
12226: sub metadata_generate_part0 {
12227:     my ($metadata,$metacache,$uri) = @_;
12228:     my %allnames;
12229:     foreach my $metakey (keys(%$metadata)) {
12230: 	if ($metakey=~/^parameter\_(.*)/) {
12231: 	  my $part=$$metacache{':'.$metakey.'.part'};
12232: 	  my $name=$$metacache{':'.$metakey.'.name'};
12233: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12234: 	    $allnames{$name}=$part;
12235: 	  }
12236: 	}
12237:     }
12238:     foreach my $name (keys(%allnames)) {
12239:       $$metadata{"parameter_0_$name"}=1;
12240:       my $key=":parameter_0_$name";
12241:       $$metacache{"$key.part"}='0';
12242:       $$metacache{"$key.name"}=$name;
12243:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12244: 					   $allnames{$name}.'_'.$name.
12245: 					   '.type'};
12246:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12247: 			     '.display'};
12248:       my $expr='[Part: '.$allnames{$name}.']';
12249:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12250:       $$metacache{"$key.display"}=$olddis;
12251:     }
12252: }
12253: 
12254: # ------------------------------------------------------ Devalidate title cache
12255: 
12256: sub devalidate_title_cache {
12257:     my ($url)=@_;
12258:     if (!$env{'request.course.id'}) { return; }
12259:     my $symb=&symbread($url);
12260:     if (!$symb) { return; }
12261:     my $key=$env{'request.course.id'}."\0".$symb;
12262:     &devalidate_cache_new('title',$key);
12263: }
12264: 
12265: # ------------------------------------------------- Get the title of a course
12266: 
12267: sub current_course_title {
12268:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12269: }
12270: # ------------------------------------------------- Get the title of a resource
12271: 
12272: sub gettitle {
12273:     my $urlsymb=shift;
12274:     my $symb=&symbread($urlsymb);
12275:     if ($symb) {
12276: 	my $key=$env{'request.course.id'}."\0".$symb;
12277: 	my ($result,$cached)=&is_cached_new('title',$key);
12278: 	if (defined($cached)) { 
12279: 	    return $result;
12280: 	}
12281: 	my ($map,$resid,$url)=&decode_symb($symb);
12282: 	my $title='';
12283: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12284: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12285: 	} else {
12286: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12287: 		    &GDBM_READER(),0640)) {
12288: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12289: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12290: 		untie(%bighash);
12291: 	    }
12292: 	}
12293: 	$title=~s/\&colon\;/\:/gs;
12294: 	if ($title) {
12295: # Remember both $symb and $title for dynamic metadata
12296:             $accesshash{$symb.'___crstitle'}=$title;
12297:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12298: # Cache this title and then return it
12299: 	    return &do_cache_new('title',$key,$title,600);
12300: 	}
12301: 	$urlsymb=$url;
12302:     }
12303:     my $title=&metadata($urlsymb,'title');
12304:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12305:     return $title;
12306: }
12307: 
12308: sub get_slot {
12309:     my ($which,$cnum,$cdom)=@_;
12310:     if (!$cnum || !$cdom) {
12311: 	(undef,my $courseid)=&whichuser();
12312: 	$cdom=$env{'course.'.$courseid.'.domain'};
12313: 	$cnum=$env{'course.'.$courseid.'.num'};
12314:     }
12315:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12316:     my %slotinfo;
12317:     if (exists($remembered{$key})) {
12318: 	$slotinfo{$which} = $remembered{$key};
12319:     } else {
12320: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12321: 	&Apache::lonhomework::showhash(%slotinfo);
12322: 	my ($tmp)=keys(%slotinfo);
12323: 	if ($tmp=~/^error:/) { return (); }
12324: 	$remembered{$key} = $slotinfo{$which};
12325:     }
12326:     if (ref($slotinfo{$which}) eq 'HASH') {
12327: 	return %{$slotinfo{$which}};
12328:     }
12329:     return $slotinfo{$which};
12330: }
12331: 
12332: sub get_reservable_slots {
12333:     my ($cnum,$cdom,$uname,$udom) = @_;
12334:     my $now = time;
12335:     my $reservable_info;
12336:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12337:     if (exists($remembered{$key})) {
12338:         $reservable_info = $remembered{$key};
12339:     } else {
12340:         my %resv;
12341:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12342:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12343:         $reservable_info = \%resv;
12344:         $remembered{$key} = $reservable_info;
12345:     }
12346:     return $reservable_info;
12347: }
12348: 
12349: sub get_course_slots {
12350:     my ($cnum,$cdom) = @_;
12351:     my $hashid=$cnum.':'.$cdom;
12352:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12353:     if (defined($cached)) {
12354:         if (ref($result) eq 'HASH') {
12355:             return %{$result};
12356:         }
12357:     } else {
12358:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12359:         my ($tmp) = keys(%slots);
12360:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12361:             &do_cache_new('allslots',$hashid,\%slots,600);
12362:             return %slots;
12363:         }
12364:     }
12365:     return;
12366: }
12367: 
12368: sub devalidate_slots_cache {
12369:     my ($cnum,$cdom)=@_;
12370:     my $hashid=$cnum.':'.$cdom;
12371:     &devalidate_cache_new('allslots',$hashid);
12372: }
12373: 
12374: sub get_coursechange {
12375:     my ($cdom,$cnum) = @_;
12376:     if ($cdom eq '' || $cnum eq '') {
12377:         return unless ($env{'request.course.id'});
12378:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12379:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12380:     }
12381:     my $hashid=$cdom.'_'.$cnum;
12382:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12383:     if ((defined($cached)) && ($change ne '')) {
12384:         return $change;
12385:     } else {
12386:         my %crshash;
12387:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12388:         if ($crshash{'internal.contentchange'} eq '') {
12389:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12390:             if ($change eq '') {
12391:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12392:                 $change = $crshash{'internal.created'};
12393:             }
12394:         } else {
12395:             $change = $crshash{'internal.contentchange'};
12396:         }
12397:         my $cachetime = 600;
12398:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12399:     }
12400:     return $change;
12401: }
12402: 
12403: sub devalidate_coursechange_cache {
12404:     my ($cnum,$cdom)=@_;
12405:     my $hashid=$cnum.':'.$cdom;
12406:     &devalidate_cache_new('crschange',$hashid);
12407: }
12408: 
12409: # ------------------------------------------------- Update symbolic store links
12410: 
12411: sub symblist {
12412:     my ($mapname,%newhash)=@_;
12413:     $mapname=&deversion(&declutter($mapname));
12414:     my %hash;
12415:     if (($env{'request.course.fn'}) && (%newhash)) {
12416:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12417:                       &GDBM_WRCREAT(),0640)) {
12418: 	    foreach my $url (keys(%newhash)) {
12419: 		next if ($url eq 'last_known'
12420: 			 && $env{'form.no_update_last_known'});
12421: 		$hash{declutter($url)}=&encode_symb($mapname,
12422: 						    $newhash{$url}->[1],
12423: 						    $newhash{$url}->[0]);
12424:             }
12425:             if (untie(%hash)) {
12426: 		return 'ok';
12427:             }
12428:         }
12429:     }
12430:     return 'error';
12431: }
12432: 
12433: # --------------------------------------------------------------- Verify a symb
12434: 
12435: sub symbverify {
12436:     my ($symb,$thisurl,$encstate)=@_;
12437:     my $thisfn=$thisurl;
12438:     $thisfn=&declutter($thisfn);
12439: # direct jump to resource in page or to a sequence - will construct own symbs
12440:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12441: # check URL part
12442:     my ($map,$resid,$url)=&decode_symb($symb);
12443: 
12444:     unless ($url eq $thisfn) { return 0; }
12445: 
12446:     $symb=&symbclean($symb);
12447:     $thisurl=&deversion($thisurl);
12448:     $thisfn=&deversion($thisfn);
12449: 
12450:     my %bighash;
12451:     my $okay=0;
12452: 
12453:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12454:                             &GDBM_READER(),0640)) {
12455:         my $noclutter;
12456:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12457:             $thisurl =~ s/\?.+$//;
12458:             if ($map =~ m{^uploaded/.+\.page$}) {
12459:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12460:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12461:                 $noclutter = 1;
12462:             }
12463:         }
12464:         my $ids;
12465:         if ($noclutter) {
12466:             $ids=$bighash{'ids_'.$thisurl};
12467:         } else {
12468:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12469:         }
12470:         unless ($ids) {
12471:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12472:             $ids=$bighash{$idkey};
12473:         }
12474:         if ($ids) {
12475: # ------------------------------------------------------------------- Has ID(s)
12476:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12477:                 $symb =~ s/\?.+$//;
12478:             }
12479: 	    foreach my $id (split(/\,/,$ids)) {
12480: 	       my ($mapid,$resid)=split(/\./,$id);
12481:                if (
12482:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12483:    eq $symb) {
12484:                    if (ref($encstate)) {
12485:                        $$encstate = $bighash{'encrypted_'.$id};
12486:                    }
12487: 		   if (($env{'request.role.adv'}) ||
12488: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12489:                        ($thisurl eq '/adm/navmaps')) {
12490: 		       $okay=1;
12491:                        last;
12492: 		   }
12493: 	       }
12494: 	   }
12495:         }
12496: 	untie(%bighash);
12497:     }
12498:     return $okay;
12499: }
12500: 
12501: # --------------------------------------------------------------- Clean-up symb
12502: 
12503: sub symbclean {
12504:     my $symb=shift;
12505:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12506: # remove version from map
12507:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12508: 
12509: # remove version from URL
12510:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12511: 
12512: # remove wrapper
12513: 
12514:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12515:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12516:     return $symb;
12517: }
12518: 
12519: # ---------------------------------------------- Split symb to find map and url
12520: 
12521: sub encode_symb {
12522:     my ($map,$resid,$url)=@_;
12523:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12524: }
12525: 
12526: sub decode_symb {
12527:     my $symb=shift;
12528:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12529:     my ($map,$resid,$url)=split(/___/,$symb);
12530:     return (&fixversion($map),$resid,&fixversion($url));
12531: }
12532: 
12533: sub fixversion {
12534:     my $fn=shift;
12535:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12536:     my %bighash;
12537:     my $uri=&clutter($fn);
12538:     my $key=$env{'request.course.id'}.'_'.$uri;
12539: # is this cached?
12540:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12541:     if (defined($cached)) { return $result; }
12542: # unfortunately not cached, or expired
12543:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12544: 	    &GDBM_READER(),0640)) {
12545:  	if ($bighash{'version_'.$uri}) {
12546:  	    my $version=$bighash{'version_'.$uri};
12547:  	    unless (($version eq 'mostrecent') || 
12548: 		    ($version==&getversion($uri))) {
12549:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12550:  	    }
12551:  	}
12552:  	untie %bighash;
12553:     }
12554:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12555: }
12556: 
12557: sub deversion {
12558:     my $url=shift;
12559:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12560:     return $url;
12561: }
12562: 
12563: # ------------------------------------------------------ Return symb list entry
12564: 
12565: sub symbread {
12566:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12567:     my $cache_str='request.symbread.cached.'.$thisfn;
12568:     if (defined($env{$cache_str})) {
12569:         if ($ignorecachednull) {
12570:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12571:         } else {
12572:             return $env{$cache_str};
12573:         }
12574:     }
12575: # no filename provided? try from environment
12576:     unless ($thisfn) {
12577:         if ($env{'request.symb'}) {
12578: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12579: 	}
12580: 	$thisfn=$env{'request.filename'};
12581:     }
12582:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12583: # is that filename actually a symb? Verify, clean, and return
12584:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12585: 	if (&symbverify($thisfn,$1)) {
12586: 	    return $env{$cache_str}=&symbclean($thisfn);
12587: 	}
12588:     }
12589:     $thisfn=declutter($thisfn);
12590:     my %hash;
12591:     my %bighash;
12592:     my $syval='';
12593:     if (($env{'request.course.fn'}) && ($thisfn)) {
12594:         my $targetfn = $thisfn;
12595:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12596:             $targetfn = 'adm/wrapper/'.$thisfn;
12597:         }
12598: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12599: 	    $targetfn=$1;
12600: 	}
12601:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12602:                       &GDBM_READER(),0640)) {
12603: 	    $syval=$hash{$targetfn};
12604:             untie(%hash);
12605:         }
12606: # ---------------------------------------------------------- There was an entry
12607:         if ($syval) {
12608: 	    #unless ($syval=~/\_\d+$/) {
12609: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12610: 		    #&appenv({'request.ambiguous' => $thisfn});
12611: 		    #return $env{$cache_str}='';
12612: 		#}    
12613: 		#$syval.=$1;
12614: 	    #}
12615:         } else {
12616: # ------------------------------------------------------- Was not in symb table
12617:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12618:                             &GDBM_READER(),0640)) {
12619: # ---------------------------------------------- Get ID(s) for current resource
12620:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12621:               unless ($ids) { 
12622:                  $ids=$bighash{'ids_/'.$thisfn};
12623:               }
12624:               unless ($ids) {
12625: # alias?
12626: 		  $ids=$bighash{'mapalias_'.$thisfn};
12627:               }
12628:               if ($ids) {
12629: # ------------------------------------------------------------------- Has ID(s)
12630:                  my @possibilities=split(/\,/,$ids);
12631:                  if ($#possibilities==0) {
12632: # ----------------------------------------------- There is only one possibility
12633: 		     my ($mapid,$resid)=split(/\./,$ids);
12634: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12635: 						    $resid,$thisfn);
12636:                      if (ref($possibles) eq 'HASH') {
12637:                          $possibles->{$syval} = 1;    
12638:                      }
12639:                      if ($checkforblock) {
12640:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12641:                          if (@blockers) {
12642:                              $syval = '';
12643:                              return;
12644:                          }
12645:                      }
12646:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12647: # ------------------------------------------ There is more than one possibility
12648:                      my $realpossible=0;
12649:                      foreach my $id (@possibilities) {
12650: 			 my $file=$bighash{'src_'.$id};
12651:                          my $canaccess;
12652:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12653:                              $canaccess = 1;
12654:                          } else { 
12655:                              $canaccess = &allowed('bre',$file);
12656:                          }
12657:                          if ($canaccess) {
12658:          		     my ($mapid,$resid)=split(/\./,$id);
12659:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12660:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12661: 						             $resid,$thisfn);
12662:                                  if (ref($possibles) eq 'HASH') {
12663:                                      $possibles->{$syval} = 1;
12664:                                  }
12665:                                  if ($checkforblock) {
12666:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12667:                                      unless (@blockers > 0) {
12668:                                          $syval = $poss_syval;
12669:                                          $realpossible++;
12670:                                      }
12671:                                  } else {
12672:                                      $syval = $poss_syval;
12673:                                      $realpossible++;
12674:                                  }
12675:                              }
12676: 			 }
12677:                      }
12678: 		     if ($realpossible!=1) { $syval=''; }
12679:                  } else {
12680:                      $syval='';
12681:                  }
12682: 	      }
12683:               untie(%bighash);
12684:            }
12685:         }
12686:         if ($syval) {
12687: 	    return $env{$cache_str}=$syval;
12688:         }
12689:     }
12690:     &appenv({'request.ambiguous' => $thisfn});
12691:     return $env{$cache_str}='';
12692: }
12693: 
12694: # ---------------------------------------------------------- Return random seed
12695: 
12696: sub numval {
12697:     my $txt=shift;
12698:     $txt=~tr/A-J/0-9/;
12699:     $txt=~tr/a-j/0-9/;
12700:     $txt=~tr/K-T/0-9/;
12701:     $txt=~tr/k-t/0-9/;
12702:     $txt=~tr/U-Z/0-5/;
12703:     $txt=~tr/u-z/0-5/;
12704:     $txt=~s/\D//g;
12705:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12706:     return int($txt);
12707: }
12708: 
12709: sub numval2 {
12710:     my $txt=shift;
12711:     $txt=~tr/A-J/0-9/;
12712:     $txt=~tr/a-j/0-9/;
12713:     $txt=~tr/K-T/0-9/;
12714:     $txt=~tr/k-t/0-9/;
12715:     $txt=~tr/U-Z/0-5/;
12716:     $txt=~tr/u-z/0-5/;
12717:     $txt=~s/\D//g;
12718:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12719:     my $total;
12720:     foreach my $val (@txts) { $total+=$val; }
12721:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12722:     return int($total);
12723: }
12724: 
12725: sub numval3 {
12726:     use integer;
12727:     my $txt=shift;
12728:     $txt=~tr/A-J/0-9/;
12729:     $txt=~tr/a-j/0-9/;
12730:     $txt=~tr/K-T/0-9/;
12731:     $txt=~tr/k-t/0-9/;
12732:     $txt=~tr/U-Z/0-5/;
12733:     $txt=~tr/u-z/0-5/;
12734:     $txt=~s/\D//g;
12735:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12736:     my $total;
12737:     foreach my $val (@txts) { $total+=$val; }
12738:     if ($_64bit) { $total=(($total<<32)>>32); }
12739:     return $total;
12740: }
12741: 
12742: sub digest {
12743:     my ($data)=@_;
12744:     my $digest=&Digest::MD5::md5($data);
12745:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12746:     my ($e,$f);
12747:     {
12748:         use integer;
12749:         $e=($a+$b);
12750:         $f=($c+$d);
12751:         if ($_64bit) {
12752:             $e=(($e<<32)>>32);
12753:             $f=(($f<<32)>>32);
12754:         }
12755:     }
12756:     if (wantarray) {
12757: 	return ($e,$f);
12758:     } else {
12759: 	my $g;
12760: 	{
12761: 	    use integer;
12762: 	    $g=($e+$f);
12763: 	    if ($_64bit) {
12764: 		$g=(($g<<32)>>32);
12765: 	    }
12766: 	}
12767: 	return $g;
12768:     }
12769: }
12770: 
12771: sub latest_rnd_algorithm_id {
12772:     return '64bit5';
12773: }
12774: 
12775: sub get_rand_alg {
12776:     my ($courseid)=@_;
12777:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12778:     if ($courseid) {
12779: 	return $env{"course.$courseid.rndseed"};
12780:     }
12781:     return &latest_rnd_algorithm_id();
12782: }
12783: 
12784: sub validCODE {
12785:     my ($CODE)=@_;
12786:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12787:     return 0;
12788: }
12789: 
12790: sub getCODE {
12791:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12792:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12793: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12794: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12795: 	return $Apache::lonhomework::history{'resource.CODE'};
12796:     }
12797:     return undef;
12798: }
12799: #
12800: #  Determines the random seed for a specific context:
12801: #
12802: # parameters:
12803: #   symb      - in course context the symb for the seed.
12804: #   course_id - The course id of the form domain_coursenum.
12805: #   domain    - Domain for the user.
12806: #   course    - Course for the user.
12807: #   cenv      - environment of the course.
12808: #
12809: # NOTE:
12810: #   All parameters are picked out of the environment if missing
12811: #   or not defined.
12812: #   If a symb cannot be determined the current time is used instead.
12813: #
12814: #  For a given well defined symb, courside, domain, username,
12815: #  and course environment, the seed is reproducible.
12816: #
12817: sub rndseed {
12818:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12819:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12820:     if (!defined($symb)) {
12821: 	unless ($symb=$wsymb) { return time; }
12822:     }
12823:     if (!defined $courseid) { 
12824: 	$courseid=$wcourseid; 
12825:     }
12826:     if (!defined $domain) { $domain=$wdomain; }
12827:     if (!defined $username) { $username=$wusername }
12828: 
12829:     my $which;
12830:     if (defined($cenv->{'rndseed'})) {
12831: 	$which = $cenv->{'rndseed'};
12832:     } else {
12833: 	$which =&get_rand_alg($courseid);
12834:     }
12835:     if (defined(&getCODE())) {
12836: 
12837: 	if ($which eq '64bit5') {
12838: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12839: 	} elsif ($which eq '64bit4') {
12840: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12841: 	} else {
12842: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12843: 	}
12844:     } elsif ($which eq '64bit5') {
12845: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12846:     } elsif ($which eq '64bit4') {
12847: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12848:     } elsif ($which eq '64bit3') {
12849: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12850:     } elsif ($which eq '64bit2') {
12851: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12852:     } elsif ($which eq '64bit') {
12853: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12854:     }
12855:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12856: }
12857: 
12858: sub rndseed_32bit {
12859:     my ($symb,$courseid,$domain,$username)=@_;
12860:     {
12861: 	use integer;
12862: 	my $symbchck=unpack("%32C*",$symb) << 27;
12863: 	my $symbseed=numval($symb) << 22;
12864: 	my $namechck=unpack("%32C*",$username) << 17;
12865: 	my $nameseed=numval($username) << 12;
12866: 	my $domainseed=unpack("%32C*",$domain) << 7;
12867: 	my $courseseed=unpack("%32C*",$courseid);
12868: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12869: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12870: 	#&logthis("rndseed :$num:$symb");
12871: 	if ($_64bit) { $num=(($num<<32)>>32); }
12872: 	return $num;
12873:     }
12874: }
12875: 
12876: sub rndseed_64bit {
12877:     my ($symb,$courseid,$domain,$username)=@_;
12878:     {
12879: 	use integer;
12880: 	my $symbchck=unpack("%32S*",$symb) << 21;
12881: 	my $symbseed=numval($symb) << 10;
12882: 	my $namechck=unpack("%32S*",$username);
12883: 	
12884: 	my $nameseed=numval($username) << 21;
12885: 	my $domainseed=unpack("%32S*",$domain) << 10;
12886: 	my $courseseed=unpack("%32S*",$courseid);
12887: 	
12888: 	my $num1=$symbchck+$symbseed+$namechck;
12889: 	my $num2=$nameseed+$domainseed+$courseseed;
12890: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12891: 	#&logthis("rndseed :$num:$symb");
12892: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12893: 	return "$num1,$num2";
12894:     }
12895: }
12896: 
12897: sub rndseed_64bit2 {
12898:     my ($symb,$courseid,$domain,$username)=@_;
12899:     {
12900: 	use integer;
12901: 	# strings need to be an even # of cahracters long, it it is odd the
12902:         # last characters gets thrown away
12903: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12904: 	my $symbseed=numval($symb) << 10;
12905: 	my $namechck=unpack("%32S*",$username.' ');
12906: 	
12907: 	my $nameseed=numval($username) << 21;
12908: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12909: 	my $courseseed=unpack("%32S*",$courseid.' ');
12910: 	
12911: 	my $num1=$symbchck+$symbseed+$namechck;
12912: 	my $num2=$nameseed+$domainseed+$courseseed;
12913: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12914: 	#&logthis("rndseed :$num:$symb");
12915: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12916: 	return "$num1,$num2";
12917:     }
12918: }
12919: 
12920: sub rndseed_64bit3 {
12921:     my ($symb,$courseid,$domain,$username)=@_;
12922:     {
12923: 	use integer;
12924: 	# strings need to be an even # of cahracters long, it it is odd the
12925:         # last characters gets thrown away
12926: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12927: 	my $symbseed=numval2($symb) << 10;
12928: 	my $namechck=unpack("%32S*",$username.' ');
12929: 	
12930: 	my $nameseed=numval2($username) << 21;
12931: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12932: 	my $courseseed=unpack("%32S*",$courseid.' ');
12933: 	
12934: 	my $num1=$symbchck+$symbseed+$namechck;
12935: 	my $num2=$nameseed+$domainseed+$courseseed;
12936: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12937: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12938: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12939: 	
12940: 	return "$num1:$num2";
12941:     }
12942: }
12943: 
12944: sub rndseed_64bit4 {
12945:     my ($symb,$courseid,$domain,$username)=@_;
12946:     {
12947: 	use integer;
12948: 	# strings need to be an even # of cahracters long, it it is odd the
12949:         # last characters gets thrown away
12950: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12951: 	my $symbseed=numval3($symb) << 10;
12952: 	my $namechck=unpack("%32S*",$username.' ');
12953: 	
12954: 	my $nameseed=numval3($username) << 21;
12955: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12956: 	my $courseseed=unpack("%32S*",$courseid.' ');
12957: 	
12958: 	my $num1=$symbchck+$symbseed+$namechck;
12959: 	my $num2=$nameseed+$domainseed+$courseseed;
12960: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12961: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12962: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12963: 	
12964: 	return "$num1:$num2";
12965:     }
12966: }
12967: 
12968: sub rndseed_64bit5 {
12969:     my ($symb,$courseid,$domain,$username)=@_;
12970:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12971:     return "$num1:$num2";
12972: }
12973: 
12974: sub rndseed_CODE_64bit {
12975:     my ($symb,$courseid,$domain,$username)=@_;
12976:     {
12977: 	use integer;
12978: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12979: 	my $symbseed=numval2($symb);
12980: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12981: 	my $CODEseed=numval(&getCODE());
12982: 	my $courseseed=unpack("%32S*",$courseid.' ');
12983: 	my $num1=$symbseed+$CODEchck;
12984: 	my $num2=$CODEseed+$courseseed+$symbchck;
12985: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12986: 	#&logthis("rndseed :$num1:$num2:$symb");
12987: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12988: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12989: 	return "$num1:$num2";
12990:     }
12991: }
12992: 
12993: sub rndseed_CODE_64bit4 {
12994:     my ($symb,$courseid,$domain,$username)=@_;
12995:     {
12996: 	use integer;
12997: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12998: 	my $symbseed=numval3($symb);
12999: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13000: 	my $CODEseed=numval3(&getCODE());
13001: 	my $courseseed=unpack("%32S*",$courseid.' ');
13002: 	my $num1=$symbseed+$CODEchck;
13003: 	my $num2=$CODEseed+$courseseed+$symbchck;
13004: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13005: 	#&logthis("rndseed :$num1:$num2:$symb");
13006: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13007: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13008: 	return "$num1:$num2";
13009:     }
13010: }
13011: 
13012: sub rndseed_CODE_64bit5 {
13013:     my ($symb,$courseid,$domain,$username)=@_;
13014:     my $code = &getCODE();
13015:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13016:     return "$num1:$num2";
13017: }
13018: 
13019: sub setup_random_from_rndseed {
13020:     my ($rndseed)=@_;
13021:     if ($rndseed =~/([,:])/) {
13022:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13023:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13024:             &Math::Random::random_set_seed_from_phrase($rndseed);
13025:         } else {
13026:             &Math::Random::random_set_seed($num1,$num2);
13027:         }
13028:     } else {
13029: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13030:     }
13031: }
13032: 
13033: sub latest_receipt_algorithm_id {
13034:     return 'receipt3';
13035: }
13036: 
13037: sub recunique {
13038:     my $fucourseid=shift;
13039:     my $unique;
13040:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13041: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13042: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13043:     } else {
13044: 	$unique=$perlvar{'lonReceipt'};
13045:     }
13046:     return unpack("%32C*",$unique);
13047: }
13048: 
13049: sub recprefix {
13050:     my $fucourseid=shift;
13051:     my $prefix;
13052:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13053: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13054: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13055:     } else {
13056: 	$prefix=$perlvar{'lonHostID'};
13057:     }
13058:     return unpack("%32C*",$prefix);
13059: }
13060: 
13061: sub ireceipt {
13062:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13063: 
13064:     my $return =&recprefix($fucourseid).'-';
13065: 
13066:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13067: 	$env{'request.state'} eq 'construct') {
13068: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13069: 	return $return;
13070:     }
13071: 
13072:     my $cuname=unpack("%32C*",$funame);
13073:     my $cudom=unpack("%32C*",$fudom);
13074:     my $cucourseid=unpack("%32C*",$fucourseid);
13075:     my $cusymb=unpack("%32C*",$fusymb);
13076:     my $cunique=&recunique($fucourseid);
13077:     my $cpart=unpack("%32S*",$part);
13078:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13079: 
13080: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13081: 			       
13082: 	$return.= ($cunique%$cuname+
13083: 		   $cunique%$cudom+
13084: 		   $cusymb%$cuname+
13085: 		   $cusymb%$cudom+
13086: 		   $cucourseid%$cuname+
13087: 		   $cucourseid%$cudom+
13088: 		   $cpart%$cuname+
13089: 		   $cpart%$cudom);
13090:     } else {
13091: 	$return.= ($cunique%$cuname+
13092: 		   $cunique%$cudom+
13093: 		   $cusymb%$cuname+
13094: 		   $cusymb%$cudom+
13095: 		   $cucourseid%$cuname+
13096: 		   $cucourseid%$cudom);
13097:     }
13098:     return $return;
13099: }
13100: 
13101: sub receipt {
13102:     my ($part)=@_;
13103:     my ($symb,$courseid,$domain,$name) = &whichuser();
13104:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13105: }
13106: 
13107: sub whichuser {
13108:     my ($passedsymb)=@_;
13109:     my ($symb,$courseid,$domain,$name,$publicuser);
13110:     if (defined($env{'form.grade_symb'})) {
13111: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13112: 	my $allowed=&allowed('vgr',$tmp_courseid);
13113: 	if (!$allowed &&
13114: 	    exists($env{'request.course.sec'}) &&
13115: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13116: 	    $allowed=&allowed('vgr',$tmp_courseid.
13117: 			      '/'.$env{'request.course.sec'});
13118: 	}
13119: 	if ($allowed) {
13120: 	    ($symb)=&get_env_multiple('form.grade_symb');
13121: 	    $courseid=$tmp_courseid;
13122: 	    ($domain)=&get_env_multiple('form.grade_domain');
13123: 	    ($name)=&get_env_multiple('form.grade_username');
13124: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13125: 	}
13126:     }
13127:     if (!$passedsymb) {
13128: 	$symb=&symbread();
13129:     } else {
13130: 	$symb=$passedsymb;
13131:     }
13132:     $courseid=$env{'request.course.id'};
13133:     $domain=$env{'user.domain'};
13134:     $name=$env{'user.name'};
13135:     if ($name eq 'public' && $domain eq 'public') {
13136: 	if (!defined($env{'form.username'})) {
13137: 	    $env{'form.username'}.=time.rand(10000000);
13138: 	}
13139: 	$name.=$env{'form.username'};
13140:     }
13141:     return ($symb,$courseid,$domain,$name,$publicuser);
13142: 
13143: }
13144: 
13145: # ------------------------------------------------------------ Serves up a file
13146: # returns either the contents of the file or 
13147: # -1 if the file doesn't exist
13148: #
13149: # if the target is a file that was uploaded via DOCS, 
13150: # a check will be made to see if a current copy exists on the local server,
13151: # if it does this will be served, otherwise a copy will be retrieved from
13152: # the home server for the course and stored in /home/httpd/html/userfiles on
13153: # the local server.   
13154: 
13155: sub getfile {
13156:     my ($file) = @_;
13157:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13158:     &repcopy($file);
13159:     return &readfile($file);
13160: }
13161: 
13162: sub repcopy_userfile {
13163:     my ($file)=@_;
13164:     my $londocroot = $perlvar{'lonDocRoot'};
13165:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13166:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13167:     my ($cdom,$cnum,$filename) = 
13168: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13169:     my $uri="/uploaded/$cdom/$cnum/$filename";
13170:     if (-e "$file") {
13171: # we already have a local copy, check it out
13172: 	my @fileinfo = stat($file);
13173: 	my $rtncode;
13174: 	my $info;
13175: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13176: 	if ($lwpresp ne 'ok') {
13177: # there is no such file anymore, even though we had a local copy
13178: 	    if ($rtncode eq '404') {
13179: 		unlink($file);
13180: 	    }
13181: 	    return -1;
13182: 	}
13183: 	if ($info < $fileinfo[9]) {
13184: # nice, the file we have is up-to-date, just say okay
13185: 	    return 'ok';
13186: 	} else {
13187: # the file is outdated, get rid of it
13188: 	    unlink($file);
13189: 	}
13190:     }
13191: # one way or the other, at this point, we don't have the file
13192: # construct the correct path for the file
13193:     my @parts = ($cdom,$cnum); 
13194:     if ($filename =~ m|^(.+)/[^/]+$|) {
13195: 	push @parts, split(/\//,$1);
13196:     }
13197:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13198:     foreach my $part (@parts) {
13199: 	$path .= '/'.$part;
13200: 	if (!-e $path) {
13201: 	    mkdir($path,0770);
13202: 	}
13203:     }
13204: # now the path exists for sure
13205: # get a user agent
13206:     my $transferfile=$file.'.in.transfer';
13207: # FIXME: this should flock
13208:     if (-e $transferfile) { return 'ok'; }
13209:     my $request;
13210:     $uri=~s/^\///;
13211:     my $homeserver = &homeserver($cnum,$cdom);
13212:     my $protocol = $protocol{$homeserver};
13213:     $protocol = 'http' if ($protocol ne 'https');
13214:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
13215:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13216: # did it work?
13217:     if ($response->is_error()) {
13218: 	unlink($transferfile);
13219: 	&logthis("Userfile repcopy failed for $uri");
13220: 	return -1;
13221:     }
13222: # worked, rename the transfer file
13223:     rename($transferfile,$file);
13224:     return 'ok';
13225: }
13226: 
13227: sub tokenwrapper {
13228:     my $uri=shift;
13229:     $uri=~s|^https?\://([^/]+)||;
13230:     $uri=~s|^/||;
13231:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13232:     my $token=$1;
13233:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13234:     if ($udom && $uname && $file) {
13235: 	$file=~s|(\?\.*)*$||;
13236:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13237:         my $homeserver = &homeserver($uname,$udom);
13238:         my $protocol = $protocol{$homeserver};
13239:         $protocol = 'http' if ($protocol ne 'https');
13240:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
13241:                (($uri=~/\?/)?'&':'?').'token='.$token.
13242:                                '&tokenissued='.$perlvar{'lonHostID'};
13243:     } else {
13244:         return '/adm/notfound.html';
13245:     }
13246: }
13247: 
13248: # call with reqtype HEAD: get last modification time
13249: # call with reqtype GET: get the file contents
13250: # Do not call this with reqtype GET for large files! It loads everything into memory
13251: #
13252: sub getuploaded {
13253:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13254:     $uri=~s/^\///;
13255:     my $homeserver = &homeserver($cnum,$cdom);
13256:     my $protocol = $protocol{$homeserver};
13257:     $protocol = 'http' if ($protocol ne 'https');
13258:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
13259:     my $request=new HTTP::Request($reqtype,$uri);
13260:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13261:     $$rtncode = $response->code;
13262:     if (! $response->is_success()) {
13263: 	return 'failed';
13264:     }      
13265:     if ($reqtype eq 'HEAD') {
13266: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13267:     } elsif ($reqtype eq 'GET') {
13268: 	$$info = $response->content;
13269:     }
13270:     return 'ok';
13271: }
13272: 
13273: sub readfile {
13274:     my $file = shift;
13275:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13276:     my $fh;
13277:     open($fh,"<",$file);
13278:     my $a='';
13279:     while (my $line = <$fh>) { $a .= $line; }
13280:     return $a;
13281: }
13282: 
13283: sub filelocation {
13284:     my ($dir,$file) = @_;
13285:     my $location;
13286:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13287: 
13288:     if ($file =~ m-^/adm/-) {
13289: 	$file=~s-^/adm/wrapper/-/-;
13290: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13291:     }
13292: 
13293:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13294:         $location = $file;
13295:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13296:         my ($udom,$uname,$filename)=
13297:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13298:         my $home=&homeserver($uname,$udom);
13299:         my $is_me=0;
13300:         my @ids=&current_machine_ids();
13301:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13302:         if ($is_me) {
13303:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13304:         } else {
13305:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13306:   	      $udom.'/'.$uname.'/'.$filename;
13307:         }
13308:     } elsif ($file =~ m-^/adm/-) {
13309: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13310:     } else {
13311:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13312:         $file=~s:^/(res|priv)/:/:;
13313:         my $space=$1;
13314:         if ( !( $file =~ m:^/:) ) {
13315:             $location = $dir. '/'.$file;
13316:         } else {
13317:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13318:         }
13319:     }
13320:     $location=~s://+:/:g; # remove duplicate /
13321:     while ($location=~m{/\.\./}) {
13322: 	if ($location =~ m{/[^/]+/\.\./}) {
13323: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13324: 	} else {
13325: 	    $location=~ s{/\.\./}{/}g;
13326: 	}
13327:     } #remove dir/..
13328:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13329:     return $location;
13330: }
13331: 
13332: sub hreflocation {
13333:     my ($dir,$file)=@_;
13334:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13335: 	$file=filelocation($dir,$file);
13336:     } elsif ($file=~m-^/adm/-) {
13337: 	$file=~s-^/adm/wrapper/-/-;
13338: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13339:     }
13340:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13341: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13342:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13343: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13344: 	        {/uploaded/$1/$2/}x;
13345:     }
13346:     if ($file=~ m{^/userfiles/}) {
13347: 	$file =~ s{^/userfiles/}{/uploaded/};
13348:     }
13349:     return $file;
13350: }
13351: 
13352: 
13353: 
13354: 
13355: 
13356: sub current_machine_domains {
13357:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13358: }
13359: 
13360: sub machine_domains {
13361:     my ($hostname) = @_;
13362:     my @domains;
13363:     my %hostname = &all_hostnames();
13364:     while( my($id, $name) = each(%hostname)) {
13365: #	&logthis("-$id-$name-$hostname-");
13366: 	if ($hostname eq $name) {
13367: 	    push(@domains,&host_domain($id));
13368: 	}
13369:     }
13370:     return @domains;
13371: }
13372: 
13373: sub current_machine_ids {
13374:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13375: }
13376: 
13377: sub machine_ids {
13378:     my ($hostname) = @_;
13379:     $hostname ||= &hostname($perlvar{'lonHostID'});
13380:     my @ids;
13381:     my %name_to_host = &all_names();
13382:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13383: 	return @{ $name_to_host{$hostname} };
13384:     }
13385:     return;
13386: }
13387: 
13388: sub additional_machine_domains {
13389:     my @domains;
13390:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13391:     while( my $line = <$fh>) {
13392:         $line =~ s/\s//g;
13393:         push(@domains,$line);
13394:     }
13395:     return @domains;
13396: }
13397: 
13398: sub default_login_domain {
13399:     my $domain = $perlvar{'lonDefDomain'};
13400:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13401:     foreach my $posdom (&current_machine_domains(),
13402:                         &additional_machine_domains()) {
13403:         if (lc($posdom) eq lc($testdomain)) {
13404:             $domain=$posdom;
13405:             last;
13406:         }
13407:     }
13408:     return $domain;
13409: }
13410: 
13411: # ------------------------------------------------------------- Declutters URLs
13412: 
13413: sub declutter {
13414:     my $thisfn=shift;
13415:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13416:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13417:         $thisfn=~s{^/home/httpd/html}{};
13418:     }
13419:     $thisfn=~s/^\///;
13420:     $thisfn=~s|^adm/wrapper/||;
13421:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13422:     $thisfn=~s/^res\///;
13423:     $thisfn=~s/^priv\///;
13424:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13425:         $thisfn=~s/\?.+$//;
13426:     }
13427:     return $thisfn;
13428: }
13429: 
13430: # ------------------------------------------------------------- Clutter up URLs
13431: 
13432: sub clutter {
13433:     my $thisfn='/'.&declutter(shift);
13434:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13435: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13436:        $thisfn='/res'.$thisfn; 
13437:     }
13438:     if ($thisfn !~m|^/adm|) {
13439: 	if ($thisfn =~ m|^/ext/|) {
13440: 	    $thisfn='/adm/wrapper'.$thisfn;
13441: 	} else {
13442: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13443: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13444: 	    if ($embstyle eq 'ssi'
13445: 		|| ($embstyle eq 'hdn')
13446: 		|| ($embstyle eq 'rat')
13447: 		|| ($embstyle eq 'prv')
13448: 		|| ($embstyle eq 'ign')) {
13449: 		#do nothing with these
13450: 	    } elsif (($embstyle eq 'img') 
13451: 		|| ($embstyle eq 'emb')
13452: 		|| ($embstyle eq 'wrp')) {
13453: 		$thisfn='/adm/wrapper'.$thisfn;
13454: 	    } elsif ($embstyle eq 'unk'
13455: 		     && $thisfn!~/\.(sequence|page)$/) {
13456: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13457: 	    } else {
13458: #		&logthis("Got a blank emb style");
13459: 	    }
13460: 	}
13461:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13462:         $thisfn='/adm/wrapper'.$thisfn;
13463:     }
13464:     return $thisfn;
13465: }
13466: 
13467: sub clutter_with_no_wrapper {
13468:     my $uri = &clutter(shift);
13469:     if ($uri =~ m-^/adm/-) {
13470: 	$uri =~ s-^/adm/wrapper/-/-;
13471: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13472:     }
13473:     return $uri;
13474: }
13475: 
13476: sub freeze_escape {
13477:     my ($value)=@_;
13478:     if (ref($value)) {
13479: 	$value=&nfreeze($value);
13480: 	return '__FROZEN__'.&escape($value);
13481:     }
13482:     return &escape($value);
13483: }
13484: 
13485: 
13486: sub thaw_unescape {
13487:     my ($value)=@_;
13488:     if ($value =~ /^__FROZEN__/) {
13489: 	substr($value,0,10,undef);
13490: 	$value=&unescape($value);
13491: 	return &thaw($value);
13492:     }
13493:     return &unescape($value);
13494: }
13495: 
13496: sub correct_line_ends {
13497:     my ($result)=@_;
13498:     $$result =~s/\r\n/\n/mg;
13499:     $$result =~s/\r/\n/mg;
13500: }
13501: # ================================================================ Main Program
13502: 
13503: sub goodbye {
13504:    &logthis("Starting Shut down");
13505: #not converted to using infrastruture and probably shouldn't be
13506:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13507: #converted
13508: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13509:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13510: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13511: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13512: #1.1 only
13513: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13514: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13515: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13516: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13517:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13518:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13519:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13520:    &flushcourselogs();
13521:    &logthis("Shutting down");
13522: }
13523: 
13524: sub get_dns {
13525:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13526:     if (!$ignore_cache) {
13527: 	my ($content,$cached)=
13528: 	    &Apache::lonnet::is_cached_new('dns',$url);
13529: 	if ($cached) {
13530: 	    &$func($content,$hashref);
13531: 	    return;
13532: 	}
13533:     }
13534: 
13535:     my %alldns;
13536:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13537:         foreach my $dns (<$config>) {
13538: 	    next if ($dns !~ /^\^(\S*)/x);
13539:             my $line = $1;
13540:             my ($host,$protocol) = split(/:/,$line);
13541:             if ($protocol ne 'https') {
13542:                 $protocol = 'http';
13543:             }
13544: 	    $alldns{$host} = $protocol;
13545:         }
13546:         close($config);
13547:     }
13548:     while (%alldns) {
13549: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13550: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13551:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13552:         delete($alldns{$dns});
13553: 	next if ($response->is_error());
13554:         if ($url eq '/adm/dns/loncapaCRL') {
13555:             return &$func($response);
13556:         } else {
13557: 	    my @content = split("\n",$response->content);
13558: 	    unless ($nocache) {
13559: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
13560: 	    }
13561: 	    &$func(\@content,$hashref);
13562:             return;
13563:         }
13564:     }
13565:     my $which = (split('/',$url,4))[3];
13566:     if ($which eq 'loncapaCRL') {
13567:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13568:         if (-e $diskfile) {
13569:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
13570:         } else {
13571:             &logthis("unable to contact DNS, no on disk file $diskfile available");
13572:         }
13573:     } else {
13574:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13575:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13576:             my @content = <$config>;
13577:             close($config);
13578:             &$func(\@content,$hashref);
13579:         }
13580:     }
13581:     return;
13582: }
13583: 
13584: # ------------------------------------------------------Get DNS checksums file
13585: sub parse_dns_checksums_tab {
13586:     my ($lines,$hashref) = @_;
13587:     my $lonhost = $perlvar{'lonHostID'};
13588:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13589:     my $loncaparev = &get_server_loncaparev($machine_dom);
13590:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13591:     my $webconfdir = '/etc/httpd/conf';
13592:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13593:         $webconfdir = '/etc/apache2';
13594:     } elsif ($distro =~ /^sles(\d+)$/) {
13595:         if ($1 >= 10) {
13596:             $webconfdir = '/etc/apache2';
13597:         }
13598:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13599:         if ($1 >= 10.0) {
13600:             $webconfdir = '/etc/apache2';
13601:         }
13602:     }
13603:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13604:     my (%chksum,%revnum);
13605:     if (ref($lines) eq 'ARRAY') {
13606:         chomp(@{$lines});
13607:         my $version = shift(@{$lines});
13608:         if ($version eq $release) {  
13609:             foreach my $line (@{$lines}) {
13610:                 my ($file,$version,$shasum) = split(/,/,$line);
13611:                 if ($file =~ m{^/etc/httpd/conf}) {
13612:                     if ($webconfdir eq '/etc/apache2') {
13613:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13614:                     }
13615:                 }
13616:                 $chksum{$file} = $shasum;
13617:                 $revnum{$file} = $version;
13618:             }
13619:             if (ref($hashref) eq 'HASH') {
13620:                 %{$hashref} = (
13621:                                 sums     => \%chksum,
13622:                                 versions => \%revnum,
13623:                               );
13624:             }
13625:         }
13626:     }
13627:     return;
13628: }
13629: 
13630: sub fetch_dns_checksums {
13631:     my %checksums;
13632:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13633:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13634:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13635:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13636:              \%checksums);
13637:     return \%checksums;
13638: }
13639: 
13640: sub fetch_crl_pemfile {
13641:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
13642: }
13643: 
13644: sub save_crl_pem {
13645:     my ($response) = @_;
13646:     my ($msg,$hadchanges);
13647:     if (ref($response)) {
13648:         my $now = time;
13649:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
13650:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
13651:         if (open(my $fh,'>',"$tmpcrl")) {
13652:             print $fh $response->content;
13653:             close($fh);
13654:             if (-e $lonca) {
13655:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
13656:                     my $check = <PIPE>;
13657:                     close(PIPE);
13658:                     chomp($check);
13659:                     if ($check eq 'verify OK') {
13660:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13661:                         my $backup;
13662:                         if (-e $dest) {
13663:                             if (&File::Copy::move($dest,"$dest.bak")) {
13664:                                 $backup = 'ok';
13665:                             }
13666:                         }
13667:                         if (&File::Copy::move($tmpcrl,$dest)) {
13668:                             $msg = 'ok';
13669:                             if ($backup) {
13670:                                 my (%oldnums,%newnums);
13671:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
13672:                                     while (<PIPE>) {
13673:                                         $oldnums{(split(/:/))[1]} = 1;
13674:                                     }
13675:                                     close(PIPE);
13676:                                 }
13677:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
13678:                                     while(<PIPE>) {
13679:                                         $newnums{(split(/:/))[1]} = 1;
13680:                                     }
13681:                                     close(PIPE);
13682:                                 }
13683:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
13684:                                     unless (exists($oldnums{$key})) {
13685:                                         $hadchanges = 1;
13686:                                         last;
13687:                                     }
13688:                                 }
13689:                                 unless ($hadchanges) {
13690:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
13691:                                         unless (exists($newnums{$key})) {
13692:                                             $hadchanges = 1;
13693:                                             last;
13694:                                         }
13695:                                     }
13696:                                 }
13697:                             }
13698:                         }
13699:                     } else {
13700:                         unlink($tmpcrl);
13701:                     }
13702:                 } else {
13703:                     unlink($tmpcrl);
13704:                 }
13705:             } else {
13706:                 unlink($tmpcrl);
13707:             }
13708:         }
13709:     }
13710:     return ($msg,$hadchanges);
13711: }
13712: 
13713: # ------------------------------------------------------------ Read domain file
13714: {
13715:     my $loaded;
13716:     my %domain;
13717: 
13718:     sub parse_domain_tab {
13719: 	my ($lines) = @_;
13720: 	foreach my $line (@$lines) {
13721: 	    next if ($line =~ /^(\#|\s*$ )/x);
13722: 
13723: 	    chomp($line);
13724: 	    my ($name,@elements) = split(/:/,$line,9);
13725: 	    my %this_domain;
13726: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13727: 			       'lang_def', 'city', 'longi', 'lati',
13728: 			       'primary') {
13729: 		$this_domain{$field} = shift(@elements);
13730: 	    }
13731: 	    $domain{$name} = \%this_domain;
13732: 	}
13733:     }
13734: 
13735:     sub reset_domain_info {
13736: 	undef($loaded);
13737: 	undef(%domain);
13738:     }
13739: 
13740:     sub load_domain_tab {
13741: 	my ($ignore_cache,$nocache) = @_;
13742: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13743: 	my $fh;
13744: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13745: 	    my @lines = <$fh>;
13746: 	    &parse_domain_tab(\@lines);
13747: 	}
13748: 	close($fh);
13749: 	$loaded = 1;
13750:     }
13751: 
13752:     sub domain {
13753: 	&load_domain_tab() if (!$loaded);
13754: 
13755: 	my ($name,$what) = @_;
13756: 	return if ( !exists($domain{$name}) );
13757: 
13758: 	if (!$what) {
13759: 	    return $domain{$name}{'description'};
13760: 	}
13761: 	return $domain{$name}{$what};
13762:     }
13763: 
13764:     sub domain_info {
13765:         &load_domain_tab() if (!$loaded);
13766:         return %domain;
13767:     }
13768: 
13769: }
13770: 
13771: 
13772: # ------------------------------------------------------------- Read hosts file
13773: {
13774:     my %hostname;
13775:     my %hostdom;
13776:     my %libserv;
13777:     my $loaded;
13778:     my %name_to_host;
13779:     my %internetdom;
13780:     my %LC_dns_serv;
13781: 
13782:     sub parse_hosts_tab {
13783: 	my ($file) = @_;
13784: 	foreach my $configline (@$file) {
13785: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13786:             chomp($configline);
13787: 	    if ($configline =~ /^\^/) {
13788:                 if ($configline =~ /^\^([\w.\-]+)/) {
13789:                     $LC_dns_serv{$1} = 1;
13790:                 }
13791:                 next;
13792:             }
13793: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13794: 	    $name=~s/\s//g;
13795: 	    if ($id && $domain && $role && $name) {
13796:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13797:                     my $curr = $hostname{$id};
13798:                     my $skip;
13799:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13800:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13801:                             $skip = 1;
13802:                         } else {
13803:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13804:                         }
13805:                     }
13806:                     unless ($skip) {
13807:                         push(@{$name_to_host{$name}},$id);
13808:                     }
13809:                 } else {
13810:                     push(@{$name_to_host{$name}},$id);
13811:                 }
13812: 		$hostname{$id}=$name;
13813: 		$hostdom{$id}=$domain;
13814: 		if ($role eq 'library') { $libserv{$id}=$name; }
13815:                 if (defined($protocol)) {
13816:                     if ($protocol eq 'https') {
13817:                         $protocol{$id} = $protocol;
13818:                     } else {
13819:                         $protocol{$id} = 'http'; 
13820:                     }
13821:                 } else {
13822:                     $protocol{$id} = 'http';
13823:                 }
13824:                 if (defined($intdom)) {
13825:                     $internetdom{$id} = $intdom;
13826:                 }
13827: 	    }
13828: 	}
13829:     }
13830:     
13831:     sub reset_hosts_info {
13832: 	&purge_remembered();
13833: 	&reset_domain_info();
13834: 	&reset_hosts_ip_info();
13835:         undef(%internetdom);
13836: 	undef(%name_to_host);
13837: 	undef(%hostname);
13838: 	undef(%hostdom);
13839: 	undef(%libserv);
13840: 	undef($loaded);
13841:     }
13842: 
13843:     sub load_hosts_tab {
13844: 	my ($ignore_cache,$nocache) = @_;
13845: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13846: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13847: 	my @config = <$config>;
13848: 	&parse_hosts_tab(\@config);
13849: 	close($config);
13850: 	$loaded=1;
13851:     }
13852: 
13853:     sub hostname {
13854: 	&load_hosts_tab() if (!$loaded);
13855: 
13856: 	my ($lonid) = @_;
13857: 	return $hostname{$lonid};
13858:     }
13859: 
13860:     sub all_hostnames {
13861: 	&load_hosts_tab() if (!$loaded);
13862: 
13863: 	return %hostname;
13864:     }
13865: 
13866:     sub all_names {
13867:         my ($ignore_cache,$nocache) = @_;
13868: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13869: 
13870: 	return %name_to_host;
13871:     }
13872: 
13873:     sub all_host_domain {
13874:         &load_hosts_tab() if (!$loaded);
13875:         return %hostdom;
13876:     }
13877: 
13878:     sub all_host_intdom {
13879:         &load_hosts_tab() if (!$loaded);
13880:         return %internetdom;
13881:     }
13882: 
13883:     sub is_library {
13884: 	&load_hosts_tab() if (!$loaded);
13885: 
13886: 	return exists($libserv{$_[0]});
13887:     }
13888: 
13889:     sub all_library {
13890: 	&load_hosts_tab() if (!$loaded);
13891: 
13892: 	return %libserv;
13893:     }
13894: 
13895:     sub unique_library {
13896: 	#2x reverse removes all hostnames that appear more than once
13897:         my %unique = reverse &all_library();
13898:         return reverse %unique;
13899:     }
13900: 
13901:     sub get_servers {
13902: 	&load_hosts_tab() if (!$loaded);
13903: 
13904: 	my ($domain,$type) = @_;
13905: 	my %possible_hosts = ($type eq 'library') ? %libserv
13906: 	                                          : %hostname;
13907: 	my %result;
13908: 	if (ref($domain) eq 'ARRAY') {
13909: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13910: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13911: 		    $result{$host} = $hostname;
13912: 		}
13913: 	    }
13914: 	} else {
13915: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13916: 		if ($hostdom{$host} eq $domain) {
13917: 		    $result{$host} = $hostname;
13918: 		}
13919: 	    }
13920: 	}
13921: 	return %result;
13922:     }
13923: 
13924:     sub get_unique_servers {
13925:         my %unique = reverse &get_servers(@_);
13926: 	return reverse %unique;
13927:     }
13928: 
13929:     sub host_domain {
13930: 	&load_hosts_tab() if (!$loaded);
13931: 
13932: 	my ($lonid) = @_;
13933: 	return $hostdom{$lonid};
13934:     }
13935: 
13936:     sub all_domains {
13937: 	&load_hosts_tab() if (!$loaded);
13938: 
13939: 	my %seen;
13940: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13941: 	return @uniq;
13942:     }
13943: 
13944:     sub internet_dom {
13945:         &load_hosts_tab() if (!$loaded);
13946: 
13947:         my ($lonid) = @_;
13948:         return $internetdom{$lonid};
13949:     }
13950: 
13951:     sub is_LC_dns {
13952:         &load_hosts_tab() if (!$loaded);
13953: 
13954:         my ($hostname) = @_;
13955:         return exists($LC_dns_serv{$hostname});
13956:     }
13957: 
13958: }
13959: 
13960: { 
13961:     my %iphost;
13962:     my %name_to_ip;
13963:     my %lonid_to_ip;
13964: 
13965:     sub get_hosts_from_ip {
13966: 	my ($ip) = @_;
13967: 	my %iphosts = &get_iphost();
13968: 	if (ref($iphosts{$ip})) {
13969: 	    return @{$iphosts{$ip}};
13970: 	}
13971: 	return;
13972:     }
13973:     
13974:     sub reset_hosts_ip_info {
13975: 	undef(%iphost);
13976: 	undef(%name_to_ip);
13977: 	undef(%lonid_to_ip);
13978:     }
13979: 
13980:     sub get_host_ip {
13981: 	my ($lonid) = @_;
13982: 	if (exists($lonid_to_ip{$lonid})) {
13983: 	    return $lonid_to_ip{$lonid};
13984: 	}
13985: 	my $name=&hostname($lonid);
13986:    	my $ip = gethostbyname($name);
13987: 	return if (!$ip || length($ip) ne 4);
13988: 	$ip=inet_ntoa($ip);
13989: 	$name_to_ip{$name}   = $ip;
13990: 	$lonid_to_ip{$lonid} = $ip;
13991: 	return $ip;
13992:     }
13993:     
13994:     sub get_iphost {
13995: 	my ($ignore_cache,$nocache) = @_;
13996: 
13997: 	if (!$ignore_cache) {
13998: 	    if (%iphost) {
13999: 		return %iphost;
14000: 	    }
14001: 	    my ($ip_info,$cached)=
14002: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14003: 	    if ($cached) {
14004: 		%iphost      = %{$ip_info->[0]};
14005: 		%name_to_ip  = %{$ip_info->[1]};
14006: 		%lonid_to_ip = %{$ip_info->[2]};
14007: 		return %iphost;
14008: 	    }
14009: 	}
14010: 
14011: 	# get yesterday's info for fallback
14012: 	my %old_name_to_ip;
14013: 	my ($ip_info,$cached)=
14014: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14015: 	if ($cached) {
14016: 	    %old_name_to_ip = %{$ip_info->[1]};
14017: 	}
14018: 
14019: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14020: 	foreach my $name (keys(%name_to_host)) {
14021: 	    my $ip;
14022: 	    if (!exists($name_to_ip{$name})) {
14023: 		$ip = gethostbyname($name);
14024: 		if (!$ip || length($ip) ne 4) {
14025: 		    if (defined($old_name_to_ip{$name})) {
14026: 			$ip = $old_name_to_ip{$name};
14027: 			&logthis("Can't find $name defaulting to old $ip");
14028: 		    } else {
14029: 			&logthis("Name $name no IP found");
14030: 			next;
14031: 		    }
14032: 		} else {
14033: 		    $ip=inet_ntoa($ip);
14034: 		}
14035: 		$name_to_ip{$name} = $ip;
14036: 	    } else {
14037: 		$ip = $name_to_ip{$name};
14038: 	    }
14039: 	    foreach my $id (@{ $name_to_host{$name} }) {
14040: 		$lonid_to_ip{$id} = $ip;
14041: 	    }
14042: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14043: 	}
14044:         unless ($nocache) {
14045: 	    &do_cache_new('iphost','iphost',
14046: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14047: 		          48*60*60);
14048:         }
14049: 
14050: 	return %iphost;
14051:     }
14052: 
14053:     #
14054:     #  Given a DNS returns the loncapa host name for that DNS 
14055:     # 
14056:     sub host_from_dns {
14057:         my ($dns) = @_;
14058:         my @hosts;
14059:         my $ip;
14060: 
14061:         if (exists($name_to_ip{$dns})) {
14062:             $ip = $name_to_ip{$dns};
14063:         }
14064:         if (!$ip) {
14065:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14066:             if (length($ip) == 4) { 
14067: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14068:             }
14069:         }
14070:         if ($ip) {
14071: 	    @hosts = get_hosts_from_ip($ip);
14072: 	    return $hosts[0];
14073:         }
14074:         return undef;
14075:     }
14076: 
14077:     sub get_internet_names {
14078:         my ($lonid) = @_;
14079:         return if ($lonid eq '');
14080:         my ($idnref,$cached)=
14081:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14082:         if ($cached) {
14083:             return $idnref;
14084:         }
14085:         my $ip = &get_host_ip($lonid);
14086:         my @hosts = &get_hosts_from_ip($ip);
14087:         my %iphost = &get_iphost();
14088:         my (@idns,%seen);
14089:         foreach my $id (@hosts) {
14090:             my $dom = &host_domain($id);
14091:             my $prim_id = &domain($dom,'primary');
14092:             my $prim_ip = &get_host_ip($prim_id);
14093:             next if ($seen{$prim_ip});
14094:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14095:                 foreach my $id (@{$iphost{$prim_ip}}) {
14096:                     my $intdom = &internet_dom($id);
14097:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14098:                         push(@idns,$intdom);
14099:                     }
14100:                 }
14101:             }
14102:             $seen{$prim_ip} = 1;
14103:         }
14104:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14105:     }
14106: 
14107: }
14108: 
14109: sub all_loncaparevs {
14110:     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);
14111: }
14112: 
14113: # ---------------------------------------------------------- Read loncaparev table
14114: {
14115:     sub load_loncaparevs { 
14116:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14117:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14118:                 while (my $configline=<$config>) {
14119:                     chomp($configline);
14120:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14121:                     $loncaparevs{$hostid}=$loncaparev;
14122:                 }
14123:                 close($config);
14124:             }
14125:         }
14126:     }
14127: }
14128: 
14129: # ---------------------------------------------------------- Read serverhostID table
14130: {
14131:     sub load_serverhomeIDs {
14132:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14133:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14134:                 while (my $configline=<$config>) {
14135:                     chomp($configline);
14136:                     my ($name,$id)=split(/:/,$configline);
14137:                     $serverhomeIDs{$name}=$id;
14138:                 }
14139:                 close($config);
14140:             }
14141:         }
14142:     }
14143: }
14144: 
14145: 
14146: BEGIN {
14147: 
14148: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14149:     unless ($readit) {
14150: {
14151:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14152:     %perlvar = (%perlvar,%{$configvars});
14153: }
14154: 
14155: 
14156: # ------------------------------------------------------ Read spare server file
14157: {
14158:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14159: 
14160:     while (my $configline=<$config>) {
14161:        chomp($configline);
14162:        if ($configline) {
14163: 	   my ($host,$type) = split(':',$configline,2);
14164: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14165: 	   push(@{ $spareid{$type} }, $host);
14166:        }
14167:     }
14168:     close($config);
14169: }
14170: # ------------------------------------------------------------ Read permissions
14171: {
14172:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14173: 
14174:     while (my $configline=<$config>) {
14175: 	chomp($configline);
14176: 	if ($configline) {
14177: 	    my ($role,$perm)=split(/ /,$configline);
14178: 	    if ($perm ne '') { $pr{$role}=$perm; }
14179: 	}
14180:     }
14181:     close($config);
14182: }
14183: 
14184: # -------------------------------------------- Read plain texts for permissions
14185: {
14186:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14187: 
14188:     while (my $configline=<$config>) {
14189: 	chomp($configline);
14190: 	if ($configline) {
14191: 	    my ($short,@plain)=split(/:/,$configline);
14192:             %{$prp{$short}} = ();
14193: 	    if (@plain > 0) {
14194:                 $prp{$short}{'std'} = $plain[0];
14195:                 for (my $i=1; $i<@plain; $i++) {
14196:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14197:                 }
14198:             }
14199: 	}
14200:     }
14201:     close($config);
14202: }
14203: 
14204: # ---------------------------------------------------------- Read package table
14205: {
14206:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14207: 
14208:     while (my $configline=<$config>) {
14209: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14210: 	chomp($configline);
14211: 	my ($short,$plain)=split(/:/,$configline);
14212: 	my ($pack,$name)=split(/\&/,$short);
14213: 	if ($plain ne '') {
14214: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14215: 	    $packagetab{$short}=$plain; 
14216: 	}
14217:     }
14218:     close($config);
14219: }
14220: 
14221: # ---------------------------------------------------------- Read loncaparev table
14222: 
14223: &load_loncaparevs();
14224: 
14225: # ---------------------------------------------------------- Read serverhostID table
14226: 
14227: &load_serverhomeIDs();
14228: 
14229: # ---------------------------------------------------------- Read releaseslist XML
14230: {
14231:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14232:     if (-e $file) {
14233:         my $parser = HTML::LCParser->new($file);
14234:         while (my $token = $parser->get_token()) {
14235:             if ($token->[0] eq 'S') {
14236:                 my $item = $token->[1];
14237:                 my $name = $token->[2]{'name'};
14238:                 my $value = $token->[2]{'value'};
14239:                 my $valuematch = $token->[2]{'valuematch'};
14240:                 my $namematch = $token->[2]{'namematch'};
14241:                 if ($item eq 'parameter') {
14242:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14243:                         my $release = $parser->get_text();
14244:                         $release =~ s/(^\s*|\s*$ )//gx;
14245:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14246:                     }
14247:                 } elsif ($item ne '' && $name ne '') {
14248:                     my $release = $parser->get_text();
14249:                     $release =~ s/(^\s*|\s*$ )//gx;
14250:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14251:                 }
14252:             }
14253:         }
14254:     }
14255: }
14256: 
14257: # ---------------------------------------------------------- Read managers table
14258: {
14259:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14260:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14261:             while (my $configline=<$config>) {
14262:                 chomp($configline);
14263:                 next if ($configline =~ /^\#/);
14264:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14265:                     $managerstab{$configline} = 1;
14266:                 }
14267:             }
14268:             close($config);
14269:         }
14270:     }
14271: }
14272: 
14273: # ------------- set up temporary directory
14274: {
14275:     $tmpdir = LONCAPA::tempdir();
14276: 
14277: }
14278: 
14279: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14280: 				'compress_threshold'=> 20_000,
14281:  			        });
14282: 
14283: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14284: $dumpcount=0;
14285: $locknum=0;
14286: 
14287: &logtouch();
14288: &logthis('<font color="yellow">INFO: Read configuration</font>');
14289: $readit=1;
14290:     {
14291: 	use integer;
14292: 	my $test=(2**32)+1;
14293: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14294: 	&logthis(" Detected 64bit platform ($_64bit)");
14295:     }
14296: }
14297: }
14298: 
14299: 1;
14300: __END__
14301: 
14302: =pod
14303: 
14304: =head1 NAME
14305: 
14306: Apache::lonnet - Subroutines to ask questions about things in the network.
14307: 
14308: =head1 SYNOPSIS
14309: 
14310: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14311: 
14312:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14313: 
14314: Common parameters:
14315: 
14316: =over 4
14317: 
14318: =item *
14319: 
14320: $uname : an internal username (if $cname expecting a course Id specifically)
14321: 
14322: =item *
14323: 
14324: $udom : a domain (if $cdom expecting a course's domain specifically)
14325: 
14326: =item *
14327: 
14328: $symb : a resource instance identifier
14329: 
14330: =item *
14331: 
14332: $namespace : the name of a .db file that contains the data needed or
14333: being set.
14334: 
14335: =back
14336: 
14337: =head1 OVERVIEW
14338: 
14339: lonnet provides subroutines which interact with the
14340: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14341: about classes, users, and resources.
14342: 
14343: For many of these objects you can also use this to store data about
14344: them or modify them in various ways.
14345: 
14346: =head2 Symbs
14347: 
14348: To identify a specific instance of a resource, LON-CAPA uses symbols
14349: or "symbs"X<symb>. These identifiers are built from the URL of the
14350: map, the resource number of the resource in the map, and the URL of
14351: the resource itself. The latter is somewhat redundant, but might help
14352: if maps change.
14353: 
14354: An example is
14355: 
14356:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14357: 
14358: The respective map entry is
14359: 
14360:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14361:   title="Problem 2">
14362:  </resource>
14363: 
14364: Symbs are used by the random number generator, as well as to store and
14365: restore data specific to a certain instance of for example a problem.
14366: 
14367: =head2 Storing And Retrieving Data
14368: 
14369: X<store()>X<cstore()>X<restore()>Three of the most important functions
14370: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14371: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14372: is is the non-critical message twin of cstore. These functions are for
14373: handlers to store a perl hash to a user's permanent data space in an
14374: easy manner, and to retrieve it again on another call. It is expected
14375: that a handler would use this once at the beginning to retrieve data,
14376: and then again once at the end to send only the new data back.
14377: 
14378: The data is stored in the user's data directory on the user's
14379: homeserver under the ID of the course.
14380: 
14381: The hash that is returned by restore will have all of the previous
14382: value for all of the elements of the hash.
14383: 
14384: Example:
14385: 
14386:  #creating a hash
14387:  my %hash;
14388:  $hash{'foo'}='bar';
14389: 
14390:  #storing it
14391:  &Apache::lonnet::cstore(\%hash);
14392: 
14393:  #changing a value
14394:  $hash{'foo'}='notbar';
14395: 
14396:  #adding a new value
14397:  $hash{'bar'}='foo';
14398:  &Apache::lonnet::cstore(\%hash);
14399: 
14400:  #retrieving the hash
14401:  my %history=&Apache::lonnet::restore();
14402: 
14403:  #print the hash
14404:  foreach my $key (sort(keys(%history))) {
14405:    print("\%history{$key} = $history{$key}");
14406:  }
14407: 
14408: Will print out:
14409: 
14410:  %history{1:foo} = bar
14411:  %history{1:keys} = foo:timestamp
14412:  %history{1:timestamp} = 990455579
14413:  %history{2:bar} = foo
14414:  %history{2:foo} = notbar
14415:  %history{2:keys} = foo:bar:timestamp
14416:  %history{2:timestamp} = 990455580
14417:  %history{bar} = foo
14418:  %history{foo} = notbar
14419:  %history{timestamp} = 990455580
14420:  %history{version} = 2
14421: 
14422: Note that the special hash entries C<keys>, C<version> and
14423: C<timestamp> were added to the hash. C<version> will be equal to the
14424: total number of versions of the data that have been stored. The
14425: C<timestamp> attribute will be the UNIX time the hash was
14426: stored. C<keys> is available in every historical section to list which
14427: keys were added or changed at a specific historical revision of a
14428: hash.
14429: 
14430: B<Warning>: do not store the hash that restore returns directly. This
14431: will cause a mess since it will restore the historical keys as if the
14432: were new keys. I.E. 1:foo will become 1:1:foo etc.
14433: 
14434: Calling convention:
14435: 
14436:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14437:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14438: 
14439: For more detailed information, see lonnet specific documentation.
14440: 
14441: =head1 RETURN MESSAGES
14442: 
14443: =over 4
14444: 
14445: =item * B<con_lost>: unable to contact remote host
14446: 
14447: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14448: when the connection is brought back up
14449: 
14450: =item * B<con_failed>: unable to contact remote host and unable to save message
14451: for later delivery
14452: 
14453: =item * B<error:>: an error a occurred, a description of the error follows the :
14454: 
14455: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14456: that was requested
14457: 
14458: =back
14459: 
14460: =head1 PUBLIC SUBROUTINES
14461: 
14462: =head2 Session Environment Functions
14463: 
14464: =over 4
14465: 
14466: =item * 
14467: X<appenv()>
14468: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14469: the user envirnoment file, and will be restored for each access this
14470: user makes during this session, also modifies the %env for the current
14471: process. Optional rolesarrayref - if defined contains a reference to an array
14472: of roles which are exempt from the restriction on modifying user.role entries 
14473: in the user's environment.db and in %env.    
14474: 
14475: =item *
14476: X<delenv()>
14477: B<delenv($delthis,$regexp)>: removes all items from the session
14478: environment file that begin with $delthis. If the 
14479: optional second arg - $regexp - is true, $delthis is treated as a 
14480: regular expression, otherwise \Q$delthis\E is used. 
14481: The values are also deleted from the current processes %env.
14482: 
14483: =item * get_env_multiple($name) 
14484: 
14485: gets $name from the %env hash, it seemlessly handles the cases where multiple
14486: values may be defined and end up as an array ref.
14487: 
14488: returns an array of values
14489: 
14490: =back
14491: 
14492: =head2 User Information
14493: 
14494: =over 4
14495: 
14496: =item *
14497: X<queryauthenticate()>
14498: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14499: authentication scheme
14500: 
14501: =item *
14502: X<authenticate()>
14503: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14504: authenticate user from domain's lib servers (first use the current
14505: one). C<$upass> should be the users password.
14506: $checkdefauth is optional (value is 1 if a check should be made to
14507:    authenticate user using default authentication method, and allow
14508:    account creation if username does not have account in the domain).
14509: $clientcancheckhost is optional (value is 1 if checking whether the
14510:    server can host will occur on the client side in lonauth.pm).   
14511: 
14512: =item *
14513: X<homeserver()>
14514: B<homeserver($uname,$udom)>: find the server which has
14515: the user's directory and files (there must be only one), this caches
14516: the answer, and also caches if there is a borken connection.
14517: 
14518: =item *
14519: X<idget()>
14520: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14521: a list of student/employee IDs or clicker IDs
14522: (student/employee IDs are a unique resource in a domain, there must be 
14523: only 1 ID per username, and only 1 username per ID in a specific domain).
14524: clickerIDs are not necessarily unique, as students might share clickers.
14525: (returns hash: id=>name,id=>name)
14526: 
14527: =item *
14528: X<idrget()>
14529: B<idrget($udom,@unames)>: find the IDs behind a list of
14530: usernames (returns hash: name=>id,name=>id)
14531: 
14532: =item *
14533: X<idput()>
14534: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14535: names and associated student/employee IDs or clicker IDs.
14536: 
14537: =item *
14538: X<iddel()>
14539: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14540: student/employee ID or clicker ID username look-ups from domain.
14541: The homeserver ($uhome) and namespace ($namespace) are optional.
14542: If no $uhome is provided, it will be determined usig &homeserver()
14543: for each user.  If no $namespace is provided, the default is ids.
14544: 
14545: =item *
14546: X<updateclickers()>
14547: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14548: clicker ID-to-username look-ups in clickers.db on library server.
14549: Permitted actions are add or del (i.e., add or delete). The 
14550: clickers.db contains clickerID as keys (escaped), and each corresponding
14551: value is an escaped comma-separated list of usernames (for whom the
14552: library server is the homeserver), who registered that particular ID.
14553: If $critical is true, the update will be sent via &critical, otherwise
14554: &reply() will be used.
14555: 
14556: =item *
14557: X<rolesinit()>
14558: B<rolesinit($udom,$username)>: get user privileges.
14559: returns user role, first access and timer interval hashes
14560: 
14561: =item *
14562: X<privileged()>
14563: B<privileged($username,$domain)>: returns a true if user has a
14564: privileged and active role (i.e. su or dc), false otherwise.
14565: 
14566: =item *
14567: X<getsection()>
14568: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14569: course $cname, return section name/number or '' for "not in course"
14570: and '-1' for "no section"
14571: 
14572: =item *
14573: X<userenvironment()>
14574: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14575: passed in @what from the requested user's environment, returns a hash
14576: 
14577: =item * 
14578: X<userlog_query()>
14579: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14580: activity.log file. %filters defines filters applied when parsing the
14581: log file. These can be start or end timestamps, or the type of action
14582: - log to look for Login or Logout events, check for Checkin or
14583: Checkout, role for role selection. The response is in the form
14584: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14585: escaped strings of the action recorded in the activity.log file.
14586: 
14587: =back
14588: 
14589: =head2 User Roles
14590: 
14591: =over 4
14592: 
14593: =item *
14594: 
14595: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14596: returns codes for allowed actions.
14597: 
14598: The first argument is required, all others are optional.
14599: 
14600: $priv is the privilege being checked.
14601: $uri contains additional information about what is being checked for access (e.g.,
14602: URL, course ID etc.). 
14603: $symb is the unique resource instance identifier in a course; if needed,
14604: but not provided, it will be retrieved via a call to &symbread(). 
14605: $role is the role for which a priv is being checked (only used if priv is evb). 
14606: $clientip is the user's IP address (only used when checking for access to portfolio 
14607: files).
14608: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14609: prevents recursive calls to &allowed.
14610: 
14611:  F: full access
14612:  U,I,K: authentication modes (cxx only)
14613:  '': forbidden
14614:  1: user needs to choose course
14615:  2: browse allowed
14616:  A: passphrase authentication needed
14617:  B: access temporarily blocked because of a blocking event in a course.
14618: 
14619: =item *
14620: 
14621: constructaccess($url,$setpriv) : check for access to construction space URL
14622: 
14623: See if the owner domain and name in the URL match those in the
14624: expected environment.  If so, return three element list
14625: ($ownername,$ownerdomain,$ownerhome).
14626: 
14627: Otherwise return the null string.
14628: 
14629: If second argument 'setpriv' is true, it assigns the privileges,
14630: and returns the same three element list, unless the owner has
14631: blocked "ad hoc" Domain Coordinator access to the Author Space,
14632: in which case the null string is returned.
14633: 
14634: =item *
14635: 
14636: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14637: define a custom role rolename set privileges in format of lonTabs/roles.tab
14638: for system, domain, and course level. $uname and $udom are optional (current
14639: user's username and domain will be used when either of $uname or $udom are absent.
14640: 
14641: =item *
14642: 
14643: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14644: (rolesplain.tab); plain text explanation of a user role term.
14645: $type is Course (default) or Community.
14646: If $forcedefault evaluates to true, text returned will be default 
14647: text for $type. Otherwise, if this is a course, the text returned 
14648: will be a custom name for the role (if defined in the course's 
14649: environment).  If no custom name is defined the default is returned.
14650:    
14651: =item *
14652: 
14653: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14654: All arguments are optional. Returns a hash of a roles, either for
14655: co-author/assistant author roles for a user's Construction Space
14656: (default), or if $context is 'userroles', roles for the user himself,
14657: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14658: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14659: For each key, value is set to colon-separated start and end times for
14660: the role.  If no username and domain are specified, will default to
14661: current user/domain. Types, roles, and roledoms are references to arrays
14662: of role statuses (active, future or previous), roles 
14663: (e.g., cc,in, st etc.) and domains of the roles which can be used
14664: to restrict the list of roles reported. If no array ref is 
14665: provided for types, will default to return only active roles.
14666: 
14667: =item *
14668: 
14669: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14670: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14671: 
14672: Additional optional arguments are: $type (if role checking is to be restricted 
14673: to certain user status types -- previous (expired roles), active (currently
14674: available roles) or future (roles available in the future), and
14675: $hideprivileged -- if true will not report course roles for users who
14676: have active Domain Coordinator role in course's domain or in additional
14677: domains (specified in 'Domains to check for privileged users' in course
14678: environment -- set via:  Course Settings -> Classlists and staff listing).
14679: 
14680: =item *
14681: 
14682: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14683: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14684: $possdomains and $possroles are optional array refs -- to domains to check and
14685: roles to check.  If $possdomains is not specified, a dump will be done of the
14686: users' roles.db to check for a dc or su role in any domain. This can be
14687: time consuming if &privileged is called repeatedly (e.g., when displaying a
14688: classlist), so in such cases, supplying a $possdomains array is preferred, as
14689: this then allows &privileged_by_domain() to be used, which caches the identity
14690: of privileged users, eliminating the need for repeated calls to &dump().
14691: 
14692: =item *
14693: 
14694: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14695: where the outer hash keys are domains specified in the $possdomains array ref,
14696: next inner hash keys are privileged roles specified in the $roles array ref,
14697: and the innermost hash contains key = value pairs for username:domain = end:start
14698: for active or future "privileged" users with that role in that domain. To avoid
14699: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14700: innerhash are cached using priv_$role and $dom as the identifiers.
14701: 
14702: =back
14703: 
14704: =head2 User Modification
14705: 
14706: =over 4
14707: 
14708: =item *
14709: 
14710: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14711: user for the level given by URL.  Optional start and end dates (leave empty
14712: string or zero for "no date")
14713: 
14714: =item *
14715: 
14716: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14717: change a users, password, possible return values are: ok,
14718: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14719: refused
14720: 
14721: =item *
14722: 
14723: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14724: 
14725: =item *
14726: 
14727: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14728:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14729: 
14730: will update user information (firstname,middlename,lastname,generation,
14731: permanentemail), and if forceid is true, student/employee ID also.
14732: A user's institutional affiliation(s) can also be updated.
14733: User information fields will not be overwritten with empty entries 
14734: unless the field is included in the $candelete array reference.
14735: This array is included when a single user is modified via "Manage Users",
14736: or when Autoupdate.pl is run by cron in a domain.
14737: 
14738: =item *
14739: 
14740: modifystudent
14741: 
14742: modify a student's enrollment and identification information.
14743: The course id is resolved based on the current user's environment.  
14744: This means the invoking user must be a course coordinator or otherwise
14745: associated with a course.
14746: 
14747: This call is essentially a wrapper for lonnet::modifyuser and
14748: lonnet::modify_student_enrollment
14749: 
14750: Inputs: 
14751: 
14752: =over 4
14753: 
14754: =item B<$udom> Student's loncapa domain
14755: 
14756: =item B<$uname> Student's loncapa login name
14757: 
14758: =item B<$uid> Student/Employee ID
14759: 
14760: =item B<$umode> Student's authentication mode
14761: 
14762: =item B<$upass> Student's password
14763: 
14764: =item B<$first> Student's first name
14765: 
14766: =item B<$middle> Student's middle name
14767: 
14768: =item B<$last> Student's last name
14769: 
14770: =item B<$gene> Student's generation
14771: 
14772: =item B<$usec> Student's section in course
14773: 
14774: =item B<$end> Unix time of the roles expiration
14775: 
14776: =item B<$start> Unix time of the roles start date
14777: 
14778: =item B<$forceid> If defined, allow $uid to be changed
14779: 
14780: =item B<$desiredhome> server to use as home server for student
14781: 
14782: =item B<$email> Student's permanent e-mail address
14783: 
14784: =item B<$type> Type of enrollment (auto or manual)
14785: 
14786: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14787: 
14788: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14789: 
14790: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14791: 
14792: =item B<$context> role change context (shown in User Management Logs display in a course)
14793: 
14794: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14795: 
14796: =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.
14797: 
14798: =back
14799: 
14800: =item *
14801: 
14802: modify_student_enrollment
14803: 
14804: Change a student's enrollment status in a class.  The environment variable
14805: 'role.request.course' must be defined for this function to proceed.
14806: 
14807: Inputs:
14808: 
14809: =over 4
14810: 
14811: =item $udom, student's domain
14812: 
14813: =item $uname, student's name
14814: 
14815: =item $uid, student's user id
14816: 
14817: =item $first, student's first name
14818: 
14819: =item $middle
14820: 
14821: =item $last
14822: 
14823: =item $gene
14824: 
14825: =item $usec
14826: 
14827: =item $end
14828: 
14829: =item $start
14830: 
14831: =item $type
14832: 
14833: =item $locktype
14834: 
14835: =item $cid
14836: 
14837: =item $selfenroll
14838: 
14839: =item $context
14840: 
14841: =item $credits, number of credits student will earn from this class
14842: 
14843: =item $instsec, institutional course section code for student
14844: 
14845: =back
14846: 
14847: 
14848: =item *
14849: 
14850: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14851: custom role; give a custom role to a user for the level given by URL.  Specify
14852: name and domain of role author, and role name
14853: 
14854: =item *
14855: 
14856: revokerole($udom,$uname,$url,$role) : revoke a role for url
14857: 
14858: =item *
14859: 
14860: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14861: 
14862: =back
14863: 
14864: =head2 Course Infomation
14865: 
14866: =over 4
14867: 
14868: =item *
14869: 
14870: coursedescription($courseid,$options) : returns a hash of information about the
14871: specified course id, including all environment settings for the
14872: course, the description of the course will be in the hash under the
14873: key 'description'
14874: 
14875: $options is an optional parameter that if supplied is a hash reference that controls
14876: what how this function works.  It has the following key/values:
14877: 
14878: =over 4
14879: 
14880: =item freshen_cache
14881: 
14882: If defined, and the environment cache for the course is valid, it is 
14883: returned in the returned hash.
14884: 
14885: =item one_time
14886: 
14887: If defined, the last cache time is set to _now_
14888: 
14889: =item user
14890: 
14891: If defined, the supplied username is used instead of the current user.
14892: 
14893: 
14894: =back
14895: 
14896: =item *
14897: 
14898: resdata($name,$domain,$type,@which) : request for current parameter
14899: setting for a specific $type, where $type is either 'course' or 'user',
14900: @what should be a list of parameters to ask about. This routine caches
14901: answers for 10 minutes.
14902: 
14903: =item *
14904: 
14905: get_courseresdata($courseid, $domain) : dump the entire course resource
14906: data base, returning a hash that is keyed by the resource name and has
14907: values that are the resource value.  I believe that the timestamps and
14908: versions are also returned.
14909: 
14910: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14911: supplemental content area. This routine caches the number of files for 
14912: 10 minutes.
14913: 
14914: =back
14915: 
14916: =head2 Course Modification
14917: 
14918: =over 4
14919: 
14920: =item *
14921: 
14922: writecoursepref($courseid,%prefs) : write preferences (environment
14923: database) for a course
14924: 
14925: =item *
14926: 
14927: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14928: 
14929: =item *
14930: 
14931: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14932: 
14933: =item *
14934: 
14935: is_course($courseid), is_course($cdom, $cnum)
14936: 
14937: Accepts either a combined $courseid (in the form of domain_courseid) or the
14938: two component version $cdom, $cnum. It checks if the specified course exists.
14939: 
14940: Returns:
14941:     undef if the course doesn't exist, otherwise
14942:     in scalar context the combined courseid.
14943:     in list context the two components of the course identifier, domain and 
14944:     courseid.    
14945: 
14946: =back
14947: 
14948: =head2 Resource Subroutines
14949: 
14950: =over 4
14951: 
14952: =item *
14953: 
14954: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14955: 
14956: =item *
14957: 
14958: repcopy($filename) : subscribes to the requested file, and attempts to
14959: replicate from the owning library server, Might return
14960: 'unavailable', 'not_found', 'forbidden', 'ok', or
14961: 'bad_request', also attempts to grab the metadata for the
14962: resource. Expects the local filesystem pathname
14963: (/home/httpd/html/res/....)
14964: 
14965: =back
14966: 
14967: =head2 Resource Information
14968: 
14969: =over 4
14970: 
14971: =item *
14972: 
14973: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14974: and returns the value of a variety of different possible values,
14975: $varname should be a request string, and the other parameters can be
14976: used to specify who and what one is asking about. Ordinarily, $cid 
14977: does not need to be specified, as it is retrived from 
14978: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14979: within lonuserstate::loadmap() when initializing a course, before
14980: $env{'request.course.id'} has been set, so it needs to be provided
14981: in that one case.
14982: 
14983: Possible values for $varname are environment.lastname (or other item
14984: from the envirnment hash), user.name (or someother aspect about the
14985: user), resource.0.maxtries (or some other part and parameter of a
14986: resource)
14987: 
14988: =item *
14989: 
14990: directcondval($number) : get current value of a condition; reads from a state
14991: string
14992: 
14993: =item *
14994: 
14995: condval($condidx) : value of condition index based on state
14996: 
14997: =item *
14998: 
14999: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15000: resource's metadata, $what should be either a specific key, or either
15001: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15002: packages that this resource currently uses, the last 3 arguments are 
15003: only used internally for recursive metadata.
15004: 
15005: the toolsymb is only used where the uri is for an external tool (for which
15006: the uri as well as the symb are guaranteed to be unique).
15007: 
15008: this function automatically caches all requests except any made recursively
15009: to retrieve a list of metadata keys for an imported library file ($liburi is 
15010: defined).
15011: 
15012: =item *
15013: 
15014: metadata_query($query,$custom,$customshow) : make a metadata query against the
15015: network of library servers; returns file handle of where SQL and regex results
15016: will be stored for query
15017: 
15018: =item *
15019: 
15020: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15021: return symbolic list entry (all arguments optional). 
15022: 
15023: Args: filename is the filename (including path) for the file for which a symb 
15024: is required; donotrecurse, if true will prevent calls to allowed() being made 
15025: to check access status if more than one resource was found in the bighash 
15026: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15027: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15028: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15029: cause possible symbs to be checked to determine if they are subject to content
15030: blocking, if so they will not be included as possible symbs; possibles is a
15031: ref to a hash, which, as a side effect, will be populated with all possible 
15032: symbs (content blocking not tested).
15033:  
15034: returns the data handle
15035: 
15036: =item *
15037: 
15038: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15039: and is a possible symb for the URL in $thisfn, and if is an encrypted
15040: resource that the user accessed using /enc/ returns a 1 on success, 0
15041: on failure, user must be in a course, as it assumes the existence of
15042: the course initial hash, and uses $env('request.course.id'}.  The third
15043: arg is an optional reference to a scalar.  If this arg is passed in the 
15044: call to symbverify, it will be set to 1 if the symb has been set to be 
15045: encrypted; otherwise it will be null.  
15046: 
15047: =item *
15048: 
15049: symbclean($symb) : removes versions numbers from a symb, returns the
15050: cleaned symb
15051: 
15052: =item *
15053: 
15054: is_on_map($uri) : checks if the $uri is somewhere on the current
15055: course map, user must be in a course for it to work.
15056: 
15057: =item *
15058: 
15059: numval($salt) : return random seed value (addend for rndseed)
15060: 
15061: =item *
15062: 
15063: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15064: a random seed, all arguments are optional, if they aren't sent it uses the
15065: environment to derive them. Note: if symb isn't sent and it can't get one
15066: from &symbread it will use the current time as its return value
15067: 
15068: =item *
15069: 
15070: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15071: unfakeable, receipt
15072: 
15073: =item *
15074: 
15075: receipt() : API to ireceipt working off of env values; given out to users
15076: 
15077: =item *
15078: 
15079: countacc($url) : count the number of accesses to a given URL
15080: 
15081: =item *
15082: 
15083: 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
15084: 
15085: =item *
15086: 
15087: 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)
15088: 
15089: =item *
15090: 
15091: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15092: 
15093: =item *
15094: 
15095: devalidate($symb) : devalidate temporary spreadsheet calculations,
15096: forcing spreadsheet to reevaluate the resource scores next time.
15097: 
15098: =item * 
15099: 
15100: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15101: when viewing in course context.
15102: 
15103:  input: six args -- filename (decluttered), course number, course domain,
15104:                     url, symb (if registered) and group (if this is a 
15105:                     group item -- e.g., bulletin board, group page etc.).
15106: 
15107:  output: array of five scalars --
15108:          $cfile -- url for file editing if editable on current server
15109:          $home -- homeserver of resource (i.e., for author if published,
15110:                                           or course if uploaded.).
15111:          $switchserver --  1 if server switch will be needed.
15112:          $forceedit -- 1 if icon/link should be to go to edit mode 
15113:          $forceview -- 1 if icon/link should be to go to view mode
15114: 
15115: =item *
15116: 
15117: is_course_upload($file,$cnum,$cdom)
15118: 
15119: Used in course context to determine if current file was uploaded to 
15120: the course (i.e., would be found in /userfiles/docs on the course's 
15121: homeserver.
15122: 
15123:   input: 3 args -- filename (decluttered), course number and course domain.
15124:   output: boolean -- 1 if file was uploaded.
15125: 
15126: =back
15127: 
15128: =head2 Storing/Retreiving Data
15129: 
15130: =over 4
15131: 
15132: =item *
15133: 
15134: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15135: permanently for this url; hashref needs to be given and should be a \%hashname;
15136: the remaining args aren't required and if they aren't passed or are '' they will
15137: be derived from the env (with the exception of $laststore, which is an 
15138: optional arg used when a user's submission is stored in grading).
15139: $laststore is $version=$timestamp, where $version is the most recent version
15140: number retrieved for the corresponding $symb in the $namespace db file, and
15141: $timestamp is the timestamp for that transaction (UNIX time).
15142: $laststore is currently only passed when cstore() is called by 
15143: structuretags::finalize_storage().
15144: 
15145: =item *
15146: 
15147: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15148: but uses critical subroutine
15149: 
15150: =item *
15151: 
15152: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15153: all args are optional
15154: 
15155: =item *
15156: 
15157: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15158: dumps the complete (or key matching regexp) namespace into a hash
15159: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15160: normally &store()ed into
15161: 
15162: $range should be either an integer '100' (give me the first 100
15163:                                            matching records)
15164:               or be  two integers sperated by a - with no spaces
15165:                  '30-50' (give me the 30th through the 50th matching
15166:                           records)
15167: 
15168: 
15169: =item *
15170: 
15171: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15172: replaces a &store() version of data with a replacement set of data
15173: for a particular resource in a namespace passed in the $storehash hash 
15174: reference. If $tolog is true, the transaction is logged in the courselog
15175: with an action=PUTSTORE.
15176: 
15177: =item *
15178: 
15179: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15180: works very similar to store/cstore, but all data is stored in a
15181: temporary location and can be reset using tmpreset, $storehash should
15182: be a hash reference, returns nothing on success
15183: 
15184: =item *
15185: 
15186: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15187: similar to restore, but all data is stored in a temporary location and
15188: can be reset using tmpreset. Returns a hash of values on success,
15189: error string otherwise.
15190: 
15191: =item *
15192: 
15193: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15194: deltes all keys for $symb form the temporary storage hash.
15195: 
15196: =item *
15197: 
15198: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15199: reference filled in from namesp ($udom and $uname are optional)
15200: 
15201: =item *
15202: 
15203: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15204: namesp ($udom and $uname are optional)
15205: 
15206: =item *
15207: 
15208: dump($namespace,$udom,$uname,$regexp,$range) : 
15209: dumps the complete (or key matching regexp) namespace into a hash
15210: ($udom, $uname, $regexp, $range are optional)
15211: 
15212: $range should be either an integer '100' (give me the first 100
15213:                                            matching records)
15214:               or be  two integers sperated by a - with no spaces
15215:                  '30-50' (give me the 30th through the 50th matching
15216:                           records)
15217: =item *
15218: 
15219: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15220: $store can be a scalar, an array reference, or if the amount to be 
15221: incremented is > 1, a hash reference.
15222: 
15223: ($udom and $uname are optional)
15224: 
15225: =item *
15226: 
15227: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15228: ($udom and $uname are optional)
15229: 
15230: =item *
15231: 
15232: cput($namespace,$storehash,$udom,$uname) : critical put
15233: ($udom and $uname are optional)
15234: 
15235: =item *
15236: 
15237: newput($namespace,$storehash,$udom,$uname) :
15238: 
15239: Attempts to store the items in the $storehash, but only if they don't
15240: currently exist, if this succeeds you can be certain that you have 
15241: successfully created a new key value pair in the $namespace db.
15242: 
15243: 
15244: Args:
15245:  $namespace: name of database to store values to
15246:  $storehash: hashref to store to the db
15247:  $udom: (optional) domain of user containing the db
15248:  $uname: (optional) name of user caontaining the db
15249: 
15250: Returns:
15251:  'ok' -> succeeded in storing all keys of $storehash
15252:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15253:                         least <key> already existed in the db (other
15254:                         requested keys may also already exist)
15255:  'error: <msg>' -> unable to tie the DB or other error occurred
15256:  'con_lost' -> unable to contact request server
15257:  'refused' -> action was not allowed by remote machine
15258: 
15259: 
15260: =item *
15261: 
15262: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15263: reference filled in from namesp (encrypts the return communication)
15264: ($udom and $uname are optional)
15265: 
15266: =item *
15267: 
15268: log($udom,$name,$home,$message) : write to permanent log for user; use
15269: critical subroutine
15270: 
15271: =item *
15272: 
15273: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15274: array reference filled in from namespace found in domain level on either
15275: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15276: 
15277: =item *
15278: 
15279: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15280: domain level either on specified domain server ($uhome) or primary domain 
15281: server ($udom and $uhome are optional)
15282: 
15283: =item * 
15284: 
15285: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15286: for: authentication, language, quotas, timezone, date locale, and portal URL in
15287: the target domain.
15288: 
15289: May also include additional key => value pairs for the following groups:
15290: 
15291: =over
15292: 
15293: =item
15294: disk quotas (MB allocated by default to portfolios and authoring spaces).
15295: 
15296: =over
15297: 
15298: =item defaultquota, authorquota
15299: 
15300: =back
15301: 
15302: =item
15303: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15304: portfolio for users).
15305: 
15306: =over
15307: 
15308: =item
15309: aboutme, blog, webdav, portfolio
15310: 
15311: =back
15312: 
15313: =item
15314: requestcourses: ability to request courses, and how requests are processed.
15315: 
15316: =over
15317: 
15318: =item
15319: official, unofficial, community, textbook, placement
15320: 
15321: =back
15322: 
15323: =item
15324: inststatus: types of institutional affiliation, and order in which they are displayed.
15325: 
15326: =over
15327: 
15328: =item
15329: inststatustypes, inststatusorder, inststatusguest
15330: 
15331: =back
15332: 
15333: =item
15334: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15335: for course's uploaded content.
15336: 
15337: =over
15338: 
15339: =item
15340: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15341: communityquota, textbookquota, placementquota
15342: 
15343: =back
15344: 
15345: =item
15346: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15347: on your servers.
15348: 
15349: =over
15350: 
15351: =item 
15352: remotesessions, hostedsessions
15353: 
15354: =back
15355: 
15356: =back
15357: 
15358: In cases where a domain coordinator has never used the "Set Domain Configuration"
15359: utility to create a configuration.db file on a domain's primary library server 
15360: only the following domain defaults: auth_def, auth_arg_def, lang_def
15361: -- corresponding values are authentication type (internal, krb4, krb5,
15362: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15363: will be available. Values are retrieved from cache (if current), unless the
15364: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15365: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15366: 
15367: Typical usage:
15368: 
15369: %domdefaults = &get_domain_defaults($target_domain);
15370: 
15371: =back
15372: 
15373: =head2 Network Status Functions
15374: 
15375: =over 4
15376: 
15377: =item *
15378: 
15379: dirlist() : return directory list based on URI (first arg).
15380: 
15381: Inputs: 1 required, 5 optional.
15382: 
15383: =over
15384: 
15385: =item 
15386: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15387: 
15388: =item
15389: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15390: 
15391: =item
15392: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15393: 
15394: =item
15395: $getpropath - boolean: 1 if prepend path using &propath(). 
15396: 
15397: =item
15398: $getuserdir - boolean: 1 if prepend path for "userfiles".
15399: 
15400: =item 
15401: $alternateRoot - path to prepend in place of path from $uri.
15402: 
15403: =back
15404: 
15405: Returns: Array of up to two items.
15406: 
15407: =over
15408: 
15409: a reference to an array of files/subdirectories
15410: 
15411: =over
15412: 
15413: Each element in the array of files/subdirectories is a & separated list of
15414: item name and the result of running stat on the item.  If dirlist was requested
15415: for a file instead of a directory, the item name will be ''. For a directory 
15416: listing, if the item is a metadata file, the element will end &N&M 
15417: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15418: default copyright set (1).  
15419: 
15420: =back
15421: 
15422: a scalar containing error condition (if encountered).
15423: 
15424: =over
15425: 
15426: =item 
15427: no_host (no homeserver identified for $username:$domain).
15428: 
15429: =item 
15430: no_such_host (server contacted for listing not identified as valid host).
15431: 
15432: =item 
15433: con_lost (connection to remote server failed).
15434: 
15435: =item 
15436: refused (invalid $username:$domain received on lond side).
15437: 
15438: =item 
15439: no_such_dir (directory at specified path on lond side does not exist). 
15440: 
15441: =item 
15442: empty (directory at specified path on lond side is empty).
15443: 
15444: =over
15445: 
15446: This is currently not encountered because the &ls3, &ls2, 
15447: &ls (_handler) routines on the lond side do not filter out
15448: . and .. from a directory listing. 
15449: 
15450: =back
15451: 
15452: =back
15453: 
15454: =back
15455: 
15456: =item *
15457: 
15458: spareserver() : find server with least workload from spare.tab
15459: 
15460: 
15461: =item *
15462: 
15463: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15464: if there is no corresponding loncapa host.
15465: 
15466: =back
15467: 
15468: 
15469: =head2 Apache Request
15470: 
15471: =over 4
15472: 
15473: =item *
15474: 
15475: ssi($url,%hash) : server side include, does a complete request cycle on url to
15476: localhost, posts hash
15477: 
15478: =back
15479: 
15480: =head2 Data to String to Data
15481: 
15482: =over 4
15483: 
15484: =item *
15485: 
15486: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15487: and '&' separators, supports elements that are arrayrefs and hashrefs
15488: 
15489: =item *
15490: 
15491: hashref2str($hashref) : convert a hashref into a string complete with
15492: escaping and '=' and '&' separators, supports elements that are
15493: arrayrefs and hashrefs
15494: 
15495: =item *
15496: 
15497: arrayref2str($arrayref) : convert an arrayref into a string complete
15498: with escaping and '&' separators, supports elements that are arrayrefs
15499: and hashrefs
15500: 
15501: =item *
15502: 
15503: str2hash($string) : convert string to hash using unescaping and
15504: splitting on '=' and '&', supports elements that are arrayrefs and
15505: hashrefs
15506: 
15507: =item *
15508: 
15509: str2array($string) : convert string to hash using unescaping and
15510: splitting on '&', supports elements that are arrayrefs and hashrefs
15511: 
15512: =back
15513: 
15514: =head2 Logging Routines
15515: 
15516: 
15517: These routines allow one to make log messages in the lonnet.log and
15518: lonnet.perm logfiles.
15519: 
15520: =over 4
15521: 
15522: =item *
15523: 
15524: logtouch() : make sure the logfile, lonnet.log, exists
15525: 
15526: =item *
15527: 
15528: logthis() : append message to the normal lonnet.log file, it gets
15529: preiodically rolled over and deleted.
15530: 
15531: =item *
15532: 
15533: logperm() : append a permanent message to lonnet.perm.log, this log
15534: file never gets deleted by any automated portion of the system, only
15535: messages of critical importance should go in here.
15536: 
15537: 
15538: =back
15539: 
15540: =head2 General File Helper Routines
15541: 
15542: =over 4
15543: 
15544: =item *
15545: 
15546: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15547: (a) files in /uploaded
15548:   (i) If a local copy of the file exists - 
15549:       compares modification date of local copy with last-modified date for 
15550:       definitive version stored on home server for course. If local copy is 
15551:       stale, requests a new version from the home server and stores it. 
15552:       If the original has been removed from the home server, then local copy 
15553:       is unlinked.
15554:   (ii) If local copy does not exist -
15555:       requests the file from the home server and stores it. 
15556:   
15557:   If $caller is 'uploadrep':  
15558:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15559:     for request for files originally uploaded via DOCS. 
15560:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15561:   
15562:   Otherwise:
15563:      This indicates a call from the content generation phase of the request.
15564:      -  returns the entire contents of the file or -1.
15565:      
15566: (b) files in /res
15567:    - returns the entire contents of a file or -1; 
15568:    it properly subscribes to and replicates the file if neccessary.
15569: 
15570: 
15571: =item *
15572: 
15573: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15574:                   reference
15575: 
15576: returns either a stat() list of data about the file or an empty list
15577: if the file doesn't exist or couldn't find out about it (connection
15578: problems or user unknown)
15579: 
15580: =item *
15581: 
15582: filelocation($dir,$file) : returns file system location of a file
15583: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15584: directory that relative $file lookups are to looked in ($dir of /a/dir
15585: and a file of ../bob will become /a/bob)
15586: 
15587: =item *
15588: 
15589: hreflocation($dir,$file) : returns file system location or a URL; same as
15590: filelocation except for hrefs
15591: 
15592: =item *
15593: 
15594: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15595: also removes beginning /home/httpd/html unless /priv/ follows it.
15596: 
15597: =back
15598: 
15599: =head2 Usererfile file routines (/uploaded*)
15600: 
15601: =over 4
15602: 
15603: =item *
15604: 
15605: userfileupload(): main rotine for putting a file in a user or course's
15606:                   filespace, arguments are,
15607: 
15608:  formname - required - this is the name of the element in $env where the
15609:            filename, and the contents of the file to create/modifed exist
15610:            the filename is in $env{'form.'.$formname.'.filename'} and the
15611:            contents of the file is located in $env{'form.'.$formname}
15612:  context - if coursedoc, store the file in the course of the active role
15613:              of the current user; 
15614:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15615:            if 'canceloverwrite': delete file in tmp/overwrites directory
15616:  subdir - required - subdirectory to put the file in under ../userfiles/
15617:          if undefined, it will be placed in "unknown"
15618: 
15619:  (This routine calls clean_filename() to remove any dangerous
15620:  characters from the filename, and then calls finuserfileupload() to
15621:  complete the transaction)
15622: 
15623:  returns either the url of the uploaded file (/uploaded/....) if successful
15624:  and /adm/notfound.html if unsuccessful
15625: 
15626: =item *
15627: 
15628: clean_filename(): routine for cleaing a filename up for storage in
15629:                  userfile space, argument is:
15630: 
15631:  filename - proposed filename
15632: 
15633: returns: the new clean filename
15634: 
15635: =item *
15636: 
15637: finishuserfileupload(): routine that creates and sends the file to
15638: userspace, probably shouldn't be called directly
15639: 
15640:   docuname: username or courseid of destination for the file
15641:   docudom: domain of user/course of destination for the file
15642:   formname: same as for userfileupload()
15643:   fname: filename (including subdirectories) for the file
15644:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15645:   allfiles: reference to hash used to store objects found by parser
15646:   codebase: reference to hash used for codebases of java objects found by parser
15647:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15648:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15649:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15650:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15651:   context: if 'overwrite', will move the uploaded file from its temporary location to
15652:             userfiles to facilitate overwriting a previously uploaded file with same name.
15653:   mimetype: reference to scalar to accommodate mime type determined
15654:             from File::MMagic if $parser = parse.
15655: 
15656:  returns either the url of the uploaded file (/uploaded/....) if successful
15657:  and /adm/notfound.html if unsuccessful (or an error message if context 
15658:  was 'overwrite').
15659:  
15660: 
15661: =item *
15662: 
15663: renameuserfile(): renames an existing userfile to a new name
15664: 
15665:   Args:
15666:    docuname: username or courseid of destination for the file
15667:    docudom: domain of user/course of destination for the file
15668:    old: current file name (including any subdirs under userfiles)
15669:    new: desired file name (including any subdirs under userfiles)
15670: 
15671: =item *
15672: 
15673: mkdiruserfile(): creates a directory is a userfiles dir
15674: 
15675:   Args:
15676:    docuname: username or courseid of destination for the file
15677:    docudom: domain of user/course of destination for the file
15678:    dir: dir to create (including any subdirs under userfiles)
15679: 
15680: =item *
15681: 
15682: removeuserfile(): removes a file that exists in userfiles
15683: 
15684:   Args:
15685:    docuname: username or courseid of destination for the file
15686:    docudom: domain of user/course of destination for the file
15687:    fname: filname to delete (including any subdirs under userfiles)
15688: 
15689: =item *
15690: 
15691: removeuploadedurl(): convience function for removeuserfile()
15692: 
15693:   Args:
15694:    url:  a full /uploaded/... url to delete
15695: 
15696: =item * 
15697: 
15698: get_portfile_permissions():
15699:   Args:
15700:     domain: domain of user or course contain the portfolio files
15701:     user: name of user or num of course contain the portfolio files
15702:   Returns:
15703:     hashref of a dump of the proper file_permissions.db
15704:    
15705: 
15706: =item * 
15707: 
15708: get_access_controls():
15709: 
15710: Args:
15711:   current_permissions: the hash ref returned from get_portfile_permissions()
15712:   group: (optional) the group you want the files associated with
15713:   file: (optional) the file you want access info on
15714: 
15715: Returns:
15716:     a hash (keys are file names) of hashes containing
15717:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15718:         values are XML containing access control settings (see below) 
15719: 
15720: Internal notes:
15721: 
15722:  access controls are stored in file_permissions.db as key=value pairs.
15723:     key -> path to file/file_name\0uniqueID:scope_end_start
15724:         where scope -> public,guest,course,group,domains or users.
15725:               end -> UNIX time for end of access (0 -> no end date)
15726:               start -> UNIX time for start of access
15727: 
15728:     value -> XML description of access control
15729:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15730:             <start></start>
15731:             <end></end>
15732: 
15733:             <password></password>  for scope type = guest
15734: 
15735:             <domain></domain>     for scope type = course or group
15736:             <number></number>
15737:             <roles id="">
15738:              <role></role>
15739:              <access></access>
15740:              <section></section>
15741:              <group></group>
15742:             </roles>
15743: 
15744:             <dom></dom>         for scope type = domains
15745: 
15746:             <users>             for scope type = users
15747:              <user>
15748:               <uname></uname>
15749:               <udom></udom>
15750:              </user>
15751:             </users>
15752:            </scope> 
15753:               
15754:  Access data is also aggregated for each file in an additional key=value pair:
15755:  key -> path to file/file_name\0accesscontrol 
15756:  value -> reference to hash
15757:           hash contains key = value pairs
15758:           where key = uniqueID:scope_end_start
15759:                 value = UNIX time record was last updated
15760: 
15761:           Used to improve speed of look-ups of access controls for each file.  
15762:  
15763:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15764: 
15765: =item *
15766: 
15767: modify_access_controls():
15768: 
15769: Modifies access controls for a portfolio file
15770: Args
15771: 1. file name
15772: 2. reference to hash of required changes,
15773: 3. domain
15774: 4. username
15775:   where domain,username are the domain of the portfolio owner 
15776:   (either a user or a course) 
15777: 
15778: Returns:
15779: 1. result of additions or updates ('ok' or 'error', with error message). 
15780: 2. result of deletions ('ok' or 'error', with error message).
15781: 3. reference to hash of any new or updated access controls.
15782: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15783:    key = integer (inbound ID)
15784:    value = uniqueID
15785: 
15786: =item *
15787: 
15788: get_timebased_id():
15789: 
15790: Attempts to get a unique timestamp-based suffix for use with items added to a 
15791: course via the Course Editor (e.g., folders, composite pages, 
15792: group bulletin boards).
15793: 
15794: Args: (first three required; six others optional)
15795: 
15796: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15797:    docssequence, or name of group
15798: 
15799: 2. keyid (alphanumeric): name of temporary locking key in hash,
15800:    e.g., num, boardids
15801: 
15802: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15803:    file will be named nohist_namespace.db
15804: 
15805: 4. cdom: domain of course; default is current course domain from %env
15806: 
15807: 5. cnum: course number; default is current course number from %env
15808: 
15809: 6. idtype: set to concat if an additional digit is to be appended to the 
15810:    unix timestamp to form the suffix, if the plain timestamp is already
15811:    in use.  Default is to not do this, but simply increment the unix 
15812:    timestamp by 1 until a unique key is obtained.
15813: 
15814: 7. who: holder of locking key; defaults to user:domain for user.
15815: 
15816: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15817:    retrying); default is 3.
15818: 
15819: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15820: 
15821: Returns:
15822: 
15823: 1. suffix obtained (numeric)
15824: 
15825: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15826: 
15827: 3. error: contains (localized) error message if an error occurred.
15828: 
15829: 
15830: =back
15831: 
15832: =head2 HTTP Helper Routines
15833: 
15834: =over 4
15835: 
15836: =item *
15837: 
15838: escape() : unpack non-word characters into CGI-compatible hex codes
15839: 
15840: =item *
15841: 
15842: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15843: 
15844: =back
15845: 
15846: =head1 PRIVATE SUBROUTINES
15847: 
15848: =head2 Underlying communication routines (Shouldn't call)
15849: 
15850: =over 4
15851: 
15852: =item *
15853: 
15854: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15855: 
15856: =item *
15857: 
15858: reply() : uses subreply to send a message to remote machine, logs all failures
15859: 
15860: =item *
15861: 
15862: critical() : passes a critical message to another server; if cannot
15863: get through then place message in connection buffer directory and
15864: returns con_delayed, if incapable of saving message, returns
15865: con_failed
15866: 
15867: =item *
15868: 
15869: reconlonc() : tries to reconnect lonc client processes.
15870: 
15871: =back
15872: 
15873: =head2 Resource Access Logging
15874: 
15875: =over 4
15876: 
15877: =item *
15878: 
15879: flushcourselogs() : flush (save) buffer logs and access logs
15880: 
15881: =item *
15882: 
15883: courselog($what) : save message for course in hash
15884: 
15885: =item *
15886: 
15887: courseacclog($what) : save message for course using &courselog().  Perform
15888: special processing for specific resource types (problems, exams, quizzes, etc).
15889: 
15890: =item *
15891: 
15892: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15893: as a PerlChildExitHandler
15894: 
15895: =back
15896: 
15897: =head2 Other
15898: 
15899: =over 4
15900: 
15901: =item *
15902: 
15903: symblist($mapname,%newhash) : update symbolic storage links
15904: 
15905: =back
15906: 
15907: =cut
15908: 

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