File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1436: download - view: text, annotated - select for diffs
Sat Jan 2 19:31:11 2021 UTC (3 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6518. Content blocking check for wrapped uploaded files (e.g., PDFs),
  uploaded files with mime types that require /adm/coursedocs/showdoc/, and
  /adm/viewclasslist.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1436 2021/01/02 19:31: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: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab $passwdmin);
   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 Net::CIDR;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: use LONCAPA::LWPReq;
  105: use LONCAPA::transliterate;
  106: 
  107: use File::Copy;
  108: 
  109: my $readit;
  110: my $max_connection_retries = 20;     # Or some such value.
  111: 
  112: require Exporter;
  113: 
  114: our @ISA = qw (Exporter);
  115: our @EXPORT = qw(%env);
  116: 
  117: 
  118: # ------------------------------------ Logging (parameters, docs, slots, roles)
  119: {
  120:     my $logid;
  121:     sub write_log {
  122: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  123:         if ($context eq 'course') {
  124:             if (($cnum eq '') || ($cdom eq '')) {
  125:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  126:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  127:             }
  128:         }
  129: 	$logid ++;
  130:         my $now = time();
  131: 	my $id=$now.'00000'.$$.'00000'.$logid;
  132:         my $ip = &get_requestor_ip();
  133:         my $logentry = { 
  134:                           $id => {
  135:                                    'exe_uname' => $env{'user.name'},
  136:                                    'exe_udom'  => $env{'user.domain'},
  137:                                    'exe_time'  => $now,
  138:                                    'exe_ip'    => $ip,
  139:                                    'delflag'   => $delflag,
  140:                                    'logentry'  => $storehash,
  141:                                    'uname'     => $uname,
  142:                                    'udom'      => $udom,
  143:                                   }
  144:                        };
  145: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  146:     }
  147: }
  148: 
  149: sub logtouch {
  150:     my $execdir=$perlvar{'lonDaemons'};
  151:     unless (-e "$execdir/logs/lonnet.log") {	
  152: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  153: 	close $fh;
  154:     }
  155:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  156:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  157: }
  158: 
  159: sub logthis {
  160:     my $message=shift;
  161:     my $execdir=$perlvar{'lonDaemons'};
  162:     my $now=time;
  163:     my $local=localtime($now);
  164:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  165: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  166: 	print $fh $logstring;
  167: 	close($fh);
  168:     }
  169:     return 1;
  170: }
  171: 
  172: sub logperm {
  173:     my $message=shift;
  174:     my $execdir=$perlvar{'lonDaemons'};
  175:     my $now=time;
  176:     my $local=localtime($now);
  177:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  178: 	print $fh "$now:$message:$local\n";
  179: 	close($fh);
  180:     }
  181:     return 1;
  182: }
  183: 
  184: sub create_connection {
  185:     my ($hostname,$lonid) = @_;
  186:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  187: 				     Type    => SOCK_STREAM,
  188: 				     Timeout => 10);
  189:     return 0 if (!$client);
  190:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  191:     my $result = <$client>;
  192:     chomp($result);
  193:     return 1 if ($result eq 'done');
  194:     return 0;
  195: }
  196: 
  197: sub get_server_timezone {
  198:     my ($cnum,$cdom) = @_;
  199:     my $home=&homeserver($cnum,$cdom);
  200:     if ($home ne 'no_host') {
  201:         my $cachetime = 24*3600;
  202:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  203:         if (defined($cached)) {
  204:             return $timezone;
  205:         } else {
  206:             my $timezone = &reply('servertimezone',$home);
  207:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  208:         }
  209:     }
  210: }
  211: 
  212: sub get_server_distarch {
  213:     my ($lonhost,$ignore_cache) = @_;
  214:     if (defined($lonhost)) {
  215:         if (!defined(&hostname($lonhost))) {
  216:             return;
  217:         }
  218:         my $cachetime = 12*3600;
  219:         if (!$ignore_cache) {
  220:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  221:             if (defined($cached)) {
  222:                 return $distarch;
  223:             }
  224:         }
  225:         my $rep = &reply('serverdistarch',$lonhost);
  226:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  227:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  228:                 $rep eq '') {
  229:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  230:         }
  231:     }
  232:     return;
  233: }
  234: 
  235: sub get_servercerts_info {
  236:     my ($lonhost,$hostname,$context) = @_;
  237:     return if ($lonhost eq '');
  238:     if ($hostname eq '') {
  239:         $hostname = &hostname($lonhost);
  240:     }
  241:     return if ($hostname eq '');
  242:     my ($rep,$uselocal);
  243:     if ($context eq 'install') {
  244:         $uselocal = 1;
  245:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  246:         $uselocal = 1;
  247:     }
  248:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  249:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  250:         if ($distro eq '') {
  251:             $uselocal = 0;
  252:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  253:             if ($1 < 6) {
  254:                 $uselocal = 0;
  255:             }
  256:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  257:             if ($1 < 12) {
  258:                 $uselocal = 0;
  259:             }
  260:         }
  261:     }
  262:     if ($uselocal) {
  263:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  264:     } else {
  265:         $rep=&reply('servercerts',$lonhost);
  266:     }
  267:     my ($result,%returnhash);
  268:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  269:         ($rep eq 'unknown_cmd')) {
  270:         $result = $rep;
  271:     } else {
  272:         $result = 'ok';
  273:         my @pairs=split(/\&/,$rep);
  274:         foreach my $item (@pairs) {
  275:             my ($key,$value)=split(/=/,$item,2);
  276:             my $what = &unescape($key);
  277:             $returnhash{$what}=&thaw_unescape($value);
  278:         }
  279:     }
  280:     return ($result,\%returnhash);
  281: }
  282: 
  283: sub get_server_loncaparev {
  284:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  285:     if (defined($lonhost)) {
  286:         if (!defined(&hostname($lonhost))) {
  287:             undef($lonhost);
  288:         }
  289:     }
  290:     if (!defined($lonhost)) {
  291:         if (defined(&domain($dom,'primary'))) {
  292:             $lonhost=&domain($dom,'primary');
  293:             if ($lonhost eq 'no_host') {
  294:                 undef($lonhost);
  295:             }
  296:         }
  297:     }
  298:     if (defined($lonhost)) {
  299:         my $cachetime = 12*3600;
  300:         if (!$ignore_cache) {
  301:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  302:             if (defined($cached)) {
  303:                 return $loncaparev;
  304:             }
  305:         }
  306:         my ($answer,$loncaparev);
  307:         my @ids=&current_machine_ids();
  308:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  309:             $answer = $perlvar{'lonVersion'};
  310:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  311:                 $loncaparev = $1;
  312:             }
  313:         } else {
  314:             $answer = &reply('serverloncaparev',$lonhost);
  315:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  316:                 if ($caller eq 'loncron') {
  317:                     my $hostname = &hostname($lonhost);
  318:                     my $protocol = $protocol{$lonhost};
  319:                     $protocol = 'http' if ($protocol ne 'https');
  320:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  321:                     my $request=new HTTP::Request('GET',$url);
  322:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  323:                     unless ($response->is_error()) {
  324:                         my $content = $response->content;
  325:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  326:                             $loncaparev = $1;
  327:                         }
  328:                     }
  329:                 } else {
  330:                     $loncaparev = $loncaparevs{$lonhost};
  331:                 }
  332:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  333:                 $loncaparev = $1;
  334:             }
  335:         }
  336:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  337:     }
  338: }
  339: 
  340: sub get_server_homeID {
  341:     my ($hostname,$ignore_cache,$caller) = @_;
  342:     unless ($ignore_cache) {
  343:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  344:         if (defined($cached)) {
  345:             return $serverhomeID;
  346:         }
  347:     }
  348:     my $cachetime = 12*3600;
  349:     my $serverhomeID;
  350:     if ($caller eq 'loncron') { 
  351:         my @machine_ids = &machine_ids($hostname);
  352:         foreach my $id (@machine_ids) {
  353:             my $response = &reply('serverhomeID',$id);
  354:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  355:                 $serverhomeID = $response;
  356:                 last;
  357:             }
  358:         }
  359:         if ($serverhomeID eq '') {
  360:             $serverhomeID = $machine_ids[-1];
  361:         }
  362:     } else {
  363:         $serverhomeID = $serverhomeIDs{$hostname};
  364:     }
  365:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  366: }
  367: 
  368: sub get_remote_globals {
  369:     my ($lonhost,$whathash,$ignore_cache) = @_;
  370:     my ($result,%returnhash,%whatneeded);
  371:     if (ref($whathash) eq 'HASH') {
  372:         foreach my $what (sort(keys(%{$whathash}))) {
  373:             my $hashid = $lonhost.'-'.$what;
  374:             my ($response,$cached);
  375:             unless ($ignore_cache) {
  376:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  377:             }
  378:             if (defined($cached)) {
  379:                 $returnhash{$what} = $response;
  380:             } else {
  381:                 $whatneeded{$what} = 1;
  382:             }
  383:         }
  384:         if (keys(%whatneeded) == 0) {
  385:             $result = 'ok';
  386:         } else {
  387:             my $requested = &freeze_escape(\%whatneeded);
  388:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  389:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  390:                 ($rep eq 'unknown_cmd')) {
  391:                 $result = $rep;
  392:             } else {
  393:                 $result = 'ok';
  394:                 my @pairs=split(/\&/,$rep);
  395:                 foreach my $item (@pairs) {
  396:                     my ($key,$value)=split(/=/,$item,2);
  397:                     my $what = &unescape($key);
  398:                     my $hashid = $lonhost.'-'.$what;
  399:                     $returnhash{$what}=&thaw_unescape($value);
  400:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  401:                 }
  402:             }
  403:         }
  404:     }
  405:     return ($result,\%returnhash);
  406: }
  407: 
  408: sub remote_devalidate_cache {
  409:     my ($lonhost,$cachekeys) = @_;
  410:     my $items;
  411:     return unless (ref($cachekeys) eq 'ARRAY');
  412:     my $cachestr = join('&',@{$cachekeys});
  413:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  414:     return $response;
  415: }
  416: 
  417: # -------------------------------------------------- Non-critical communication
  418: sub subreply {
  419:     my ($cmd,$server)=@_;
  420:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  421:     #
  422:     #  With loncnew process trimming, there's a timing hole between lonc server
  423:     #  process exit and the master server picking up the listen on the AF_UNIX
  424:     #  socket.  In that time interval, a lock file will exist:
  425: 
  426:     my $lockfile=$peerfile.".lock";
  427:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  428: 	sleep(0.1);
  429:     }
  430:     # At this point, either a loncnew parent is listening or an old lonc
  431:     # or loncnew child is listening so we can connect or everything's dead.
  432:     #
  433:     #   We'll give the connection a few tries before abandoning it.  If
  434:     #   connection is not possible, we'll con_lost back to the client.
  435:     #   
  436:     my $client;
  437:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  438: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  439: 				      Type    => SOCK_STREAM,
  440: 				      Timeout => 10);
  441: 	if ($client) {
  442: 	    last;		# Connected!
  443: 	} else {
  444: 	    &create_connection(&hostname($server),$server);
  445: 	}
  446:         sleep(0.1);	# Try again later if failed connection.
  447:     }
  448:     my $answer;
  449:     if ($client) {
  450: 	print $client "sethost:$server:$cmd\n";
  451: 	$answer=<$client>;
  452: 	if (!$answer) { $answer="con_lost"; }
  453: 	chomp($answer);
  454:     } else {
  455: 	$answer = 'con_lost';	# Failed connection.
  456:     }
  457:     return $answer;
  458: }
  459: 
  460: sub reply {
  461:     my ($cmd,$server)=@_;
  462:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  463:     my $answer=subreply($cmd,$server);
  464:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  465:         my $logged = $cmd;
  466:         if ($cmd =~ /^encrypt:([^:]+):/) {
  467:             my $subcmd = $1;
  468:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  469:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  470:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  471:                 (undef,undef,my @rest) = split(/:/,$cmd);
  472:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  473:                     splice(@rest,2,1,'Hidden');
  474:                 } elsif ($subcmd eq 'passwd') {
  475:                     splice(@rest,2,2,('Hidden','Hidden'));
  476:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  477:                          ($subcmd eq 'autoexportgrades')) {
  478:                     splice(@rest,3,1,'Hidden');
  479:                 }
  480:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  481:             }
  482:         }
  483:         &logthis("<font color=\"blue\">WARNING:".
  484:                  " $logged to $server returned $answer</font>");
  485:     }
  486:     return $answer;
  487: }
  488: 
  489: # ----------------------------------------------------------- Send USR1 to lonc
  490: 
  491: sub reconlonc {
  492:     my ($lonid) = @_;
  493:     if ($lonid) {
  494:         my $hostname = &hostname($lonid);
  495: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  496: 	if ($hostname && -e $peerfile) {
  497: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  498: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  499: 					     Type    => SOCK_STREAM,
  500: 					     Timeout => 10);
  501: 	    if ($client) {
  502: 		print $client ("reset_retries\n");
  503: 		my $answer=<$client>;
  504: 		#reset just this one.
  505: 	    }
  506: 	}
  507: 	return;
  508:     }
  509: 
  510:     &logthis("Trying to reconnect lonc");
  511:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  512:     if (open(my $fh,"<",$loncfile)) {
  513: 	my $loncpid=<$fh>;
  514:         chomp($loncpid);
  515:         if (kill 0 => $loncpid) {
  516: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  517:             kill USR1 => $loncpid;
  518:             sleep 1;
  519:         } else {
  520: 	    &logthis(
  521:                "<font color=\"blue\">WARNING:".
  522:                " lonc at pid $loncpid not responding, giving up</font>");
  523:         }
  524:     } else {
  525: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  526:     }
  527: }
  528: 
  529: # ------------------------------------------------------ Critical communication
  530: 
  531: sub critical {
  532:     my ($cmd,$server)=@_;
  533:     unless (&hostname($server)) {
  534:         &logthis("<font color=\"blue\">WARNING:".
  535:                " Critical message to unknown server ($server)</font>");
  536:         return 'no_such_host';
  537:     }
  538:     my $answer=reply($cmd,$server);
  539:     if ($answer eq 'con_lost') {
  540: 	&reconlonc($server);
  541: 	my $answer=reply($cmd,$server);
  542:         if ($answer eq 'con_lost') {
  543:             my $now=time;
  544:             my $middlename=$cmd;
  545:             $middlename=substr($middlename,0,16);
  546:             $middlename=~s/\W//g;
  547:             my $dfilename=
  548:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  549:             $dumpcount++;
  550:             {
  551: 		my $dfh;
  552: 		if (open($dfh,">",$dfilename)) {
  553: 		    print $dfh "$cmd\n"; 
  554: 		    close($dfh);
  555: 		}
  556:             }
  557:             sleep 1;
  558:             my $wcmd='';
  559:             {
  560: 		my $dfh;
  561: 		if (open($dfh,"<",$dfilename)) {
  562: 		    $wcmd=<$dfh>; 
  563: 		    close($dfh);
  564: 		}
  565:             }
  566:             chomp($wcmd);
  567:             if ($wcmd eq $cmd) {
  568: 		&logthis("<font color=\"blue\">WARNING: ".
  569:                          "Connection buffer $dfilename: $cmd</font>");
  570:                 &logperm("D:$server:$cmd");
  571: 	        return 'con_delayed';
  572:             } else {
  573:                 &logthis("<font color=\"red\">CRITICAL:"
  574:                         ." Critical connection failed: $server $cmd</font>");
  575:                 &logperm("F:$server:$cmd");
  576:                 return 'con_failed';
  577:             }
  578:         }
  579:     }
  580:     return $answer;
  581: }
  582: 
  583: # ------------------------------------------- check if return value is an error
  584: 
  585: sub error {
  586:     my ($result) = @_;
  587:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  588: 	if ($2 == 2) { return undef; }
  589: 	return $1;
  590:     }
  591:     return undef;
  592: }
  593: 
  594: sub convert_and_load_session_env {
  595:     my ($lonidsdir,$handle)=@_;
  596:     my @profile;
  597:     {
  598: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  599: 	if (!$opened) {
  600: 	    return 0;
  601: 	}
  602: 	flock($idf,LOCK_SH);
  603: 	@profile=<$idf>;
  604: 	close($idf);
  605:     }
  606:     my %temp_env;
  607:     foreach my $line (@profile) {
  608: 	if ($line !~ m/=/) {
  609: 	    return 0;
  610: 	}
  611: 	chomp($line);
  612: 	my ($envname,$envvalue)=split(/=/,$line,2);
  613: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  614:     }
  615:     unlink("$lonidsdir/$handle.id");
  616:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  617: 	    0640)) {
  618: 	%disk_env = %temp_env;
  619: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  620: 	untie(%disk_env);
  621:     }
  622:     return 1;
  623: }
  624: 
  625: # ------------------------------------------- Transfer profile into environment
  626: my $env_loaded;
  627: sub transfer_profile_to_env {
  628:     my ($lonidsdir,$handle,$force_transfer) = @_;
  629:     if (!$force_transfer && $env_loaded) { return; } 
  630: 
  631:     if (!defined($lonidsdir)) {
  632: 	$lonidsdir = $perlvar{'lonIDsDir'};
  633:     }
  634:     if (!defined($handle)) {
  635:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  636:     }
  637: 
  638:     my $convert;
  639:     {
  640:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  641: 	if (!$opened) {
  642: 	    return;
  643: 	}
  644: 	flock($idf,LOCK_SH);
  645: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  646: 		&GDBM_READER(),0640)) {
  647: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  648: 	    untie(%disk_env);
  649: 	} else {
  650: 	    $convert = 1;
  651: 	}
  652:     }
  653:     if ($convert) {
  654: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  655: 	    &logthis("Failed to load session, or convert session.");
  656: 	}
  657:     }
  658: 
  659:     my %remove;
  660:     while ( my $envname = each(%env) ) {
  661:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  662:             if ($time < time-300) {
  663:                 $remove{$key}++;
  664:             }
  665:         }
  666:     }
  667: 
  668:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  669:     $env_loaded=1;
  670:     foreach my $expired_key (keys(%remove)) {
  671:         &delenv($expired_key);
  672:     }
  673: }
  674: 
  675: # ---------------------------------------------------- Check for valid session 
  676: sub check_for_valid_session {
  677:     my ($r,$name,$userhashref,$domref) = @_;
  678:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  679:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  680:     if ($name eq 'lonDAV') {
  681:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  682:     } else {
  683:         $lonidsdir=$r->dir_config('lonIDsDir');
  684:         if ($name eq '') {
  685:             $name = 'lonID';
  686:         }
  687:     }
  688:     if ($name eq 'lonID') {
  689:         $secure = 'lonSID';
  690:         $linkname = 'lonLinkID';
  691:         $pubname = 'lonPubID';
  692:         if (exists($cookies{$secure})) {
  693:             $lonid=$cookies{$secure};
  694:         } elsif (exists($cookies{$name})) {
  695:             $lonid=$cookies{$name};
  696:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  697:             $lonid=$cookies{$linkname};
  698:         } elsif (exists($cookies{$pubname})) {
  699:             $lonid=$cookies{$pubname};
  700:         }
  701:     } else {
  702:         $lonid=$cookies{$name};
  703:     }
  704:     return undef if (!$lonid);
  705: 
  706:     my $handle=&LONCAPA::clean_handle($lonid->value);
  707:     if (-l "$lonidsdir/$handle.id") {
  708:         my $link = readlink("$lonidsdir/$handle.id");
  709:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  710:             $handle = $1;
  711:         }
  712:     }
  713:     if (!-e "$lonidsdir/$handle.id") {
  714:         if ((ref($domref)) && ($name eq 'lonID') && 
  715:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  716:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  717:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  718:                 $$domref = $possudom;
  719:             }
  720:         }
  721:         return undef;
  722:     }
  723: 
  724:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  725:     return undef if (!$opened);
  726: 
  727:     flock($idf,LOCK_SH);
  728:     my %disk_env;
  729:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  730: 	    &GDBM_READER(),0640)) {
  731: 	return undef;	
  732:     }
  733: 
  734:     if (!defined($disk_env{'user.name'})
  735: 	|| !defined($disk_env{'user.domain'})) {
  736:         untie(%disk_env);
  737: 	return undef;
  738:     }
  739: 
  740:     if (ref($userhashref) eq 'HASH') {
  741:         $userhashref->{'name'} = $disk_env{'user.name'};
  742:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  743:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  744:         if ($userhashref->{'lti'}) {
  745:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  746:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  747:         }
  748:     }
  749:     untie(%disk_env);
  750: 
  751:     return $handle;
  752: }
  753: 
  754: sub timed_flock {
  755:     my ($file,$lock_type) = @_;
  756:     my $failed=0;
  757:     eval {
  758: 	local $SIG{__DIE__}='DEFAULT';
  759: 	local $SIG{ALRM}=sub {
  760: 	    $failed=1;
  761: 	    die("failed lock");
  762: 	};
  763: 	alarm(13);
  764: 	flock($file,$lock_type);
  765: 	alarm(0);
  766:     };
  767:     if ($failed) {
  768: 	return undef;
  769:     } else {
  770: 	return 1;
  771:     }
  772: }
  773: 
  774: sub get_sessionfile_vars {
  775:     my ($handle,$lonidsdir,$storearr) = @_;
  776:     my %returnhash;
  777:     unless (ref($storearr) eq 'ARRAY') {
  778:         return %returnhash;
  779:     }
  780:     if (-l "$lonidsdir/$handle.id") {
  781:         my $link = readlink("$lonidsdir/$handle.id");
  782:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  783:             $handle = $1;
  784:         }
  785:     }
  786:     if ((-e "$lonidsdir/$handle.id") &&
  787:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  788:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  789:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  790:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  791:                 flock($idf,LOCK_SH);
  792:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  793:                         &GDBM_READER(),0640)) {
  794:                     foreach my $item (@{$storearr}) {
  795:                         $returnhash{$item} = $disk_env{$item};
  796:                     }
  797:                     untie(%disk_env);
  798:                 }
  799:             }
  800:         }
  801:     }
  802:     return %returnhash;
  803: }
  804: 
  805: # ---------------------------------------------------------- Append Environment
  806: 
  807: sub appenv {
  808:     my ($newenv,$roles) = @_;
  809:     if (ref($newenv) eq 'HASH') {
  810:         foreach my $key (keys(%{$newenv})) {
  811:             my $refused = 0;
  812: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  813:                 $refused = 1;
  814:                 if (ref($roles) eq 'ARRAY') {
  815:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  816:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  817:                         $refused = 0;
  818:                     }
  819:                 }
  820:             }
  821:             if ($refused) {
  822:                 &logthis("<font color=\"blue\">WARNING: ".
  823:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  824:                          .'</font>');
  825: 	        delete($newenv->{$key});
  826:             } else {
  827:                 $env{$key}=$newenv->{$key};
  828:             }
  829:         }
  830:         my $lonids = $perlvar{'lonIDsDir'};
  831:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  832:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  833:             if ($opened
  834: 	        && &timed_flock($env_file,LOCK_EX)
  835: 	        &&
  836: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  837: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  838: 	        while (my ($key,$value) = each(%{$newenv})) {
  839: 	            $disk_env{$key} = $value;
  840: 	        }
  841: 	        untie(%disk_env);
  842:             }
  843:         }
  844:     }
  845:     return 'ok';
  846: }
  847: # ----------------------------------------------------- Delete from Environment
  848: 
  849: sub delenv {
  850:     my ($delthis,$regexp,$roles) = @_;
  851:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  852:         my $refused = 1;
  853:         if (ref($roles) eq 'ARRAY') {
  854:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  855:             if (grep(/^\Q$role\E$/,@{$roles})) {
  856:                 $refused = 0;
  857:             }
  858:         }
  859:         if ($refused) {
  860:             &logthis("<font color=\"blue\">WARNING: ".
  861:                      "Attempt to delete from environment ".$delthis);
  862:             return 'error';
  863:         }
  864:     }
  865:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  866:     if ($opened
  867: 	&& &timed_flock($env_file,LOCK_EX)
  868: 	&&
  869: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  870: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  871: 	foreach my $key (keys(%disk_env)) {
  872: 	    if ($regexp) {
  873:                 if ($key=~/^$delthis/) {
  874:                     delete($env{$key});
  875:                     delete($disk_env{$key});
  876:                 } 
  877:             } else {
  878:                 if ($key=~/^\Q$delthis\E/) {
  879: 		    delete($env{$key});
  880: 		    delete($disk_env{$key});
  881: 	        }
  882:             }
  883: 	}
  884: 	untie(%disk_env);
  885:     }
  886:     return 'ok';
  887: }
  888: 
  889: sub get_env_multiple {
  890:     my ($name) = @_;
  891:     my @values;
  892:     if (defined($env{$name})) {
  893:         # exists is it an array
  894:         if (ref($env{$name})) {
  895:             @values=@{ $env{$name} };
  896:         } else {
  897:             $values[0]=$env{$name};
  898:         }
  899:     }
  900:     return(@values);
  901: }
  902: 
  903: # ------------------------------------------------------------------- Locking
  904: 
  905: sub set_lock {
  906:     my ($text)=@_;
  907:     $locknum++;
  908:     my $id=$$.'-'.$locknum;
  909:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  910:              'session.lock.'.$id => $text});
  911:     return $id;
  912: }
  913: 
  914: sub get_locks {
  915:     my $num=0;
  916:     my %texts=();
  917:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  918:        if ($lock=~/\w/) {
  919:           $num++;
  920:           $texts{$lock}=$env{'session.lock.'.$lock};
  921:        }
  922:    }
  923:    return ($num,%texts);
  924: }
  925: 
  926: sub remove_lock {
  927:     my ($id)=@_;
  928:     my $newlocks='';
  929:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  930:        if (($lock=~/\w/) && ($lock ne $id)) {
  931:           $newlocks.=','.$lock;
  932:        }
  933:     }
  934:     &appenv({'session.locks' => $newlocks});
  935:     &delenv('session.lock.'.$id);
  936: }
  937: 
  938: sub remove_all_locks {
  939:     my $activelocks=$env{'session.locks'};
  940:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  941:        if ($lock=~/\w/) {
  942:           &remove_lock($lock);
  943:        }
  944:     }
  945: }
  946: 
  947: 
  948: # ------------------------------------------ Find out current server userload
  949: sub userload {
  950:     my $numusers=0;
  951:     {
  952: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  953: 	my $filename;
  954: 	my $curtime=time;
  955: 	while ($filename=readdir(LONIDS)) {
  956: 	    next if ($filename eq '.' || $filename eq '..');
  957: 	    next if ($filename =~ /publicuser_\d+\.id/);
  958:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  959: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  960: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  961: 	}
  962: 	closedir(LONIDS);
  963:     }
  964:     my $userloadpercent=0;
  965:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  966:     if ($maxuserload) {
  967: 	$userloadpercent=100*$numusers/$maxuserload;
  968:     }
  969:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  970:     return $userloadpercent;
  971: }
  972: 
  973: # ------------------------------ Find server with least workload from spare.tab
  974: 
  975: sub spareserver {
  976:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  977:     my $spare_server;
  978:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  979:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  980:                                                      :  $userloadpercent;
  981:     my ($uint_dom,$remotesessions);
  982:     if (($udom ne '') && (&domain($udom) ne '')) {
  983:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  984:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  985:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  986:         $remotesessions = $udomdefaults{'remotesessions'};
  987:     }
  988:     my $spareshash = &this_host_spares($udom);
  989:     if (ref($spareshash) eq 'HASH') {
  990:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  991:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  992:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  993:                                              $try_server));
  994: 	        ($spare_server, $lowest_load) =
  995: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  996:             }
  997:         }
  998: 
  999:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
 1000: 
 1001:         if (!$found_server) {
 1002:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1003: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1004:                     next unless (&spare_can_host($udom,$uint_dom,
 1005:                                                  $remotesessions,$try_server));
 1006: 	            ($spare_server, $lowest_load) =
 1007: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1008:                 }
 1009: 	    }
 1010:         }
 1011:     }
 1012: 
 1013:     if (!$want_server_name) {
 1014:         if (defined($spare_server)) {
 1015:             my $hostname = &hostname($spare_server);
 1016:             if (defined($hostname)) {
 1017:                 my $protocol = 'http';
 1018:                 if ($protocol{$spare_server} eq 'https') {
 1019:                     $protocol = $protocol{$spare_server};
 1020:                 }
 1021: 	        $spare_server = $protocol.'://'.$hostname;
 1022:             }
 1023:         }
 1024:     }
 1025:     return $spare_server;
 1026: }
 1027: 
 1028: sub compare_server_load {
 1029:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1030: 
 1031:     if ($required) {
 1032:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1033:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1034:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1035:         if (($major eq '' && $minor eq '') ||
 1036:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1037:             return ($spare_server,$lowest_load);
 1038:         }
 1039:     }
 1040: 
 1041:     my $loadans     = &reply('load',    $try_server);
 1042:     my $userloadans = &reply('userload',$try_server);
 1043: 
 1044:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1045: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1046:     }
 1047: 
 1048:     my $load;
 1049:     if ($loadans =~ /\d/) {
 1050: 	if ($userloadans =~ /\d/) {
 1051: 	    #both are numbers, pick the bigger one
 1052: 	    $load = ($loadans > $userloadans) ? $loadans 
 1053: 		                              : $userloadans;
 1054: 	} else {
 1055: 	    $load = $loadans;
 1056: 	}
 1057:     } else {
 1058: 	$load = $userloadans;
 1059:     }
 1060: 
 1061:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1062: 	$spare_server = $try_server;
 1063: 	$lowest_load  = $load;
 1064:     }
 1065:     return ($spare_server,$lowest_load);
 1066: }
 1067: 
 1068: # --------------------------- ask offload servers if user already has a session
 1069: sub find_existing_session {
 1070:     my ($udom,$uname) = @_;
 1071:     my $spareshash = &this_host_spares($udom);
 1072:     if (ref($spareshash) eq 'HASH') {
 1073:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1074:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1075:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1076:             }
 1077:         }
 1078:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1079:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1080:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1081:             }
 1082:         }
 1083:     }
 1084:     return;
 1085: }
 1086: 
 1087: sub delusersession {
 1088:     my ($lonid,$udom,$uname) = @_;
 1089:     my $uprimary_id = &domain($udom,'primary');
 1090:     my $uintdom = &internet_dom($uprimary_id);
 1091:     my $intdom = &internet_dom($lonid);
 1092:     my $serverhomedom = &host_domain($lonid);
 1093:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1094:         return &reply(join(':','delusersession',
 1095:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1096:     }
 1097:     return;
 1098: }
 1099: 
 1100: # check if user's browser sent load balancer cookie and server still has session
 1101: # and is not overloaded.
 1102: sub check_for_balancer_cookie {
 1103:     my ($r,$update_mtime) = @_;
 1104:     my ($otherserver,$cookie);
 1105:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1106:     if (exists($cookies{'balanceID'})) {
 1107:         my $balid = $cookies{'balanceID'};
 1108:         $cookie=&LONCAPA::clean_handle($balid->value);
 1109:         my $balancedir=$r->dir_config('lonBalanceDir');
 1110:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1111:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1112:                 my ($possudom,$possuname) = ($1,$2);
 1113:                 my $has_session = 0;
 1114:                 if ((&domain($possudom) ne '') &&
 1115:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1116:                     my $try_server;
 1117:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1118:                     if ($opened) {
 1119:                         flock($idf,LOCK_SH);
 1120:                         while (my $line = <$idf>) {
 1121:                             chomp($line);
 1122:                             if (&hostname($line) ne '') {
 1123:                                 $try_server = $line;
 1124:                                 last;
 1125:                             }
 1126:                         }
 1127:                         close($idf);
 1128:                         if (($try_server) &&
 1129:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1130:                             my $lowest_load = 30000;
 1131:                             ($otherserver,$lowest_load) =
 1132:                                 &compare_server_load($try_server,undef,$lowest_load);
 1133:                             if ($otherserver ne '' && $lowest_load < 100) {
 1134:                                 $has_session = 1;
 1135:                             } else {
 1136:                                 undef($otherserver);
 1137:                             }
 1138:                         }
 1139:                     }
 1140:                 }
 1141:                 if ($has_session) {
 1142:                     if ($update_mtime) {
 1143:                         my $atime = my $mtime = time;
 1144:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1145:                     }
 1146:                 } else {
 1147:                     unlink("$balancedir/$cookie.id");
 1148:                 }
 1149:             }
 1150:         }
 1151:     }
 1152:     return ($otherserver,$cookie);
 1153: }
 1154: 
 1155: sub updatebalcookie {
 1156:     my ($cookie,$balancer,$lastentry)=@_;
 1157:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1158:         my ($udom,$uname) = ($1,$2);
 1159:         my $uprimary_id = &domain($udom,'primary');
 1160:         my $uintdom = &internet_dom($uprimary_id);
 1161:         my $intdom = &internet_dom($balancer);
 1162:         my $serverhomedom = &host_domain($balancer);
 1163:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1164:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1165:         }
 1166:     }
 1167:     return;
 1168: }
 1169: 
 1170: sub delbalcookie {
 1171:     my ($cookie,$balancer) =@_;
 1172:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1173:         my ($udom,$uname) = ($1,$2);
 1174:         my $uprimary_id = &domain($udom,'primary');
 1175:         my $uintdom = &internet_dom($uprimary_id);
 1176:         my $intdom = &internet_dom($balancer);
 1177:         my $serverhomedom = &host_domain($balancer);
 1178:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1179:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1180:         }
 1181:     }
 1182: }
 1183: 
 1184: # -------------------------------- ask if server already has a session for user
 1185: sub has_user_session {
 1186:     my ($lonid,$udom,$uname) = @_;
 1187:     my $result = &reply(join(':','userhassession',
 1188: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1189:     return 1 if ($result eq 'ok');
 1190: 
 1191:     return 0;
 1192: }
 1193: 
 1194: # --------- determine least loaded server in a user's domain which allows login
 1195: 
 1196: sub choose_server {
 1197:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1198:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1199:     my %servers = &get_servers($udom);
 1200:     my $lowest_load = 30000;
 1201:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1202:     if ($skiploadbal) {
 1203:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1204:         unless (defined($cached)) {
 1205:             my $cachetime = 60*60*24;
 1206:             my %domconfig =
 1207:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1208:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1209:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1210:                                            $cachetime);
 1211:             }
 1212:         }
 1213:     }
 1214:     foreach my $lonhost (keys(%servers)) {
 1215:         if ($skiploadbal) {
 1216:             if (ref($balancers) eq 'HASH') {
 1217:                 next if (exists($balancers->{$lonhost}));
 1218:             }
 1219:         }
 1220:         my $loginvia;
 1221:         if ($checkloginvia) {
 1222:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1223:             if ($loginvia) {
 1224:                 my ($server,$path) = split(/:/,$loginvia);
 1225:                 ($login_host, $lowest_load) =
 1226:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1227:                 if ($login_host eq $server) {
 1228:                     $portal_path = $path;
 1229:                     $isredirect = 1;
 1230:                 }
 1231:             } else {
 1232:                 ($login_host, $lowest_load) =
 1233:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1234:                 if ($login_host eq $lonhost) {
 1235:                     $portal_path = '';
 1236:                     $isredirect = ''; 
 1237:                 }
 1238:             }
 1239:         } else {
 1240:             ($login_host, $lowest_load) =
 1241:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1242:         }
 1243:     }
 1244:     if ($login_host ne '') {
 1245:         $hostname = &hostname($login_host);
 1246:     }
 1247:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1248: }
 1249: 
 1250: sub get_course_sessions {
 1251:     my ($cnum,$cdom,$lastactivity) = @_;
 1252:     my %servers = &internet_dom_servers($cdom);
 1253:     my %returnhash;
 1254:     foreach my $server (sort(keys(%servers))) {
 1255:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1256:         my @pairs=split(/\&/,$rep);
 1257:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1258:             foreach my $item (@pairs) {
 1259:                 my ($key,$value)=split(/=/,$item,2);
 1260:                 $key = &unescape($key);
 1261:                 next if ($key =~ /^error: 2 /);
 1262:                 if (exists($returnhash{$key})) {
 1263:                     next if ($value < $returnhash{$key});
 1264:                 }
 1265:                 $returnhash{$key}=$value;
 1266:             }
 1267:         }
 1268:     }
 1269:     return %returnhash;
 1270: }
 1271: 
 1272: # --------------------------------------------- Try to change a user's password
 1273: 
 1274: sub changepass {
 1275:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1276:     $currentpass = &escape($currentpass);
 1277:     $newpass     = &escape($newpass);
 1278:     my $lonhost = $perlvar{'lonHostID'};
 1279:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1280: 		       $server);
 1281:     if (! $answer) {
 1282: 	&logthis("No reply on password change request to $server ".
 1283: 		 "by $uname in domain $udom.");
 1284:     } elsif ($answer =~ "^ok") {
 1285:         &logthis("$uname in $udom successfully changed their password ".
 1286: 		 "on $server.");
 1287:     } elsif ($answer =~ "^pwchange_failure") {
 1288: 	&logthis("$uname in $udom was unable to change their password ".
 1289: 		 "on $server.  The action was blocked by either lcpasswd ".
 1290: 		 "or pwchange");
 1291:     } elsif ($answer =~ "^non_authorized") {
 1292:         &logthis("$uname in $udom did not get their password correct when ".
 1293: 		 "attempting to change it on $server.");
 1294:     } elsif ($answer =~ "^auth_mode_error") {
 1295:         &logthis("$uname in $udom attempted to change their password despite ".
 1296: 		 "not being locally or internally authenticated on $server.");
 1297:     } elsif ($answer =~ "^unknown_user") {
 1298:         &logthis("$uname in $udom attempted to change their password ".
 1299: 		 "on $server but were unable to because $server is not ".
 1300: 		 "their home server.");
 1301:     } elsif ($answer =~ "^refused") {
 1302: 	&logthis("$server refused to change $uname in $udom password because ".
 1303: 		 "it was sent an unencrypted request to change the password.");
 1304:     } elsif ($answer =~ "invalid_client") {
 1305:         &logthis("$server refused to change $uname in $udom password because ".
 1306:                  "it was a reset by e-mail originating from an invalid server.");
 1307:     } elsif ($answer =~ "^prioruse") {
 1308:        &logthis("$server refused to change $uname in $udom password because ".
 1309:                 "the password had been used before");
 1310:     }
 1311:     return $answer;
 1312: }
 1313: 
 1314: # ----------------------- Try to determine user's current authentication scheme
 1315: 
 1316: sub queryauthenticate {
 1317:     my ($uname,$udom)=@_;
 1318:     my $uhome=&homeserver($uname,$udom);
 1319:     if (!$uhome) {
 1320: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1321: 	return 'no_host';
 1322:     }
 1323:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1324:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1325: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1326:     }
 1327:     return $answer;
 1328: }
 1329: 
 1330: # --------- Try to authenticate user from domain's lib servers (first this one)
 1331: 
 1332: sub authenticate {
 1333:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1334:     $upass=&escape($upass);
 1335:     $uname= &LONCAPA::clean_username($uname);
 1336:     my $uhome=&homeserver($uname,$udom,1);
 1337:     my $newhome;
 1338:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1339: # Maybe the machine was offline and only re-appeared again recently?
 1340:         &reconlonc();
 1341: # One more
 1342: 	$uhome=&homeserver($uname,$udom,1);
 1343:         if (($uhome eq 'no_host') && $checkdefauth) {
 1344:             if (defined(&domain($udom,'primary'))) {
 1345:                 $newhome=&domain($udom,'primary');
 1346:             }
 1347:             if ($newhome ne '') {
 1348:                 $uhome = $newhome;
 1349:             }
 1350:         }
 1351: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1352: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1353: 	    return 'no_host';
 1354:         }
 1355:     }
 1356:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1357:     if ($answer eq 'authorized') {
 1358:         if ($newhome) {
 1359:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1360:             return 'no_account_on_host'; 
 1361:         } else {
 1362:             &logthis("User $uname at $udom authorized by $uhome");
 1363:             return $uhome;
 1364:         }
 1365:     }
 1366:     if ($answer eq 'non_authorized') {
 1367: 	&logthis("User $uname at $udom rejected by $uhome");
 1368: 	return 'no_host'; 
 1369:     }
 1370:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1371:     return 'no_host';
 1372: }
 1373: 
 1374: sub can_host_session {
 1375:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1376:     my $canhost = 1;
 1377:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1378:     if (ref($remotesessions) eq 'HASH') {
 1379:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1380:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1381:                 $canhost = 0;
 1382:             } else {
 1383:                 $canhost = 1;
 1384:             }
 1385:         }
 1386:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1387:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1388:                 $canhost = 1;
 1389:             } else {
 1390:                 $canhost = 0;
 1391:             }
 1392:         }
 1393:         if ($canhost) {
 1394:             if ($remotesessions->{'version'} ne '') {
 1395:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1396:                 if ($reqmajor ne '' && $reqminor ne '') {
 1397:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1398:                         my $major = $1;
 1399:                         my $minor = $2;
 1400:                         if (($major < $reqmajor ) ||
 1401:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1402:                             $canhost = 0;
 1403:                         }
 1404:                     } else {
 1405:                         $canhost = 0;
 1406:                     }
 1407:                 }
 1408:             }
 1409:         }
 1410:     }
 1411:     if ($canhost) {
 1412:         if (ref($hostedsessions) eq 'HASH') {
 1413:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1414:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1415:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1416:                 if (($uint_dom ne '') && 
 1417:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1418:                     $canhost = 0;
 1419:                 } else {
 1420:                     $canhost = 1;
 1421:                 }
 1422:             }
 1423:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1424:                 if (($uint_dom ne '') && 
 1425:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1426:                     $canhost = 1;
 1427:                 } else {
 1428:                     $canhost = 0;
 1429:                 }
 1430:             }
 1431:         }
 1432:     }
 1433:     return $canhost;
 1434: }
 1435: 
 1436: sub spare_can_host {
 1437:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1438:     my $canhost=1;
 1439:     my $try_server_hostname = &hostname($try_server);
 1440:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1441:     my $serverhomedom = &host_domain($serverhomeID);
 1442:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1443:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1444:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1445:             $canhost = 0;
 1446:         }
 1447:     }
 1448:     if (($canhost) && ($uint_dom)) {
 1449:         my @intdoms;
 1450:         my $internet_names = &get_internet_names($try_server);
 1451:         if (ref($internet_names) eq 'ARRAY') {
 1452:             @intdoms = @{$internet_names};
 1453:         }
 1454:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1455:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1456:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1457:                                          $remotesessions,
 1458:                                          $defdomdefaults{'hostedsessions'});
 1459:         }
 1460:     }
 1461:     return $canhost;
 1462: }
 1463: 
 1464: sub this_host_spares {
 1465:     my ($dom) = @_;
 1466:     my ($dom_in_use,$lonhost_in_use,$result);
 1467:     my @hosts = &current_machine_ids();
 1468:     foreach my $lonhost (@hosts) {
 1469:         if (&host_domain($lonhost) eq $dom) {
 1470:             $dom_in_use = $dom;
 1471:             $lonhost_in_use = $lonhost;
 1472:             last;
 1473:         }
 1474:     }
 1475:     if ($dom_in_use ne '') {
 1476:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1477:     }
 1478:     if (ref($result) ne 'HASH') {
 1479:         $lonhost_in_use = $perlvar{'lonHostID'};
 1480:         $dom_in_use = &host_domain($lonhost_in_use);
 1481:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1482:         if (ref($result) ne 'HASH') {
 1483:             $result = \%spareid;
 1484:         }
 1485:     }
 1486:     return $result;
 1487: }
 1488: 
 1489: sub spares_for_offload  {
 1490:     my ($dom_in_use,$lonhost_in_use) = @_;
 1491:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1492:     if (defined($cached)) {
 1493:         return $result;
 1494:     } else {
 1495:         my $cachetime = 60*60*24;
 1496:         my %domconfig =
 1497:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1498:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1499:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1500:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1501:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1502:                 }
 1503:             }
 1504:         }
 1505:     }
 1506:     return;
 1507: }
 1508: 
 1509: sub get_lonbalancer_config {
 1510:     my ($servers) = @_;
 1511:     my ($currbalancer,$currtargets);
 1512:     if (ref($servers) eq 'HASH') {
 1513:         foreach my $server (keys(%{$servers})) {
 1514:             my %what = (
 1515:                          spareid => 1,
 1516:                          perlvar => 1,
 1517:                        );
 1518:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1519:             if ($result eq 'ok') {
 1520:                 if (ref($returnhash) eq 'HASH') {
 1521:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1522:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1523:                             $currbalancer = $server;
 1524:                             $currtargets = {};
 1525:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1526:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1527:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1528:                                 }
 1529:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1530:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1531:                                 }
 1532:                             }
 1533:                             last;
 1534:                         }
 1535:                     }
 1536:                 }
 1537:             }
 1538:         }
 1539:     }
 1540:     return ($currbalancer,$currtargets);
 1541: }
 1542: 
 1543: sub check_loadbalancing {
 1544:     my ($uname,$udom,$caller) = @_;
 1545:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1546:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1547:     my $lonhost = $perlvar{'lonHostID'};
 1548:     my @hosts = &current_machine_ids();
 1549:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1550:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1551:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1552:     my $serverhomedom = &host_domain($lonhost);
 1553:     my $domneedscache;
 1554:     my $cachetime = 60*60*24;
 1555: 
 1556:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1557:         $dom_in_use = $udom;
 1558:         $homeintdom = 1;
 1559:     } else {
 1560:         $dom_in_use = $serverhomedom;
 1561:     }
 1562:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1563:     unless (defined($cached)) {
 1564:         my %domconfig =
 1565:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1566:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1567:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1568:         } else {
 1569:             $domneedscache = $dom_in_use;
 1570:         }
 1571:     }
 1572:     if (ref($result) eq 'HASH') {
 1573:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1574:             &check_balancer_result($result,@hosts);
 1575:         if ($is_balancer) {
 1576:             if (ref($currrules) eq 'HASH') {
 1577:                 if ($homeintdom) {
 1578:                     if ($uname ne '') {
 1579:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1580:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1581:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1582:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1583:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1584:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1585:                             }
 1586:                         }
 1587:                         if ($rule_in_effect eq '') {
 1588:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1589:                             if ($userenv{'inststatus'} ne '') {
 1590:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1591:                                 my ($othertitle,$usertypes,$types) =
 1592:                                     &Apache::loncommon::sorted_inst_types($udom);
 1593:                                 if (ref($types) eq 'ARRAY') {
 1594:                                     foreach my $type (@{$types}) {
 1595:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1596:                                             if (exists($currrules->{$type})) {
 1597:                                                 $rule_in_effect = $currrules->{$type};
 1598:                                             }
 1599:                                         }
 1600:                                     }
 1601:                                 }
 1602:                             } else {
 1603:                                 if (exists($currrules->{'default'})) {
 1604:                                     $rule_in_effect = $currrules->{'default'};
 1605:                                 }
 1606:                             }
 1607:                         }
 1608:                     } else {
 1609:                         if (exists($currrules->{'default'})) {
 1610:                             $rule_in_effect = $currrules->{'default'};
 1611:                         }
 1612:                     }
 1613:                 } else {
 1614:                     if ($currrules->{'_LC_external'} ne '') {
 1615:                         $rule_in_effect = $currrules->{'_LC_external'};
 1616:                     }
 1617:                 }
 1618:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1619:                                                        $uname,$udom);
 1620:             }
 1621:         }
 1622:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1623:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1624:         unless (defined($cached)) {
 1625:             my %domconfig =
 1626:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1627:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1628:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1629:             } else {
 1630:                 $domneedscache = $serverhomedom;
 1631:             }
 1632:         }
 1633:         if (ref($result) eq 'HASH') {
 1634:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1635:                 &check_balancer_result($result,@hosts);
 1636:             if ($is_balancer) {
 1637:                 if (ref($currrules) eq 'HASH') {
 1638:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1639:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1640:                     }
 1641:                 }
 1642:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1643:                                                        $uname,$udom);
 1644:             }
 1645:         } else {
 1646:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1647:                 $is_balancer = 1;
 1648:                 $offloadto = &this_host_spares($dom_in_use);
 1649:             }
 1650:             unless (defined($cached)) {
 1651:                 $domneedscache = $serverhomedom;
 1652:             }
 1653:         }
 1654:     } else {
 1655:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1656:             $is_balancer = 1;
 1657:             $offloadto = &this_host_spares($dom_in_use);
 1658:         }
 1659:         unless (defined($cached)) {
 1660:             $domneedscache = $serverhomedom;
 1661:         }
 1662:     }
 1663:     if ($domneedscache) {
 1664:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1665:     }
 1666:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1667:         my $lowest_load = 30000;
 1668:         if (ref($offloadto) eq 'HASH') {
 1669:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1670:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1671:                     ($otherserver,$lowest_load) =
 1672:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1673:                 }
 1674:             }
 1675:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1676: 
 1677:             if (!$found_server) {
 1678:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1679:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1680:                         ($otherserver,$lowest_load) =
 1681:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1682:                     }
 1683:                 }
 1684:             }
 1685:         } elsif (ref($offloadto) eq 'ARRAY') {
 1686:             if (@{$offloadto} == 1) {
 1687:                 $otherserver = $offloadto->[0];
 1688:             } elsif (@{$offloadto} > 1) {
 1689:                 foreach my $try_server (@{$offloadto}) {
 1690:                     ($otherserver,$lowest_load) =
 1691:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1692:                 }
 1693:             }
 1694:         }
 1695:         unless ($caller eq 'login') {
 1696:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1697:                 $is_balancer = 0;
 1698:                 if ($uname ne '' && $udom ne '') {
 1699:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1700:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1701:                                  'user.loadbalcheck.time' => time});
 1702:                     }
 1703:                 }
 1704:             }
 1705:         }
 1706:     }
 1707:     if (($is_balancer) && (!$homeintdom)) {
 1708:         undef($setcookie);
 1709:     }
 1710:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1711: }
 1712: 
 1713: sub check_balancer_result {
 1714:     my ($result,@hosts) = @_;
 1715:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1716:     if (ref($result) eq 'HASH') {
 1717:         if ($result->{'lonhost'} ne '') {
 1718:             my $currbalancer = $result->{'lonhost'};
 1719:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1720:                 $is_balancer = 1;
 1721:                 $currtargets = $result->{'targets'};
 1722:                 $currrules = $result->{'rules'};
 1723:             }
 1724:             $dom_balancers = $currbalancer;
 1725:         } else {
 1726:             if (keys(%{$result})) {
 1727:                 foreach my $key (keys(%{$result})) {
 1728:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1729:                         (ref($result->{$key}) eq 'HASH')) {
 1730:                         $is_balancer = 1;
 1731:                         $currrules = $result->{$key}{'rules'};
 1732:                         $currtargets = $result->{$key}{'targets'};
 1733:                         $setcookie = $result->{$key}{'cookie'};
 1734:                         last;
 1735:                     }
 1736:                 }
 1737:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1738:             }
 1739:         }
 1740:     }
 1741:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1742: }
 1743: 
 1744: sub get_loadbalancer_targets {
 1745:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1746:     my $offloadto;
 1747:     if ($rule_in_effect eq 'none') {
 1748:         return [$perlvar{'lonHostID'}];
 1749:     } elsif ($rule_in_effect eq '') {
 1750:         $offloadto = $currtargets;
 1751:     } else {
 1752:         if ($rule_in_effect eq 'homeserver') {
 1753:             my $homeserver = &homeserver($uname,$udom);
 1754:             if ($homeserver ne 'no_host') {
 1755:                 $offloadto = [$homeserver];
 1756:             }
 1757:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1758:             my %domconfig =
 1759:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1760:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1761:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1762:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1763:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1764:                     }
 1765:                 }
 1766:             } else {
 1767:                 my %servers = &internet_dom_servers($udom);
 1768:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1769:                 if (&hostname($remotebalancer) ne '') {
 1770:                     $offloadto = [$remotebalancer];
 1771:                 }
 1772:             }
 1773:         } elsif (&hostname($rule_in_effect) ne '') {
 1774:             $offloadto = [$rule_in_effect];
 1775:         }
 1776:     }
 1777:     return $offloadto;
 1778: }
 1779: 
 1780: sub internet_dom_servers {
 1781:     my ($dom) = @_;
 1782:     my (%uniqservers,%servers);
 1783:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1784:     my @machinedoms = &machine_domains($primaryserver);
 1785:     foreach my $mdom (@machinedoms) {
 1786:         my %currservers = %servers;
 1787:         my %server = &get_servers($mdom);
 1788:         %servers = (%currservers,%server);
 1789:     }
 1790:     my %by_hostname;
 1791:     foreach my $id (keys(%servers)) {
 1792:         push(@{$by_hostname{$servers{$id}}},$id);
 1793:     }
 1794:     foreach my $hostname (sort(keys(%by_hostname))) {
 1795:         if (@{$by_hostname{$hostname}} > 1) {
 1796:             my $match = 0;
 1797:             foreach my $id (@{$by_hostname{$hostname}}) {
 1798:                 if (&host_domain($id) eq $dom) {
 1799:                     $uniqservers{$id} = $hostname;
 1800:                     $match = 1;
 1801:                 }
 1802:             }
 1803:             unless ($match) {
 1804:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1805:             }
 1806:         } else {
 1807:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1808:         }
 1809:     }
 1810:     return %uniqservers;
 1811: }
 1812: 
 1813: sub trusted_domains {
 1814:     my ($cmdtype,$calldom) = @_;
 1815:     my ($trusted,$untrusted);
 1816:     if (&domain($calldom) eq '') {
 1817:         return ($trusted,$untrusted);
 1818:     }
 1819:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1820:         return ($trusted,$untrusted);
 1821:     }
 1822:     my $callprimary = &domain($calldom,'primary');
 1823:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1824:     if ($intcalldom eq '') {
 1825:         return ($trusted,$untrusted);
 1826:     }
 1827: 
 1828:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1829:     unless (defined($cached)) {
 1830:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1831:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1832:         $trustconfig = $domconfig{'trust'};
 1833:     }
 1834:     if (ref($trustconfig)) {
 1835:         my (%possexc,%possinc,@allexc,@allinc); 
 1836:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1837:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1838:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1839:             }
 1840:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1841:                 $possinc{$intcalldom} = 1;
 1842:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1843:             }
 1844:         }
 1845:         if (keys(%possexc)) {
 1846:             if (keys(%possinc)) {
 1847:                 foreach my $key (sort(keys(%possexc))) {
 1848:                     next if ($key eq $intcalldom);
 1849:                     unless ($possinc{$key}) {
 1850:                         push(@allexc,$key);
 1851:                     }
 1852:                 }
 1853:             } else {
 1854:                 @allexc = sort(keys(%possexc));
 1855:             }
 1856:         }
 1857:         if (keys(%possinc)) {
 1858:             $possinc{$intcalldom} = 1;
 1859:             @allinc = sort(keys(%possinc));
 1860:         }
 1861:         if ((@allexc > 0) || (@allinc > 0)) {
 1862:             my %doms_by_intdom;
 1863:             my %allintdoms = &all_host_intdom();
 1864:             my %alldoms = &all_host_domain();
 1865:             foreach my $key (%allintdoms) {
 1866:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1867:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1868:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1869:                     }
 1870:                 } else {
 1871:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1872:                 }
 1873:             }
 1874:             foreach my $exc (@allexc) {
 1875:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1876:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1877:                 }
 1878:             }
 1879:             foreach my $inc (@allinc) {
 1880:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1881:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1882:                 }
 1883:             }
 1884:         }
 1885:     }
 1886:     return ($trusted,$untrusted);
 1887: }
 1888: 
 1889: sub will_trust {
 1890:     my ($cmdtype,$domain,$possdom) = @_;
 1891:     return 1 if ($domain eq $possdom);
 1892:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1893:     my $willtrust; 
 1894:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1895:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1896:             $willtrust = 1;
 1897:         }
 1898:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1899:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1900:             $willtrust = 1;
 1901:         }
 1902:     } else {
 1903:         $willtrust = 1;
 1904:     }
 1905:     return $willtrust;
 1906: }
 1907: 
 1908: # ---------------------- Find the homebase for a user from domain's lib servers
 1909: 
 1910: my %homecache;
 1911: sub homeserver {
 1912:     my ($uname,$udom,$ignoreBadCache)=@_;
 1913:     my $index="$uname:$udom";
 1914: 
 1915:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1916: 
 1917:     my %servers = &get_servers($udom,'library');
 1918:     foreach my $tryserver (keys(%servers)) {
 1919:         next if ($ignoreBadCache ne 'true' && 
 1920: 		 exists($badServerCache{$tryserver}));
 1921: 
 1922: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1923: 	if ($answer eq 'found') {
 1924: 	    delete($badServerCache{$tryserver}); 
 1925: 	    return $homecache{$index}=$tryserver;
 1926: 	} elsif ($answer eq 'no_host') {
 1927: 	    $badServerCache{$tryserver}=1;
 1928: 	}
 1929:     }    
 1930:     return 'no_host';
 1931: }
 1932: 
 1933: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1934: 
 1935: sub idget {
 1936:     my ($udom,$idsref,$namespace)=@_;
 1937:     my %returnhash=();
 1938:     my @ids=(); 
 1939:     if (ref($idsref) eq 'ARRAY') {
 1940:         @ids = @{$idsref};
 1941:     } else {
 1942:         return %returnhash; 
 1943:     }
 1944:     if ($namespace eq '') {
 1945:         $namespace = 'ids';
 1946:     }
 1947:     
 1948:     my %servers = &get_servers($udom,'library');
 1949:     foreach my $tryserver (keys(%servers)) {
 1950: 	my $idlist=join('&', map { &escape($_); } @ids);
 1951: 	if ($namespace eq 'ids') {
 1952: 	    $idlist=~tr/A-Z/a-z/;
 1953: 	}
 1954: 	my $reply;
 1955: 	if ($namespace eq 'ids') {
 1956: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1957: 	} else {
 1958: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1959: 	}
 1960: 	my @answer=();
 1961: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1962: 	    @answer=split(/\&/,$reply);
 1963: 	}                    ;
 1964: 	my $i;
 1965: 	for ($i=0;$i<=$#ids;$i++) {
 1966: 	    if ($answer[$i]) {
 1967: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1968: 	    }
 1969: 	}
 1970:     }
 1971:     return %returnhash;
 1972: }
 1973: 
 1974: # ------------------------------------- Find the IDs behind a list of usernames
 1975: 
 1976: sub idrget {
 1977:     my ($udom,@unames)=@_;
 1978:     my %returnhash=();
 1979:     foreach my $uname (@unames) {
 1980:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1981:     }
 1982:     return %returnhash;
 1983: }
 1984: 
 1985: # Store away a list of names and associated student/employee IDs or clicker IDs
 1986: 
 1987: sub idput {
 1988:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1989:     my %servers=();
 1990:     my %ids=();
 1991:     my %byid = ();
 1992:     if (ref($idsref) eq 'HASH') {
 1993:         %ids=%{$idsref};
 1994:     }
 1995:     if ($namespace eq '') {
 1996:         $namespace = 'ids'; 
 1997:     }
 1998:     foreach my $uname (keys(%ids)) {
 1999: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 2000:         if ($uhom eq '') {
 2001:             $uhom=&homeserver($uname,$udom);
 2002:         }
 2003:         if ($uhom ne 'no_host') {
 2004:             my $esc_unam=&escape($uname);
 2005:             if ($namespace eq 'ids') {
 2006:                 my $id=&escape($ids{$uname});
 2007:                 $id=~tr/A-Z/a-z/;
 2008:                 my $esc_unam=&escape($uname);
 2009:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2010:             } else {
 2011:                 my @currids = split(/,/,$ids{$uname});
 2012:                 foreach my $id (@currids) {
 2013:                     $byid{$uhom}{$id} .= $uname.',';
 2014:                 }
 2015:             }
 2016:         }
 2017:     }
 2018:     if ($namespace eq 'clickers') {
 2019:         foreach my $server (keys(%byid)) {
 2020:             if (ref($byid{$server}) eq 'HASH') {
 2021:                 foreach my $id (keys(%{$byid{$server}})) {
 2022:                     $byid{$server} =~ s/,$//;
 2023:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2024:                 }
 2025:             }
 2026:         }
 2027:     }
 2028:     foreach my $server (keys(%servers)) {
 2029:         $servers{$server} =~ s/\&$//;
 2030:         if ($namespace eq 'ids') {     
 2031:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2032:         } else {
 2033:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2034:         }
 2035:     }
 2036: }
 2037: 
 2038: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2039: 
 2040: sub iddel {
 2041:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2042:     my %result=();
 2043:     my %ids=();
 2044:     my %byid = ();
 2045:     if (ref($idshashref) eq 'HASH') {
 2046:         %ids=%{$idshashref};
 2047:     } else {
 2048:         return %result;
 2049:     }
 2050:     if ($namespace eq '') {
 2051:         $namespace = 'ids';
 2052:     }
 2053:     my %servers=();
 2054:     while (my ($id,$unamestr) = each(%ids)) {
 2055:         if ($namespace eq 'ids') {
 2056:             my $uhom = $uhome;
 2057:             if ($uhom eq '') { 
 2058:                 $uhom=&homeserver($unamestr,$udom);
 2059:             }
 2060:             if ($uhom ne 'no_host') {
 2061:                 $servers{$uhom}.='&'.&escape($id);
 2062:             }
 2063:          } else {
 2064:             my @curritems = split(/,/,$ids{$id});
 2065:             foreach my $uname (@curritems) {
 2066:                 my $uhom = $uhome;
 2067:                 if ($uhom eq '') {
 2068:                     $uhom=&homeserver($uname,$udom);
 2069:                 }
 2070:                 if ($uhom ne 'no_host') { 
 2071:                     $byid{$uhom}{$id} .= $uname.',';
 2072:                 }
 2073:             }
 2074:         }
 2075:     }
 2076:     if ($namespace eq 'clickers') {
 2077:         foreach my $server (keys(%byid)) {
 2078:             if (ref($byid{$server}) eq 'HASH') {
 2079:                 foreach my $id (keys(%{$byid{$server}})) {
 2080:                     $byid{$server}{$id} =~ s/,$//;
 2081:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2082:                 }
 2083:             }
 2084:         }
 2085:     }
 2086:     foreach my $server (keys(%servers)) {
 2087:         $servers{$server} =~ s/\&$//;
 2088:         if ($namespace eq 'ids') {
 2089:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2090:         } elsif ($namespace eq 'clickers') {
 2091:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2092:         }
 2093:     }
 2094:     return %result;
 2095: }
 2096: 
 2097: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2098: 
 2099: sub updateclickers {
 2100:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2101:     my %clickers;
 2102:     if (ref($idshashref) eq 'HASH') {
 2103:         %clickers=%{$idshashref};
 2104:     } else {
 2105:         return;
 2106:     }
 2107:     my $items='';
 2108:     foreach my $item (keys(%clickers)) {
 2109:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2110:     }
 2111:     $items=~s/\&$//;
 2112:     my $request = "updateclickers:$udom:$action:$items";
 2113:     if ($critical) {
 2114:         return &critical($request,$uhome);
 2115:     } else {
 2116:         return &reply($request,$uhome);
 2117:     }
 2118: }
 2119: 
 2120: # ------------------------------dump from db file owned by domainconfig user
 2121: sub dump_dom {
 2122:     my ($namespace, $udom, $regexp) = @_;
 2123: 
 2124:     $udom ||= $env{'user.domain'};
 2125: 
 2126:     return () unless $udom;
 2127: 
 2128:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2129: }
 2130: 
 2131: # ------------------------------------------ get items from domain db files   
 2132: 
 2133: sub get_dom {
 2134:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2135:     return if ($udom eq 'public');
 2136:     my $items='';
 2137:     foreach my $item (@$storearr) {
 2138:         $items.=&escape($item).'&';
 2139:     }
 2140:     $items=~s/\&$//;
 2141:     if (!$udom) {
 2142:         $udom=$env{'user.domain'};
 2143:         return if ($udom eq 'public');
 2144:         if (defined(&domain($udom,'primary'))) {
 2145:             $uhome=&domain($udom,'primary');
 2146:         } else {
 2147:             undef($uhome);
 2148:         }
 2149:     } else {
 2150:         if (!$uhome) {
 2151:             if (defined(&domain($udom,'primary'))) {
 2152:                 $uhome=&domain($udom,'primary');
 2153:             }
 2154:         }
 2155:     }
 2156:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2157:         my $rep;
 2158:         if ($namespace =~ /^enc/) {
 2159:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2160:         } else {
 2161:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2162:         }
 2163:         my %returnhash;
 2164:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2165:             return %returnhash;
 2166:         }
 2167:         my @pairs=split(/\&/,$rep);
 2168:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2169:             return @pairs;
 2170:         }
 2171:         my $i=0;
 2172:         foreach my $item (@$storearr) {
 2173:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2174:             $i++;
 2175:         }
 2176:         return %returnhash;
 2177:     } else {
 2178:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2179:     }
 2180: }
 2181: 
 2182: # -------------------------------------------- put items in domain db files 
 2183: 
 2184: sub put_dom {
 2185:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2186:     if (!$udom) {
 2187:         $udom=$env{'user.domain'};
 2188:         if (defined(&domain($udom,'primary'))) {
 2189:             $uhome=&domain($udom,'primary');
 2190:         } else {
 2191:             undef($uhome);
 2192:         }
 2193:     } else {
 2194:         if (!$uhome) {
 2195:             if (defined(&domain($udom,'primary'))) {
 2196:                 $uhome=&domain($udom,'primary');
 2197:             }
 2198:         }
 2199:     } 
 2200:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2201:         my $items='';
 2202:         foreach my $item (keys(%$storehash)) {
 2203:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2204:         }
 2205:         $items=~s/\&$//;
 2206:         if ($namespace =~ /^enc/) {
 2207:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2208:         } else {
 2209:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2210:         }
 2211:     } else {
 2212:         &logthis("put_dom failed - no homeserver and/or domain");
 2213:     }
 2214: }
 2215: 
 2216: # --------------------- newput for items in db file owned by domainconfig user
 2217: sub newput_dom {
 2218:     my ($namespace,$storehash,$udom) = @_;
 2219:     my $result;
 2220:     if (!$udom) {
 2221:         $udom=$env{'user.domain'};
 2222:     }
 2223:     if ($udom) {
 2224:         my $uname = &get_domainconfiguser($udom);
 2225:         $result = &newput($namespace,$storehash,$udom,$uname);
 2226:     }
 2227:     return $result;
 2228: }
 2229: 
 2230: # --------------------- delete for items in db file owned by domainconfig user
 2231: sub del_dom {
 2232:     my ($namespace,$storearr,$udom)=@_;
 2233:     if (ref($storearr) eq 'ARRAY') {
 2234:         if (!$udom) {
 2235:             $udom=$env{'user.domain'};
 2236:         }
 2237:         if ($udom) {
 2238:             my $uname = &get_domainconfiguser($udom); 
 2239:             return &del($namespace,$storearr,$udom,$uname);
 2240:         }
 2241:     }
 2242: }
 2243: 
 2244: # ----------------------------------construct domainconfig user for a domain 
 2245: sub get_domainconfiguser {
 2246:     my ($udom) = @_;
 2247:     return $udom.'-domainconfig';
 2248: }
 2249: 
 2250: sub retrieve_inst_usertypes {
 2251:     my ($udom) = @_;
 2252:     my (%returnhash,@order);
 2253:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2254:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2255:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2256:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2257:     } else {
 2258:         if (defined(&domain($udom,'primary'))) {
 2259:             my $uhome=&domain($udom,'primary');
 2260:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2261:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2262:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2263:                 return (\%returnhash,\@order);
 2264:             }
 2265:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2266:             my @pairs=split(/\&/,$hashitems);
 2267:             foreach my $item (@pairs) {
 2268:                 my ($key,$value)=split(/=/,$item,2);
 2269:                 $key = &unescape($key);
 2270:                 next if ($key =~ /^error: 2 /);
 2271:                 $returnhash{$key}=&thaw_unescape($value);
 2272:             }
 2273:             my @esc_order = split(/\&/,$orderitems);
 2274:             foreach my $item (@esc_order) {
 2275:                 push(@order,&unescape($item));
 2276:             }
 2277:         } else {
 2278:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2279:         }
 2280:         return (\%returnhash,\@order);
 2281:     }
 2282: }
 2283: 
 2284: sub is_domainimage {
 2285:     my ($url) = @_;
 2286:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2287:         if (&domain($1) ne '') {
 2288:             return '1';
 2289:         }
 2290:     }
 2291:     return;
 2292: }
 2293: 
 2294: sub inst_directory_query {
 2295:     my ($srch) = @_;
 2296:     my $udom = $srch->{'srchdomain'};
 2297:     my %results;
 2298:     my $homeserver = &domain($udom,'primary');
 2299:     my $outcome;
 2300:     if ($homeserver ne '') {
 2301:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2302:             if ($srch->{'srchby'} eq 'email') {
 2303:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2304:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2305:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2306:                     (($major == 2) && ($minor < 12))) {
 2307:                     return;
 2308:                 }
 2309:             }
 2310:         }
 2311: 	my $queryid=&reply("querysend:instdirsearch:".
 2312: 			   &escape($srch->{'srchby'}).':'.
 2313: 			   &escape($srch->{'srchterm'}).':'.
 2314: 			   &escape($srch->{'srchtype'}),$homeserver);
 2315: 	my $host=&hostname($homeserver);
 2316: 	if ($queryid !~/^\Q$host\E\_/) {
 2317: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2318: 	    return;
 2319: 	}
 2320: 	my $response = &get_query_reply($queryid);
 2321: 	my $maxtries = 5;
 2322: 	my $tries = 1;
 2323: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2324: 	    $response = &get_query_reply($queryid);
 2325: 	    $tries ++;
 2326: 	}
 2327: 
 2328:         if (!&error($response) && $response ne 'refused') {
 2329:             if ($response eq 'unavailable') {
 2330:                 $outcome = $response;
 2331:             } else {
 2332:                 $outcome = 'ok';
 2333:                 my @matches = split(/\n/,$response);
 2334:                 foreach my $match (@matches) {
 2335:                     my ($key,$value) = split(/=/,$match);
 2336:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2337:                 }
 2338:             }
 2339:         }
 2340:     }
 2341:     return ($outcome,%results);
 2342: }
 2343: 
 2344: sub usersearch {
 2345:     my ($srch) = @_;
 2346:     my $dom = $srch->{'srchdomain'};
 2347:     my %results;
 2348:     my %libserv = &all_library();
 2349:     my $query = 'usersearch';
 2350:     foreach my $tryserver (keys(%libserv)) {
 2351:         if (&host_domain($tryserver) eq $dom) {
 2352:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2353:                 if ($srch->{'srchby'} eq 'email') {
 2354:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2355:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2356:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2357:                              (($major == 2) && ($minor < 12)));
 2358:                 }
 2359:             }
 2360:             my $host=&hostname($tryserver);
 2361:             my $queryid=
 2362:                 &reply("querysend:".&escape($query).':'.
 2363:                        &escape($srch->{'srchby'}).':'.
 2364:                        &escape($srch->{'srchtype'}).':'.
 2365:                        &escape($srch->{'srchterm'}),$tryserver);
 2366:             if ($queryid !~/^\Q$host\E\_/) {
 2367:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2368:                 next;
 2369:             }
 2370:             my $reply = &get_query_reply($queryid);
 2371:             my $maxtries = 1;
 2372:             my $tries = 1;
 2373:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2374:                 $reply = &get_query_reply($queryid);
 2375:                 $tries ++;
 2376:             }
 2377:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2378:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2379:             } else {
 2380:                 my @matches;
 2381:                 if ($reply =~ /\n/) {
 2382:                     @matches = split(/\n/,$reply);
 2383:                 } else {
 2384:                     @matches = split(/\&/,$reply);
 2385:                 }
 2386:                 foreach my $match (@matches) {
 2387:                     my ($uname,$udom,%userhash);
 2388:                     foreach my $entry (split(/:/,$match)) {
 2389:                         my ($key,$value) =
 2390:                             map {&unescape($_);} split(/=/,$entry);
 2391:                         $userhash{$key} = $value;
 2392:                         if ($key eq 'username') {
 2393:                             $uname = $value;
 2394:                         } elsif ($key eq 'domain') {
 2395:                             $udom = $value;
 2396:                         }
 2397:                     }
 2398:                     $results{$uname.':'.$udom} = \%userhash;
 2399:                 }
 2400:             }
 2401:         }
 2402:     }
 2403:     return %results;
 2404: }
 2405: 
 2406: sub get_instuser {
 2407:     my ($udom,$uname,$id) = @_;
 2408:     my $homeserver = &domain($udom,'primary');
 2409:     my ($outcome,%results);
 2410:     if ($homeserver ne '') {
 2411:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2412:                            &escape($id).':'.&escape($udom),$homeserver);
 2413:         my $host=&hostname($homeserver);
 2414:         if ($queryid !~/^\Q$host\E\_/) {
 2415:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2416:             return;
 2417:         }
 2418:         my $response = &get_query_reply($queryid);
 2419:         my $maxtries = 5;
 2420:         my $tries = 1;
 2421:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2422:             $response = &get_query_reply($queryid);
 2423:             $tries ++;
 2424:         }
 2425:         if (!&error($response) && $response ne 'refused') {
 2426:             if ($response eq 'unavailable') {
 2427:                 $outcome = $response;
 2428:             } else {
 2429:                 $outcome = 'ok';
 2430:                 my @matches = split(/\n/,$response);
 2431:                 foreach my $match (@matches) {
 2432:                     my ($key,$value) = split(/=/,$match);
 2433:                     $results{&unescape($key)} = &thaw_unescape($value);
 2434:                 }
 2435:             }
 2436:         }
 2437:     }
 2438:     my %userinfo;
 2439:     if (ref($results{$uname}) eq 'HASH') {
 2440:         %userinfo = %{$results{$uname}};
 2441:     } 
 2442:     return ($outcome,%userinfo);
 2443: }
 2444: 
 2445: sub get_multiple_instusers {
 2446:     my ($udom,$users,$caller) = @_;
 2447:     my ($outcome,$results);
 2448:     if (ref($users) eq 'HASH') {
 2449:         my $count = keys(%{$users}); 
 2450:         my $requested = &freeze_escape($users);
 2451:         my $homeserver = &domain($udom,'primary');
 2452:         if ($homeserver ne '') {
 2453:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2454:             my $host=&hostname($homeserver);
 2455:             if ($queryid !~/^\Q$host\E\_/) {
 2456:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2457:                          ' for host: '.$homeserver.'in domain '.$udom);
 2458:                 return ($outcome,$results);
 2459:             }
 2460:             my $response = &get_query_reply($queryid);
 2461:             my $maxtries = 5;
 2462:             if ($count > 100) {
 2463:                 $maxtries = 1+int($count/20);
 2464:             }
 2465:             my $tries = 1;
 2466:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2467:                 $response = &get_query_reply($queryid);
 2468:                 $tries ++;
 2469:             }
 2470:             if ($response eq '') {
 2471:                 $results = {};
 2472:                 foreach my $key (keys(%{$users})) {
 2473:                     my ($uname,$id);
 2474:                     if ($caller eq 'id') {
 2475:                         $id = $key;
 2476:                     } else {
 2477:                         $uname = $key;
 2478:                     }
 2479:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2480:                     $outcome = $resp;
 2481:                     if ($resp eq 'ok') {
 2482:                         %{$results} = (%{$results}, %info);
 2483:                     } else {
 2484:                         last;
 2485:                     }
 2486:                 }
 2487:             } elsif(!&error($response) && ($response ne 'refused')) {
 2488:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2489:                     $outcome = $response;
 2490:                 } else {
 2491:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2492:                     if ($outcome eq 'ok') {
 2493:                         $results = &thaw_unescape($userdata); 
 2494:                     }
 2495:                 }
 2496:             }
 2497:         }
 2498:     }
 2499:     return ($outcome,$results);
 2500: }
 2501: 
 2502: sub inst_rulecheck {
 2503:     my ($udom,$uname,$id,$item,$rules) = @_;
 2504:     my %returnhash;
 2505:     if ($udom ne '') {
 2506:         if (ref($rules) eq 'ARRAY') {
 2507:             @{$rules} = map {&escape($_);} (@{$rules});
 2508:             my $rulestr = join(':',@{$rules});
 2509:             my $homeserver=&domain($udom,'primary');
 2510:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2511:                 my $response;
 2512:                 if ($item eq 'username') {                
 2513:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2514:                                               ':'.&escape($uname).':'.$rulestr,
 2515:                                               $homeserver));
 2516:                 } elsif ($item eq 'id') {
 2517:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2518:                                               ':'.&escape($id).':'.$rulestr,
 2519:                                               $homeserver));
 2520:                 } elsif ($item eq 'selfcreate') {
 2521:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2522:                                                &escape($udom).':'.&escape($uname).
 2523:                                               ':'.$rulestr,$homeserver));
 2524:                 }
 2525:                 if ($response ne 'refused') {
 2526:                     my @pairs=split(/\&/,$response);
 2527:                     foreach my $item (@pairs) {
 2528:                         my ($key,$value)=split(/=/,$item,2);
 2529:                         $key = &unescape($key);
 2530:                         next if ($key =~ /^error: 2 /);
 2531:                         $returnhash{$key}=&thaw_unescape($value);
 2532:                     }
 2533:                 }
 2534:             }
 2535:         }
 2536:     }
 2537:     return %returnhash;
 2538: }
 2539: 
 2540: sub inst_userrules {
 2541:     my ($udom,$check) = @_;
 2542:     my (%ruleshash,@ruleorder);
 2543:     if ($udom ne '') {
 2544:         my $homeserver=&domain($udom,'primary');
 2545:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2546:             my $response;
 2547:             if ($check eq 'id') {
 2548:                 $response=&reply('instidrules:'.&escape($udom),
 2549:                                  $homeserver);
 2550:             } elsif ($check eq 'email') {
 2551:                 $response=&reply('instemailrules:'.&escape($udom),
 2552:                                  $homeserver);
 2553:             } else {
 2554:                 $response=&reply('instuserrules:'.&escape($udom),
 2555:                                  $homeserver);
 2556:             }
 2557:             if (($response ne 'refused') && ($response ne 'error') && 
 2558:                 ($response ne 'unknown_cmd') && 
 2559:                 ($response ne 'no_such_host')) {
 2560:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2561:                 my @pairs=split(/\&/,$hashitems);
 2562:                 foreach my $item (@pairs) {
 2563:                     my ($key,$value)=split(/=/,$item,2);
 2564:                     $key = &unescape($key);
 2565:                     next if ($key =~ /^error: 2 /);
 2566:                     $ruleshash{$key}=&thaw_unescape($value);
 2567:                 }
 2568:                 my @esc_order = split(/\&/,$orderitems);
 2569:                 foreach my $item (@esc_order) {
 2570:                     push(@ruleorder,&unescape($item));
 2571:                 }
 2572:             }
 2573:         }
 2574:     }
 2575:     return (\%ruleshash,\@ruleorder);
 2576: }
 2577: 
 2578: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2579: 
 2580: sub get_domain_defaults {
 2581:     my ($domain,$ignore_cache) = @_;
 2582:     return if (($domain eq '') || ($domain eq 'public'));
 2583:     my $cachetime = 60*60*24;
 2584:     unless ($ignore_cache) {
 2585:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2586:         if (defined($cached)) {
 2587:             if (ref($result) eq 'HASH') {
 2588:                 return %{$result};
 2589:             }
 2590:         }
 2591:     }
 2592:     my %domdefaults;
 2593:     my %domconfig =
 2594:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2595:                                   'requestcourses','inststatus',
 2596:                                   'coursedefaults','usersessions',
 2597:                                   'requestauthor','selfenrollment',
 2598:                                   'coursecategories','ssl','autoenroll',
 2599:                                   'trust','helpsettings','wafproxy'],$domain);
 2600:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2601:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2602:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2603:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2604:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2605:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2606:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2607:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2608:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2609:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2610:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2611:     } else {
 2612:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2613:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2614:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2615:     }
 2616:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2617:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2618:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2619:         } else {
 2620:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2621:         }
 2622:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2623:         foreach my $item (@usertools) {
 2624:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2625:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2626:             }
 2627:         }
 2628:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2629:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2630:         }
 2631:     }
 2632:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2633:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2634:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2635:         }
 2636:     }
 2637:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2638:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2639:     }
 2640:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2641:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2642:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2643:         }
 2644:     }
 2645:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2646:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2647:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2648:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2649:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2650:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2651:         }
 2652:         foreach my $type (@coursetypes) {
 2653:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2654:                 unless ($type eq 'community') {
 2655:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2656:                 }
 2657:             }
 2658:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2659:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2660:             }
 2661:             if ($domdefaults{'postsubmit'} eq 'on') {
 2662:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2663:                     $domdefaults{$type.'postsubtimeout'} = 
 2664:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2665:                 }
 2666:             }
 2667:         }
 2668:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2669:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2670:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2671:                 if (@clonecodes) {
 2672:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2673:                 }
 2674:             }
 2675:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2676:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2677:         }
 2678:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2679:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2680:         } 
 2681:     }
 2682:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2683:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2684:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2685:         }
 2686:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2687:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2688:         }
 2689:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2690:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2691:         }
 2692:     }
 2693:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2694:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2695:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2696:                             'approval','limit');
 2697:             foreach my $type (@coursetypes) {
 2698:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2699:                     my @mgrdc = ();
 2700:                     foreach my $item (@settings) {
 2701:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2702:                             push(@mgrdc,$item);
 2703:                         }
 2704:                     }
 2705:                     if (@mgrdc) {
 2706:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2707:                     }
 2708:                 }
 2709:             }
 2710:         }
 2711:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2712:             foreach my $type (@coursetypes) {
 2713:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2714:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2715:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2716:                     }
 2717:                 }
 2718:             }
 2719:         }
 2720:     }
 2721:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2722:         $domdefaults{'catauth'} = 'std';
 2723:         $domdefaults{'catunauth'} = 'std';
 2724:         if ($domconfig{'coursecategories'}{'auth'}) {
 2725:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2726:         }
 2727:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2728:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2729:         }
 2730:     }
 2731:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2732:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2733:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2734:         }
 2735:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2736:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2737:         }
 2738:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2739:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2740:         }
 2741:     }
 2742:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2743:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2744:         foreach my $prefix (@prefixes) {
 2745:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2746:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2747:             }
 2748:         }
 2749:     }
 2750:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2751:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2752:     }
 2753:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2754:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2755:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2756:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2757:         }
 2758:     }
 2759:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2760:         foreach my $item ('ipheader','trusted','exempt') {
 2761:             if ($domconfig{'wafproxy'}{$item}) {
 2762:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2763:             }
 2764:         }
 2765:     } 
 2766:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2767:     return %domdefaults;
 2768: }
 2769: 
 2770: sub get_dom_cats {
 2771:     my ($dom) = @_;
 2772:     return unless (&domain($dom));
 2773:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2774:     unless (defined($cached)) {
 2775:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2776:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2777:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2778:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2779:             } else {
 2780:                 $cats = {};
 2781:             }
 2782:         } else {
 2783:             $cats = {};
 2784:         }
 2785:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2786:     }
 2787:     return $cats;
 2788: }
 2789: 
 2790: sub get_dom_instcats {
 2791:     my ($dom) = @_;
 2792:     return unless (&domain($dom));
 2793:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2794:     unless (defined($cached)) {
 2795:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2796:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2797:         if ($totcodes > 0) {
 2798:             my $caller = 'global';
 2799:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2800:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2801:                 $instcats = {
 2802:                                 codes => \%codes,
 2803:                                 codetitles => \@codetitles,
 2804:                                 cat_titles => \%cat_titles,
 2805:                                 cat_order => \%cat_order,
 2806:                             };
 2807:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2808:             }
 2809:         }
 2810:     }
 2811:     return $instcats;
 2812: }
 2813: 
 2814: sub retrieve_instcodes {
 2815:     my ($coursecodes,$dom) = @_;
 2816:     my $totcodes;
 2817:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2818:     foreach my $course (keys(%courses)) {
 2819:         if (ref($courses{$course}) eq 'HASH') {
 2820:             if ($courses{$course}{'inst_code'} ne '') {
 2821:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2822:                 $totcodes ++;
 2823:             }
 2824:         }
 2825:     }
 2826:     return $totcodes;
 2827: }
 2828: 
 2829: sub course_portal_url {
 2830:     my ($cnum,$cdom) = @_;
 2831:     my $chome = &homeserver($cnum,$cdom);
 2832:     my $hostname = &hostname($chome);
 2833:     my $protocol = $protocol{$chome};
 2834:     $protocol = 'http' if ($protocol ne 'https');
 2835:     my %domdefaults = &get_domain_defaults($cdom);
 2836:     my $firsturl;
 2837:     if ($domdefaults{'portal_def'}) {
 2838:         $firsturl = $domdefaults{'portal_def'};
 2839:     } else {
 2840:         $firsturl = $protocol.'://'.$hostname;
 2841:     }
 2842:     return $firsturl;
 2843: }
 2844: 
 2845: # --------------------------------------------- Get domain config for passwords
 2846: 
 2847: sub get_passwdconf {
 2848:     my ($dom) = @_;
 2849:     my (%passwdconf,$gotconf,$lookup);
 2850:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2851:     if (defined($cached)) {
 2852:         if (ref($result) eq 'HASH') {
 2853:             %passwdconf = %{$result};
 2854:             $gotconf = 1;
 2855:         }
 2856:     }
 2857:     unless ($gotconf) {
 2858:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2859:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2860:             %passwdconf = %{$domconfig{'passwords'}};
 2861:         }
 2862:         my $cachetime = 24*60*60;
 2863:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2864:     }
 2865:     return %passwdconf;
 2866: }
 2867: 
 2868: # --------------------------------------------------- Assign a key to a student
 2869: 
 2870: sub assign_access_key {
 2871: #
 2872: # a valid key looks like uname:udom#comments
 2873: # comments are being appended
 2874: #
 2875:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2876:     $kdom=
 2877:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2878:     $knum=
 2879:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2880:     $cdom=
 2881:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2882:     $cnum=
 2883:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2884:     $udom=$env{'user.name'} unless (defined($udom));
 2885:     $uname=$env{'user.domain'} unless (defined($uname));
 2886:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2887:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2888:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2889:                                                   # assigned to this person
 2890:                                                   # - this should not happen,
 2891:                                                   # unless something went wrong
 2892:                                                   # the first time around
 2893: # ready to assign
 2894:         $logentry=$1.'; '.$logentry;
 2895:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2896:                                                  $kdom,$knum) eq 'ok') {
 2897: # key now belongs to user
 2898: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2899:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2900:                 &appenv({'environment.'.$envkey => $ckey});
 2901:                 return 'ok';
 2902:             } else {
 2903:                 return 
 2904:   'error: Count not permanently assign key, will need to be re-entered later.';
 2905: 	    }
 2906:         } else {
 2907:             return 'error: Could not assign key, try again later.';
 2908:         }
 2909:     } elsif (!$existing{$ckey}) {
 2910: # the key does not exist
 2911: 	return 'error: The key does not exist';
 2912:     } else {
 2913: # the key is somebody else's
 2914: 	return 'error: The key is already in use';
 2915:     }
 2916: }
 2917: 
 2918: # ------------------------------------------ put an additional comment on a key
 2919: 
 2920: sub comment_access_key {
 2921: #
 2922: # a valid key looks like uname:udom#comments
 2923: # comments are being appended
 2924: #
 2925:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2926:     $cdom=
 2927:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2928:     $cnum=
 2929:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2930:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2931:     if ($existing{$ckey}) {
 2932:         $existing{$ckey}.='; '.$logentry;
 2933: # ready to assign
 2934:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2935:                                                  $cdom,$cnum) eq 'ok') {
 2936: 	    return 'ok';
 2937:         } else {
 2938: 	    return 'error: Count not store comment.';
 2939:         }
 2940:     } else {
 2941: # the key does not exist
 2942: 	return 'error: The key does not exist';
 2943:     }
 2944: }
 2945: 
 2946: # ------------------------------------------------------ Generate a set of keys
 2947: 
 2948: sub generate_access_keys {
 2949:     my ($number,$cdom,$cnum,$logentry)=@_;
 2950:     $cdom=
 2951:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2952:     $cnum=
 2953:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2954:     unless (&allowed('mky',$cdom)) { return 0; }
 2955:     unless (($cdom) && ($cnum)) { return 0; }
 2956:     if ($number>10000) { return 0; }
 2957:     sleep(2); # make sure don't get same seed twice
 2958:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2959:     my $total=0;
 2960:     for (my $i=1;$i<=$number;$i++) {
 2961:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2962:                   sprintf("%lx",int(100000*rand)).'-'.
 2963:                   sprintf("%lx",int(100000*rand));
 2964:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2965:        $newkey=~s/0/h/g; # and also 0 and O
 2966:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2967:        if ($existing{$newkey}) {
 2968:            $i--;
 2969:        } else {
 2970: 	  if (&put('accesskeys',
 2971:               { $newkey => '# generated '.localtime().
 2972:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2973:                            '; '.$logentry },
 2974: 		   $cdom,$cnum) eq 'ok') {
 2975:               $total++;
 2976: 	  }
 2977:        }
 2978:     }
 2979:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2980:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2981:     return $total;
 2982: }
 2983: 
 2984: # ------------------------------------------------------- Validate an accesskey
 2985: 
 2986: sub validate_access_key {
 2987:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2988:     $cdom=
 2989:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2990:     $cnum=
 2991:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2992:     $udom=$env{'user.domain'} unless (defined($udom));
 2993:     $uname=$env{'user.name'} unless (defined($uname));
 2994:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2995:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2996: }
 2997: 
 2998: # ------------------------------------- Find the section of student in a course
 2999: sub devalidate_getsection_cache {
 3000:     my ($udom,$unam,$courseid)=@_;
 3001:     my $hashid="$udom:$unam:$courseid";
 3002:     &devalidate_cache_new('getsection',$hashid);
 3003: }
 3004: 
 3005: sub courseid_to_courseurl {
 3006:     my ($courseid) = @_;
 3007:     #already url style courseid
 3008:     return $courseid if ($courseid =~ m{^/});
 3009: 
 3010:     if (exists($env{'course.'.$courseid.'.num'})) {
 3011: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3012: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3013: 	return "/$cdom/$cnum";
 3014:     }
 3015: 
 3016:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 3017:     if (exists($courseinfo{'num'})) {
 3018: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3019:     }
 3020: 
 3021:     return undef;
 3022: }
 3023: 
 3024: sub getsection {
 3025:     my ($udom,$unam,$courseid)=@_;
 3026:     my $cachetime=1800;
 3027: 
 3028:     my $hashid="$udom:$unam:$courseid";
 3029:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3030:     if (defined($cached)) { return $result; }
 3031: 
 3032:     my %Pending; 
 3033:     my %Expired;
 3034:     #
 3035:     # Each role can either have not started yet (pending), be active, 
 3036:     #    or have expired.
 3037:     #
 3038:     # If there is an active role, we are done.
 3039:     #
 3040:     # If there is more than one role which has not started yet, 
 3041:     #     choose the one which will start sooner
 3042:     # If there is one role which has not started yet, return it.
 3043:     #
 3044:     # If there is more than one expired role, choose the one which ended last.
 3045:     # If there is a role which has expired, return it.
 3046:     #
 3047:     $courseid = &courseid_to_courseurl($courseid);
 3048:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3049:     foreach my $key (keys(%roleshash)) {
 3050:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3051:         my $section=$1;
 3052:         if ($key eq $courseid.'_st') { $section=''; }
 3053:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3054:         my $now=time;
 3055:         if (defined($end) && $end && ($now > $end)) {
 3056:             $Expired{$end}=$section;
 3057:             next;
 3058:         }
 3059:         if (defined($start) && $start && ($now < $start)) {
 3060:             $Pending{$start}=$section;
 3061:             next;
 3062:         }
 3063:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3064:     }
 3065:     #
 3066:     # Presumedly there will be few matching roles from the above
 3067:     # loop and the sorting time will be negligible.
 3068:     if (scalar(keys(%Pending))) {
 3069:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3070:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3071:     } 
 3072:     if (scalar(keys(%Expired))) {
 3073:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3074:         my $time = pop(@sorted);
 3075:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3076:     }
 3077:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3078: }
 3079: 
 3080: sub save_cache {
 3081:     &purge_remembered();
 3082:     #&Apache::loncommon::validate_page();
 3083:     undef(%env);
 3084:     undef($env_loaded);
 3085: }
 3086: 
 3087: my $to_remember=-1;
 3088: my %remembered;
 3089: my %accessed;
 3090: my $kicks=0;
 3091: my $hits=0;
 3092: sub make_key {
 3093:     my ($name,$id) = @_;
 3094:     if (length($id) > 65 
 3095: 	&& length(&escape($id)) > 200) {
 3096: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3097:     }
 3098:     return &escape($name.':'.$id);
 3099: }
 3100: 
 3101: sub devalidate_cache_new {
 3102:     my ($name,$id,$debug) = @_;
 3103:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3104:     my $remembered_id=$name.':'.$id;
 3105:     $id=&make_key($name,$id);
 3106:     $memcache->delete($id);
 3107:     delete($remembered{$remembered_id});
 3108:     delete($accessed{$remembered_id});
 3109: }
 3110: 
 3111: sub is_cached_new {
 3112:     my ($name,$id,$debug) = @_;
 3113:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3114:     if (exists($remembered{$remembered_id})) {
 3115: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3116: 	$accessed{$remembered_id}=[&gettimeofday()];
 3117: 	$hits++;
 3118: 	return ($remembered{$remembered_id},1);
 3119:     }
 3120:     $id=&make_key($name,$id);
 3121:     my $value = $memcache->get($id);
 3122:     if (!(defined($value))) {
 3123: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3124: 	return (undef,undef);
 3125:     }
 3126:     if ($value eq '__undef__') {
 3127: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3128: 	$value=undef;
 3129:     }
 3130:     &make_room($remembered_id,$value,$debug);
 3131:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3132:     return ($value,1);
 3133: }
 3134: 
 3135: sub do_cache_new {
 3136:     my ($name,$id,$value,$time,$debug) = @_;
 3137:     my $remembered_id=$name.':'.$id;
 3138:     $id=&make_key($name,$id);
 3139:     my $setvalue=$value;
 3140:     if (!defined($setvalue)) {
 3141: 	$setvalue='__undef__';
 3142:     }
 3143:     if (!defined($time) ) {
 3144: 	$time=600;
 3145:     }
 3146:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3147:     my $result = $memcache->set($id,$setvalue,$time);
 3148:     if (! $result) {
 3149: 	&logthis("caching of id -> $id  failed");
 3150: 	$memcache->disconnect_all();
 3151:     }
 3152:     # need to make a copy of $value
 3153:     &make_room($remembered_id,$value,$debug);
 3154:     return $value;
 3155: }
 3156: 
 3157: sub make_room {
 3158:     my ($remembered_id,$value,$debug)=@_;
 3159: 
 3160:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3161:                                     : $value;
 3162:     if ($to_remember<0) { return; }
 3163:     $accessed{$remembered_id}=[&gettimeofday()];
 3164:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3165:     my $to_kick;
 3166:     my $max_time=0;
 3167:     foreach my $other (keys(%accessed)) {
 3168: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3169: 	    $to_kick=$other;
 3170: 	    $max_time=&tv_interval($accessed{$other});
 3171: 	}
 3172:     }
 3173:     delete($remembered{$to_kick});
 3174:     delete($accessed{$to_kick});
 3175:     $kicks++;
 3176:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3177:     return;
 3178: }
 3179: 
 3180: sub purge_remembered {
 3181:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3182:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3183:     undef(%remembered);
 3184:     undef(%accessed);
 3185: }
 3186: # ------------------------------------- Read an entry from a user's environment
 3187: 
 3188: sub userenvironment {
 3189:     my ($udom,$unam,@what)=@_;
 3190:     my $items;
 3191:     foreach my $item (@what) {
 3192:         $items.=&escape($item).'&';
 3193:     }
 3194:     $items=~s/\&$//;
 3195:     my %returnhash=();
 3196:     my $uhome = &homeserver($unam,$udom);
 3197:     unless ($uhome eq 'no_host') {
 3198:         my @answer=split(/\&/, 
 3199:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3200:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3201:             return %returnhash;
 3202:         }
 3203:         my $i;
 3204:         for ($i=0;$i<=$#what;$i++) {
 3205: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3206:         }
 3207:     }
 3208:     return %returnhash;
 3209: }
 3210: 
 3211: # ---------------------------------------------------------- Get a studentphoto
 3212: sub studentphoto {
 3213:     my ($udom,$unam,$ext) = @_;
 3214:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3215:     if (defined($env{'request.course.id'})) {
 3216:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3217:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3218:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3219:             } else {
 3220:                 my ($result,$perm_reqd)=
 3221: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3222:                 if ($result eq 'ok') {
 3223:                     if (!($perm_reqd eq 'yes')) {
 3224:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3225:                     }
 3226:                 }
 3227:             }
 3228:         }
 3229:     } else {
 3230:         my ($result,$perm_reqd) = 
 3231: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3232:         if ($result eq 'ok') {
 3233:             if (!($perm_reqd eq 'yes')) {
 3234:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3235:             }
 3236:         }
 3237:     }
 3238:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3239: }
 3240: 
 3241: sub retrievestudentphoto {
 3242:     my ($udom,$unam,$ext,$type) = @_;
 3243:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3244:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3245:     if ($ret eq 'ok') {
 3246:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3247:         if ($type eq 'thumbnail') {
 3248:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3249:         }
 3250:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3251:         return $tokenurl;
 3252:     } else {
 3253:         if ($type eq 'thumbnail') {
 3254:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3255:         } else { 
 3256:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3257:         }
 3258:     }
 3259: }
 3260: 
 3261: # -------------------------------------------------------------------- New chat
 3262: 
 3263: sub chatsend {
 3264:     my ($newentry,$anon,$group)=@_;
 3265:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3266:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3267:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3268:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3269: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3270: 		   &escape($newentry)).':'.$group,$chome);
 3271: }
 3272: 
 3273: # ------------------------------------------ Find current version of a resource
 3274: 
 3275: sub getversion {
 3276:     my $fname=&clutter(shift);
 3277:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3278:     return &currentversion(&filelocation('',$fname));
 3279: }
 3280: 
 3281: sub currentversion {
 3282:     my $fname=shift;
 3283:     my $author=$fname;
 3284:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3285:     my ($udom,$uname)=split(/\//,$author);
 3286:     my $home=&homeserver($uname,$udom);
 3287:     if ($home eq 'no_host') { 
 3288:         return -1; 
 3289:     }
 3290:     my $answer=&reply("currentversion:$fname",$home);
 3291:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3292: 	return -1;
 3293:     }
 3294:     return $answer;
 3295: }
 3296: 
 3297: #
 3298: # Return special version number of resource if set by override, empty otherwise
 3299: #
 3300: sub usedversion {
 3301:     my $fname=shift;
 3302:     unless ($fname) { $fname=$env{'request.uri'}; }
 3303:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3304:     if ($urlversion) { return $urlversion; }
 3305:     return '';
 3306: }
 3307: 
 3308: # ----------------------------- Subscribe to a resource, return URL if possible
 3309: 
 3310: sub subscribe {
 3311:     my $fname=shift;
 3312:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3313:     $fname=~s/[\n\r]//g;
 3314:     my $author=$fname;
 3315:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3316:     my ($udom,$uname)=split(/\//,$author);
 3317:     my $home=homeserver($uname,$udom);
 3318:     if ($home eq 'no_host') {
 3319:         return 'not_found';
 3320:     }
 3321:     my $answer=reply("sub:$fname",$home);
 3322:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3323: 	$answer.=' by '.$home;
 3324:     }
 3325:     return $answer;
 3326: }
 3327:     
 3328: # -------------------------------------------------------------- Replicate file
 3329: 
 3330: sub repcopy {
 3331:     my $filename=shift;
 3332:     $filename=~s/\/+/\//g;
 3333:     my $londocroot = $perlvar{'lonDocRoot'};
 3334:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3335:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3336:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3337: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3338: 	return &repcopy_userfile($filename);
 3339:     }
 3340:     $filename=~s/[\n\r]//g;
 3341:     my $transname="$filename.in.transfer";
 3342: # FIXME: this should flock
 3343:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3344:     my $remoteurl=subscribe($filename);
 3345:     if ($remoteurl =~ /^con_lost by/) {
 3346: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3347:            return 'unavailable';
 3348:     } elsif ($remoteurl eq 'not_found') {
 3349: 	   #&logthis("Subscribe returned not_found: $filename");
 3350: 	   return 'not_found';
 3351:     } elsif ($remoteurl =~ /^rejected by/) {
 3352: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3353:            return 'forbidden';
 3354:     } elsif ($remoteurl eq 'directory') {
 3355:            return 'ok';
 3356:     } else {
 3357:         my $author=$filename;
 3358:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3359:         my ($udom,$uname)=split(/\//,$author);
 3360:         my $home=homeserver($uname,$udom);
 3361:         unless ($home eq $perlvar{'lonHostID'}) {
 3362:            my @parts=split(/\//,$filename);
 3363:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3364:            if ($path ne "$londocroot/res") {
 3365:                &logthis("Malconfiguration for replication: $filename");
 3366: 	       return 'bad_request';
 3367:            }
 3368:            my $count;
 3369:            for ($count=5;$count<$#parts;$count++) {
 3370:                $path.="/$parts[$count]";
 3371:                if ((-e $path)!=1) {
 3372: 		   mkdir($path,0777);
 3373:                }
 3374:            }
 3375:            my $request=new HTTP::Request('GET',"$remoteurl");
 3376:            my $response;
 3377:            if ($remoteurl =~ m{/raw/}) {
 3378:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3379:            } else {
 3380:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3381:            }
 3382:            if ($response->is_error()) {
 3383: 	       unlink($transname);
 3384:                my $message=$response->status_line;
 3385:                &logthis("<font color=\"blue\">WARNING:"
 3386:                        ." LWP get: $message: $filename</font>");
 3387:                return 'unavailable';
 3388:            } else {
 3389: 	       if ($remoteurl!~/\.meta$/) {
 3390:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3391:                   my $mresponse;
 3392:                   if ($remoteurl =~ m{/raw/}) {
 3393:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3394:                   } else {
 3395:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3396:                   }
 3397:                   if ($mresponse->is_error()) {
 3398: 		      unlink($filename.'.meta');
 3399:                       &logthis(
 3400:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3401:                   }
 3402: 	       }
 3403:                rename($transname,$filename);
 3404:                return 'ok';
 3405:            }
 3406:        }
 3407:     }
 3408: }
 3409: 
 3410: # ------------------------------------------------- Unsubscribe from a resource
 3411: 
 3412: sub unsubscribe {
 3413:     my ($fname) = @_;
 3414:     my $answer;
 3415:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3416:     $fname=~s/[\n\r]//g;
 3417:     my $author=$fname;
 3418:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3419:     my ($udom,$uname)=split(/\//,$author);
 3420:     my $home=homeserver($uname,$udom);
 3421:     if ($home eq 'no_host') {
 3422:         $answer = 'no_host';
 3423:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3424:         $answer = 'home';
 3425:     } else {
 3426:         my $defdom = $perlvar{'lonDefDomain'};
 3427:         if (&will_trust('content',$defdom,$udom)) {
 3428:             $answer = reply("unsub:$fname",$home);
 3429:         } else {
 3430:             $answer = 'untrusted';
 3431:         }
 3432:     }
 3433:     return $answer;
 3434: }
 3435: 
 3436: # ------------------------------------------------ Get server side include body
 3437: sub ssi_body {
 3438:     my ($filelink,%form)=@_;
 3439:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3440:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3441:     }
 3442:     my $output='';
 3443:     my $response;
 3444:     if ($filelink=~/^https?\:/) {
 3445:        ($output,$response)=&externalssi($filelink);
 3446:     } else {
 3447:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3448:        $filelink .= 'inhibitmenu=yes';
 3449:        ($output,$response)=&ssi($filelink,%form);
 3450:     }
 3451:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3452:     $output=~s/^.*?\<body[^\>]*\>//si;
 3453:     $output=~s/\<\/body\s*\>.*?$//si;
 3454:     if (wantarray) {
 3455:         return ($output, $response);
 3456:     } else {
 3457:         return $output;
 3458:     }
 3459: }
 3460: 
 3461: # --------------------------------------------------------- Server Side Include
 3462: 
 3463: sub absolute_url {
 3464:     my ($host_name) = @_;
 3465:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3466:     if ($host_name eq '') {
 3467: 	$host_name = $ENV{'SERVER_NAME'};
 3468:     }
 3469:     return $protocol.$host_name;
 3470: }
 3471: 
 3472: #
 3473: #   Server side include.
 3474: # Parameters:
 3475: #  fn     Possibly encrypted resource name/id.
 3476: #  form   Hash that describes how the rendering should be done
 3477: #         and other things.
 3478: # Returns:
 3479: #   Scalar context: The content of the response.
 3480: #   Array context:  2 element list of the content and the full response object.
 3481: #     
 3482: sub ssi {
 3483: 
 3484:     my ($fn,%form)=@_;
 3485:     my $request;
 3486: 
 3487:     $form{'no_update_last_known'}=1;
 3488:     &Apache::lonenc::check_encrypt(\$fn);
 3489:     if (%form) {
 3490:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3491:       $request->content(join('&',map { 
 3492:             my $name = escape($_);
 3493:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3494:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3495:             : &escape($form{$_}) );    
 3496:         } keys(%form)));
 3497:     } else {
 3498:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3499:     }
 3500: 
 3501:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3502:     my $lonhost = $perlvar{'lonHostID'};
 3503:     my $islocal;
 3504:     if (($env{'request.course.id'}) &&
 3505:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3506:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3507:         ($form{'grade_symb'} ne '') &&
 3508:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3509:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3510:         $islocal = 1;
 3511:     }
 3512:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3513:                                                 '','','',$islocal);
 3514: 
 3515:     if (wantarray) {
 3516: 	return ($response->content, $response);
 3517:     } else {
 3518: 	return $response->content;
 3519:     }
 3520: }
 3521: 
 3522: sub externalssi {
 3523:     my ($url)=@_;
 3524:     my $request=new HTTP::Request('GET',$url);
 3525:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3526:     if (wantarray) {
 3527:         return ($response->content, $response);
 3528:     } else {
 3529:         return $response->content;
 3530:     }
 3531: }
 3532: 
 3533: 
 3534: # If the local copy of a replicated resource is outdated, trigger a  
 3535: # connection from the homeserver to flush the delayed queue. If no update 
 3536: # happens, remove local copies of outdated resource (and corresponding
 3537: # metadata file).
 3538: 
 3539: sub remove_stale_resfile {
 3540:     my ($url) = @_;
 3541:     my $removed;
 3542:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3543:         my $audom = $1;
 3544:         my $auname = $2;
 3545:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3546:             my $homeserver = &homeserver($auname,$audom);
 3547:             unless (($homeserver eq 'no_host') ||
 3548:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3549:                 my $fname = &filelocation('',$url);
 3550:                 if (-e $fname) {
 3551:                     my $hostname = &hostname($homeserver);
 3552:                     if ($hostname) {
 3553:                         my $protocol = $protocol{$homeserver};
 3554:                         $protocol = 'http' if ($protocol ne 'https');
 3555:                         my $uri = &declutter($url);
 3556:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3557:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3558:                         if ($response->is_success()) {
 3559:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3560:                             my $locmodtime = (stat($fname))[9];
 3561:                             if ($locmodtime < $remmodtime) {
 3562:                                 my $stale;
 3563:                                 my $answer = &reply('pong',$homeserver);
 3564:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3565:                                     sleep(0.2);
 3566:                                     $locmodtime = (stat($fname))[9];
 3567:                                     if ($locmodtime < $remmodtime) {
 3568:                                         my $posstransfer = $fname.'.in.transfer';
 3569:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3570:                                             $removed = 1;
 3571:                                         } else {
 3572:                                             $stale = 1;
 3573:                                         }
 3574:                                     } else {
 3575:                                         $removed = 1;
 3576:                                     }
 3577:                                 } else {
 3578:                                     $stale = 1;
 3579:                                 }
 3580:                                 if ($stale) {
 3581:                                     if (unlink($fname)) {
 3582:                                         if ($uri!~/\.meta$/) {
 3583:                                             if (-e $fname.'.meta') {
 3584:                                                 unlink($fname.'.meta');
 3585:                                             }
 3586:                                         }
 3587:                                         my $unsubresult = &unsubscribe($fname);
 3588:                                         unless ($unsubresult eq 'ok') {
 3589:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3590:                                         }
 3591:                                         $removed = 1;
 3592:                                     }
 3593:                                 }
 3594:                             }
 3595:                         }
 3596:                     }
 3597:                 }
 3598:             }
 3599:         }
 3600:     }
 3601:     return $removed;
 3602: }
 3603: 
 3604: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3605: 
 3606: sub allowuploaded {
 3607:     my ($srcurl,$url)=@_;
 3608:     $url=&clutter(&declutter($url));
 3609:     my $dir=$url;
 3610:     $dir=~s/\/[^\/]+$//;
 3611:     my %httpref=();
 3612:     my $httpurl=&hreflocation('',$url);
 3613:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3614:     &Apache::lonnet::appenv(\%httpref);
 3615: }
 3616: 
 3617: #
 3618: # Determine if the current user should be able to edit a particular resource,
 3619: # when viewing in course context.
 3620: # (a) When viewing resource used to determine if "Edit" item is included in 
 3621: #     Functions.
 3622: # (b) When displaying folder contents in course editor, used to determine if
 3623: #     "Edit" link will be displayed alongside resource.
 3624: #
 3625: #  input: six args -- filename (decluttered), course number, course domain,
 3626: #                   url, symb (if registered) and group (if this is a group
 3627: #                   item -- e.g., bulletin board, group page etc.).
 3628: #  output: array of five scalars -- 
 3629: #          $cfile -- url for file editing if editable on current server
 3630: #          $home -- homeserver of resource (i.e., for author if published,
 3631: #                                           or course if uploaded.).
 3632: #          $switchserver --  1 if server switch will be needed.
 3633: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3634: #          $forceview -- 1 if icon/link should be to go to view mode
 3635: #
 3636: 
 3637: sub can_edit_resource {
 3638:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3639:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3640: #
 3641: # For aboutme pages user can only edit his/her own.
 3642: #
 3643:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3644:         my ($sdom,$sname) = ($1,$2);
 3645:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3646:             $home = $env{'user.home'};
 3647:             $cfile = $resurl;
 3648:             if ($env{'form.forceedit'}) {
 3649:                 $forceview = 1;
 3650:             } else {
 3651:                 $forceedit = 1;
 3652:             }
 3653:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3654:         } else {
 3655:             return;
 3656:         }
 3657:     }
 3658: 
 3659:     if ($env{'request.course.id'}) {
 3660:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3661:         if ($group ne '') {
 3662: # if this is a group homepage or group bulletin board, check group privs
 3663:             my $allowed = 0;
 3664:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3665:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3666:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3667:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3668:                     $allowed = 1;
 3669:                 }
 3670:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3671:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3672:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3673:                     $allowed = 1;
 3674:                 }
 3675:             }
 3676:             if ($allowed) {
 3677:                 $home=&homeserver($cnum,$cdom);
 3678:                 if ($env{'form.forceedit'}) {
 3679:                     $forceview = 1;
 3680:                 } else {
 3681:                     $forceedit = 1;
 3682:                 }
 3683:                 $cfile = $resurl;
 3684:             } else {
 3685:                 return;
 3686:             }
 3687:         } else {
 3688:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3689:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3690:                     return;
 3691:                 }
 3692:             } elsif (!$crsedit) {
 3693: #
 3694: # No edit allowed where CC has switched to student role.
 3695: #
 3696:                 return;
 3697:             }
 3698:         }
 3699:     }
 3700: 
 3701:     if ($file ne '') {
 3702:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3703:             if (&is_course_upload($file,$cnum,$cdom)) {
 3704:                 $uploaded = 1;
 3705:                 $incourse = 1;
 3706:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3707:                     $cfile = &hreflocation('',$file);
 3708:                     if ($env{'form.forceedit'}) {
 3709:                         $forceview = 1;
 3710:                     } else {
 3711:                         $forceedit = 1;
 3712:                     }
 3713:                 }
 3714:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3715:                 $incourse = 1;
 3716:                 if ($env{'form.forceedit'}) {
 3717:                     $forceview = 1;
 3718:                 } else {
 3719:                     $forceedit = 1;
 3720:                 }
 3721:                 $cfile = $resurl;
 3722:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3723:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3724:                     $incourse = 1;
 3725:                     if ($env{'form.forceedit'}) {
 3726:                         $forceview = 1;
 3727:                     } else {
 3728:                         $forceedit = 1;
 3729:                     }
 3730:                     $cfile = $resurl;
 3731:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3732:                     $incourse = 1;
 3733:                     $cfile = $resurl.'/smpedit';
 3734:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3735:                     $incourse = 1;
 3736:                     if ($env{'form.forceedit'}) {
 3737:                         $forceview = 1;
 3738:                     } else {
 3739:                         $forceedit = 1;
 3740:                     }
 3741:                     $cfile = $resurl;
 3742:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3743:                     my ($map,$id,$res) = &decode_symb($symb);
 3744:                     if ($map =~ /\.page$/) {
 3745:                         $incourse = 1;
 3746:                         if ($env{'form.forceedit'}) {
 3747:                             $forceview = 1;
 3748:                             $cfile = $map;
 3749:                         } else {
 3750:                             $forceedit = 1;
 3751:                             $cfile =  '/adm/wrapper'.$resurl;
 3752:                         }
 3753:                     }
 3754:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3755:                     $incourse = 1;
 3756:                     if ($env{'form.forceedit'}) {
 3757:                         $forceview = 1;
 3758:                     } else {
 3759:                         $forceedit = 1;
 3760:                     }
 3761:                     $cfile = $resurl;
 3762:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3763:                     $incourse = 1;
 3764:                     if ($env{'form.forceedit'}) {
 3765:                         $forceview = 1;
 3766:                     } else {
 3767:                         $forceedit = 1;
 3768:                     }
 3769:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3770:                 }
 3771:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3772:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3773:                 if (&is_on_map($template)) { 
 3774:                     $incourse = 1;
 3775:                     $forceview = 1;
 3776:                     $cfile = $template;
 3777:                 }
 3778:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3779:                 $incourse = 1;
 3780:                 if ($env{'form.forceedit'}) {
 3781:                     $forceview = 1;
 3782:                 } else {
 3783:                     $forceedit = 1;
 3784:                 }
 3785:                 $cfile = $resurl;
 3786:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3787:                 $incourse = 1;
 3788:                 if ($env{'form.forceedit'}) {
 3789:                     $forceview = 1;
 3790:                 } else {
 3791:                     $forceedit = 1;
 3792:                 }
 3793:                 $cfile = $resurl;
 3794:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3795:                 $incourse = 1;
 3796:                 $forceview = 1;
 3797:                 if ($symb) {
 3798:                     my ($map,$id,$res)=&decode_symb($symb);
 3799:                     $env{'request.symb'} = $symb;
 3800:                     $cfile = &clutter($res);
 3801:                 } else {
 3802:                     $cfile = $env{'form.suppurl'};
 3803:                     my $escfile = &unescape($cfile);
 3804:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3805:                         $cfile = '/adm/wrapper'.$escfile;
 3806:                     } else {
 3807:                         $escfile =~ s{^http://}{};
 3808:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3809:                     }
 3810:                 }
 3811:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3812:                 if ($env{'form.forceedit'}) {
 3813:                     $forceview = 1;
 3814:                 } else {
 3815:                     $forceedit = 1;
 3816:                 }
 3817:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3818:             }
 3819:         }
 3820:         if ($uploaded || $incourse) {
 3821:             $home=&homeserver($cnum,$cdom);
 3822:         } elsif ($file !~ m{/$}) {
 3823:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3824:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3825:             # Check that the user has permission to edit this resource
 3826:             my $setpriv = 1;
 3827:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3828:             if (defined($cfudom)) {
 3829:                 $home=&homeserver($cfuname,$cfudom);
 3830:                 $cfile=$file;
 3831:             }
 3832:         }
 3833:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3834:             (($home ne '') && ($home ne 'no_host'))) {
 3835:             my @ids=&current_machine_ids();
 3836:             unless (grep(/^\Q$home\E$/,@ids)) {
 3837:                 $switchserver=1;
 3838:             }
 3839:         }
 3840:     }
 3841:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3842: }
 3843: 
 3844: sub is_course_upload {
 3845:     my ($file,$cnum,$cdom) = @_;
 3846:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3847:     $uploadpath =~ s{^\/}{};
 3848:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3849:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3850:         return 1;
 3851:     }
 3852:     return;
 3853: }
 3854: 
 3855: sub in_course {
 3856:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3857:     if ($hideprivileged) {
 3858:         my $skipuser;
 3859:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3860:         my @possdoms = ($cdom);  
 3861:         if ($coursehash{'checkforpriv'}) { 
 3862:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3863:         }
 3864:         if (&privileged($uname,$udom,\@possdoms)) {
 3865:             $skipuser = 1;
 3866:             if ($coursehash{'nothideprivileged'}) {
 3867:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3868:                     my $user;
 3869:                     if ($item =~ /:/) {
 3870:                         $user = $item;
 3871:                     } else {
 3872:                         $user = join(':',split(/[\@]/,$item));
 3873:                     }
 3874:                     if ($user eq $uname.':'.$udom) {
 3875:                         undef($skipuser);
 3876:                         last;
 3877:                     }
 3878:                 }
 3879:             }
 3880:             if ($skipuser) {
 3881:                 return 0;
 3882:             }
 3883:         }
 3884:     }
 3885:     $type ||= 'any';
 3886:     if (!defined($cdom) || !defined($cnum)) {
 3887:         my $cid  = $env{'request.course.id'};
 3888:         $cdom = $env{'course.'.$cid.'.domain'};
 3889:         $cnum = $env{'course.'.$cid.'.num'};
 3890:     }
 3891:     my $typesref;
 3892:     if (($type eq 'any') || ($type eq 'all')) {
 3893:         $typesref = ['active','previous','future'];
 3894:     } elsif ($type eq 'previous' || $type eq 'future') {
 3895:         $typesref = [$type];
 3896:     }
 3897:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3898:                               $typesref,undef,[$cdom]);
 3899:     my ($tmp) = keys(%roles);
 3900:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3901:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3902:     if (@course_roles > 0) {
 3903:         return 1;
 3904:     }
 3905:     return 0;
 3906: }
 3907: 
 3908: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3909: # input: action, courseID, current domain, intended
 3910: #        path to file, source of file, instruction to parse file for objects,
 3911: #        ref to hash for embedded objects,
 3912: #        ref to hash for codebase of java objects.
 3913: #        reference to scalar to accommodate mime type determined
 3914: #          from File::MMagic if $parser = parse.
 3915: #
 3916: # output: url to file (if action was uploaddoc), 
 3917: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3918: #
 3919: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3920: # course.
 3921: #
 3922: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3923: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3924: #          course's home server.
 3925: #
 3926: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3927: #          be copied from $source (current location) to 
 3928: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3929: #         and will then be copied to
 3930: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3931: #         course's home server.
 3932: #
 3933: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3934: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3935: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3936: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3937: #         in course's home server.
 3938: #
 3939: 
 3940: sub process_coursefile {
 3941:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3942:         $mimetype)=@_;
 3943:     my $fetchresult;
 3944:     my $home=&homeserver($docuname,$docudom);
 3945:     if ($action eq 'propagate') {
 3946:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3947: 			     $home);
 3948:     } else {
 3949:         my $fpath = '';
 3950:         my $fname = $file;
 3951:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3952:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3953:         my $filepath = &build_filepath($fpath);
 3954:         if ($action eq 'copy') {
 3955:             if ($source eq '') {
 3956:                 $fetchresult = 'no source file';
 3957:                 return $fetchresult;
 3958:             } else {
 3959:                 my $destination = $filepath.'/'.$fname;
 3960:                 rename($source,$destination);
 3961:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3962:                                  $home);
 3963:             }
 3964:         } elsif ($action eq 'uploaddoc') {
 3965:             open(my $fh,'>',$filepath.'/'.$fname);
 3966:             print $fh $env{'form.'.$source};
 3967:             close($fh);
 3968:             if ($parser eq 'parse') {
 3969:                 my $mm = new File::MMagic;
 3970:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3971:                 if ($type eq 'text/html') {
 3972:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3973:                     unless ($parse_result eq 'ok') {
 3974:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3975:                     }
 3976:                 }
 3977:                 if (ref($mimetype)) {
 3978:                     $$mimetype = $type;
 3979:                 } 
 3980:             }
 3981:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3982:                                  $home);
 3983:             if ($fetchresult eq 'ok') {
 3984:                 return '/uploaded/'.$fpath.'/'.$fname;
 3985:             } else {
 3986:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3987:                         ' to host '.$home.': '.$fetchresult);
 3988:                 return '/adm/notfound.html';
 3989:             }
 3990:         }
 3991:     }
 3992:     unless ( $fetchresult eq 'ok') {
 3993:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3994:              ' to host '.$home.': '.$fetchresult);
 3995:     }
 3996:     return $fetchresult;
 3997: }
 3998: 
 3999: sub build_filepath {
 4000:     my ($fpath) = @_;
 4001:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4002:     unless ($fpath eq '') {
 4003:         my @parts=split('/',$fpath);
 4004:         foreach my $part (@parts) {
 4005:             $filepath.= '/'.$part;
 4006:             if ((-e $filepath)!=1) {
 4007:                 mkdir($filepath,0777);
 4008:             }
 4009:         }
 4010:     }
 4011:     return $filepath;
 4012: }
 4013: 
 4014: sub store_edited_file {
 4015:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4016:     my $file = $primary_url;
 4017:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4018:     my $fpath = '';
 4019:     my $fname = $file;
 4020:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4021:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4022:     my $filepath = &build_filepath($fpath);
 4023:     open(my $fh,'>',$filepath.'/'.$fname);
 4024:     print $fh $content;
 4025:     close($fh);
 4026:     my $home=&homeserver($docuname,$docudom);
 4027:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4028: 			  $home);
 4029:     if ($$fetchresult eq 'ok') {
 4030:         return '/uploaded/'.$fpath.'/'.$fname;
 4031:     } else {
 4032:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4033: 		 ' to host '.$home.': '.$$fetchresult);
 4034:         return '/adm/notfound.html';
 4035:     }
 4036: }
 4037: 
 4038: sub clean_filename {
 4039:     my ($fname,$args)=@_;
 4040: # Replace Windows backslashes by forward slashes
 4041:     $fname=~s/\\/\//g;
 4042:     if (!$args->{'keep_path'}) {
 4043:         # Get rid of everything but the actual filename
 4044: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4045:     }
 4046: # Replace spaces by underscores
 4047:     $fname=~s/\s+/\_/g;
 4048: # Transliterate non-ascii text to ascii
 4049:     my $lang = &Apache::lonlocal::current_language();
 4050:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4051: # Replace all other weird characters by nothing
 4052:     $fname=~s{[^/\w\.\-]}{}g;
 4053: # Replace all .\d. sequences with _\d. so they no longer look like version
 4054: # numbers
 4055:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4056:     return $fname;
 4057: }
 4058: 
 4059: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4060: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4061: # image with the same aspect ratio as the original, but with dimensions which do 
 4062: # not exceed $resizewidth and $resizeheight.
 4063:  
 4064: sub resizeImage {
 4065:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4066:     my $ima = Image::Magick->new;
 4067:     my $resized;
 4068:     if (-e $img_path) {
 4069:         $ima->Read($img_path);
 4070:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4071:             my $width = $ima->Get('width');
 4072:             my $height = $ima->Get('height');
 4073:             if ($width > $resizewidth) {
 4074: 	        my $factor = $width/$resizewidth;
 4075:                 my $newheight = $height/$factor;
 4076:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4077:                 $resized = 1;
 4078:             }
 4079:         }
 4080:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4081:             my $width = $ima->Get('width');
 4082:             my $height = $ima->Get('height');
 4083:             if ($height > $resizeheight) {
 4084:                 my $factor = $height/$resizeheight;
 4085:                 my $newwidth = $width/$factor;
 4086:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4087:                 $resized = 1;
 4088:             }
 4089:         }
 4090:         if ($resized) {
 4091:             $ima->Write($img_path);
 4092:         }
 4093:     }
 4094:     return;
 4095: }
 4096: 
 4097: # --------------- Take an uploaded file and put it into the userfiles directory
 4098: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4099: #                    the desired filename is in $env{"form.$formname.filename"}
 4100: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4101: #                                    canceloverwrite, scantron or ''.
 4102: #                   if 'coursedoc': upload to the current course
 4103: #                   if 'existingfile': write file to tmp/overwrites directory 
 4104: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4105: #                   $context is passed as argument to &finishuserfileupload
 4106: #        $subdir - directory in userfile to store the file into
 4107: #        $parser - instruction to parse file for objects ($parser = parse) or
 4108: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4109: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4110: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4111: #        $allfiles - reference to hash for embedded objects
 4112: #        $codebase - reference to hash for codebase of java objects
 4113: #        $desuname - username for permanent storage of uploaded file
 4114: #        $dsetudom - domain for permanaent storage of uploaded file
 4115: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4116: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4117: #        $resizewidth - width (pixels) to which to resize uploaded image
 4118: #        $resizeheight - height (pixels) to which to resize uploaded image
 4119: #        $mimetype - reference to scalar to accommodate mime type determined
 4120: #                    from File::MMagic.
 4121: # 
 4122: # output: url of file in userspace, or error: <message> 
 4123: #             or /adm/notfound.html if failure to upload occurse
 4124: 
 4125: sub userfileupload {
 4126:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4127:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4128:     if (!defined($subdir)) { $subdir='unknown'; }
 4129:     my $fname=$env{'form.'.$formname.'.filename'};
 4130:     $fname=&clean_filename($fname);
 4131:     # See if there is anything left
 4132:     unless ($fname) { return 'error: no uploaded file'; }
 4133:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4134:     if ($fname =~ /^\./) {
 4135:         my ($s,$usec) = &gettimeofday();
 4136:         while (length($usec) < 6) {
 4137:             $usec = '0'.$usec;
 4138:         }
 4139:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4140:     }
 4141:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4142:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4143:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4144:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4145:         my $now = time;
 4146:         my $filepath;
 4147:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4148:              $filepath = 'tmp/helprequests/'.$now;
 4149:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4150:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4151:                          '_'.$env{'user.domain'}.'/pending';
 4152:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4153:             my ($docuname,$docudom);
 4154:             if ($destudom =~ /^$match_domain$/) {
 4155:                 $docudom = $destudom;
 4156:             } else {
 4157:                 $docudom = $env{'user.domain'};
 4158:             }
 4159:             if ($destuname =~ /^$match_username$/) {
 4160:                 $docuname = $destuname;
 4161:             } else {
 4162:                 $docuname = $env{'user.name'};
 4163:             }
 4164:             if (exists($env{'form.group'})) {
 4165:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4166:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4167:             }
 4168:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4169:             if ($context eq 'canceloverwrite') {
 4170:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4171:                 if (-e  $tempfile) {
 4172:                     my @info = stat($tempfile);
 4173:                     if ($info[9] eq $env{'form.timestamp'}) {
 4174:                         unlink($tempfile);
 4175:                     }
 4176:                 }
 4177:                 return;
 4178:             }
 4179:         }
 4180:         # Create the directory if not present
 4181:         my @parts=split(/\//,$filepath);
 4182:         my $fullpath = $perlvar{'lonDaemons'};
 4183:         for (my $i=0;$i<@parts;$i++) {
 4184:             $fullpath .= '/'.$parts[$i];
 4185:             if ((-e $fullpath)!=1) {
 4186:                 mkdir($fullpath,0777);
 4187:             }
 4188:         }
 4189:         open(my $fh,'>',$fullpath.'/'.$fname);
 4190:         print $fh $env{'form.'.$formname};
 4191:         close($fh);
 4192:         if ($context eq 'existingfile') {
 4193:             my @info = stat($fullpath.'/'.$fname);
 4194:             return ($fullpath.'/'.$fname,$info[9]);
 4195:         } else {
 4196:             return $fullpath.'/'.$fname;
 4197:         }
 4198:     }
 4199:     if ($subdir eq 'scantron') {
 4200:         $fname = 'scantron_orig_'.$fname;
 4201:     } else {
 4202:         $fname="$subdir/$fname";
 4203:     }
 4204:     if ($context eq 'coursedoc') {
 4205: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4206: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4207:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4208:             return &finishuserfileupload($docuname,$docudom,
 4209: 					 $formname,$fname,$parser,$allfiles,
 4210: 					 $codebase,$thumbwidth,$thumbheight,
 4211:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4212:         } else {
 4213:             if ($env{'form.folder'}) {
 4214:                 $fname=$env{'form.folder'}.'/'.$fname;
 4215:             }
 4216:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4217: 				       $fname,$formname,$parser,
 4218: 				       $allfiles,$codebase,$mimetype);
 4219:         }
 4220:     } elsif (defined($destuname)) {
 4221:         my $docuname=$destuname;
 4222:         my $docudom=$destudom;
 4223: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4224: 				     $parser,$allfiles,$codebase,
 4225:                                      $thumbwidth,$thumbheight,
 4226:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4227:     } else {
 4228:         my $docuname=$env{'user.name'};
 4229:         my $docudom=$env{'user.domain'};
 4230:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4231:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4232:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4233:         }
 4234: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4235: 				     $parser,$allfiles,$codebase,
 4236:                                      $thumbwidth,$thumbheight,
 4237:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4238:     }
 4239: }
 4240: 
 4241: sub finishuserfileupload {
 4242:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4243:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4244:     my $path=$docudom.'/'.$docuname.'/';
 4245:     my $filepath=$perlvar{'lonDocRoot'};
 4246:   
 4247:     my ($fnamepath,$file,$fetchthumb);
 4248:     $file=$fname;
 4249:     if ($fname=~m|/|) {
 4250:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4251: 	$path.=$fnamepath.'/';
 4252:     }
 4253:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4254:     my $count;
 4255:     for ($count=4;$count<=$#parts;$count++) {
 4256:         $filepath.="/$parts[$count]";
 4257:         if ((-e $filepath)!=1) {
 4258: 	    mkdir($filepath,0777);
 4259:         }
 4260:     }
 4261: 
 4262: # Save the file
 4263:     {
 4264: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4265: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4266: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4267: 	    return '/adm/notfound.html';
 4268: 	}
 4269:         if ($context eq 'overwrite') {
 4270:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4271:             my $target = $filepath.'/'.$file;
 4272:             if (-e $source) {
 4273:                 my @info = stat($source);
 4274:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4275:                     unless (&File::Copy::move($source,$target)) {
 4276:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4277:                         return "Moving from $source failed";
 4278:                     }
 4279:                 } else {
 4280:                     return "Temporary file: $source had unexpected date/time for last modification";
 4281:                 }
 4282:             } else {
 4283:                 return "Temporary file: $source missing";
 4284:             }
 4285:         } elsif (!print FH ($env{'form.'.$formname})) {
 4286: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4287: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4288: 	    return '/adm/notfound.html';
 4289: 	}
 4290: 	close(FH);
 4291:         if ($resizewidth && $resizeheight) {
 4292:             my $mm = new File::MMagic;
 4293:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4294:             if ($mime_type =~ m{^image/}) {
 4295: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4296:             }  
 4297: 	}
 4298:     }
 4299:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4300:         if (ref($mimetype)) {
 4301:             if ($$mimetype eq '') {
 4302:                 my $mm = new File::MMagic;
 4303:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4304:                 $$mimetype = $type;
 4305:             }
 4306:         }
 4307:     }
 4308:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4309:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4310:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4311:                                                        $allfiles,$codebase);
 4312:             unless ($parse_result eq 'ok') {
 4313:                 &logthis('Failed to parse '.$filepath.$file.
 4314: 	   	         ' for embedded media: '.$parse_result); 
 4315:             }
 4316:         }
 4317:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4318:         my $format = $env{'form.scantron_format'};
 4319:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4320:     }
 4321:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4322:         my $input = $filepath.'/'.$file;
 4323:         my $output = $filepath.'/'.'tn-'.$file;
 4324:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4325:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4326:         system({$args[0]} @args);
 4327:         if (-e $filepath.'/'.'tn-'.$file) {
 4328:             $fetchthumb  = 1; 
 4329:         }
 4330:     }
 4331:  
 4332: # Notify homeserver to grep it
 4333: #
 4334:     my $docuhome=&homeserver($docuname,$docudom);	
 4335:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4336:     if ($fetchresult eq 'ok') {
 4337:         if ($fetchthumb) {
 4338:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4339:             if ($thumbresult ne 'ok') {
 4340:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4341:                          $docuhome.': '.$thumbresult);
 4342:             }
 4343:         }
 4344: #
 4345: # Return the URL to it
 4346:         return '/uploaded/'.$path.$file;
 4347:     } else {
 4348:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4349: 		 ': '.$fetchresult);
 4350:         return '/adm/notfound.html';
 4351:     }
 4352: }
 4353: 
 4354: sub extract_embedded_items {
 4355:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4356:     my @state = ();
 4357:     my (%lastids,%related,%shockwave,%flashvars);
 4358:     my %javafiles = (
 4359:                       codebase => '',
 4360:                       code => '',
 4361:                       archive => ''
 4362:                     );
 4363:     my %mediafiles = (
 4364:                       src => '',
 4365:                       movie => '',
 4366:                      );
 4367:     my $p;
 4368:     if ($content) {
 4369:         $p = HTML::LCParser->new($content);
 4370:     } else {
 4371:         $p = HTML::LCParser->new($fullpath);
 4372:     }
 4373:     while (my $t=$p->get_token()) {
 4374: 	if ($t->[0] eq 'S') {
 4375: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4376: 	    push(@state, $tagname);
 4377:             if (lc($tagname) eq 'allow') {
 4378:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4379:             }
 4380: 	    if (lc($tagname) eq 'img') {
 4381: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4382: 	    }
 4383: 	    if (lc($tagname) eq 'a') {
 4384:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4385:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4386:                 }
 4387: 	    }
 4388:             if (lc($tagname) eq 'script') {
 4389:                 my $src;
 4390:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4391:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4392:                 } else {
 4393:                     if ($attr->{'src'} ne '') {
 4394:                         $src = $attr->{'src'};
 4395:                         &add_filetype($allfiles,$src,'src');
 4396:                     }
 4397:                 }
 4398:                 my $text = $p->get_trimmed_text();
 4399:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4400:                     my @swfargs = split(/,/,$1);
 4401:                     foreach my $item (@swfargs) {
 4402:                         $item =~ s/["']//g;
 4403:                         $item =~ s/^\s+//;
 4404:                         $item =~ s/\s+$//;
 4405:                     }
 4406:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4407:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4408:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4409:                         } else {
 4410:                             $related{$swfargs[0]} = [$swfargs[2]];
 4411:                         }
 4412:                     }
 4413:                 }
 4414:             }
 4415:             if (lc($tagname) eq 'link') {
 4416:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4417:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4418:                 }
 4419:             }
 4420: 	    if (lc($tagname) eq 'object' ||
 4421: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4422: 		foreach my $item (keys(%javafiles)) {
 4423: 		    $javafiles{$item} = '';
 4424: 		}
 4425:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4426:                     $lastids{lc($tagname)} = $attr->{'id'};
 4427:                 }
 4428: 	    }
 4429: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4430: 		my $name = lc($attr->{'name'});
 4431: 		foreach my $item (keys(%javafiles)) {
 4432: 		    if ($name eq $item) {
 4433: 			$javafiles{$item} = $attr->{'value'};
 4434: 			last;
 4435: 		    }
 4436: 		}
 4437:                 my $pathfrom;
 4438: 		foreach my $item (keys(%mediafiles)) {
 4439: 		    if ($name eq $item) {
 4440:                         $pathfrom = $attr->{'value'};
 4441:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4442: 			&add_filetype($allfiles,$pathfrom,$name);
 4443: 			last;
 4444: 		    }
 4445: 		}
 4446:                 if ($name eq 'flashvars') {
 4447:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4448:                 }
 4449:                 if ($pathfrom ne '') {
 4450:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4451:                                          $pathfrom);
 4452:                 }
 4453: 	    }
 4454: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4455: 		foreach my $item (keys(%javafiles)) {
 4456: 		    if ($attr->{$item}) {
 4457: 			$javafiles{$item} = $attr->{$item};
 4458: 			last;
 4459: 		    }
 4460: 		}
 4461: 		foreach my $item (keys(%mediafiles)) {
 4462: 		    if ($attr->{$item}) {
 4463: 			&add_filetype($allfiles,$attr->{$item},$item);
 4464: 			last;
 4465: 		    }
 4466: 		}
 4467:                 if (lc($tagname) eq 'embed') {
 4468:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4469:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4470:                                              $attr->{'src'});
 4471:                     }
 4472:                 }
 4473: 	    }
 4474:             if (lc($tagname) eq 'iframe') {
 4475:                 my $src = $attr->{'src'} ;
 4476:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4477:                     &add_filetype($allfiles,$src,'src');
 4478:                 } elsif ($src =~ m{^/}) {
 4479:                     if ($env{'request.course.id'}) {
 4480:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4481:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4482:                         my $url = &hreflocation('',$fullpath);
 4483:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4484:                             my $relpath = $1;
 4485:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4486:                                 &add_filetype($allfiles,$1,'src');
 4487:                             }
 4488:                         }
 4489:                     }
 4490:                 }
 4491:             }
 4492:             if ($t->[4] =~ m{/>$}) {
 4493:                 pop(@state);
 4494:             }
 4495: 	} elsif ($t->[0] eq 'E') {
 4496: 	    my ($tagname) = ($t->[1]);
 4497: 	    if ($javafiles{'codebase'} ne '') {
 4498: 		$javafiles{'codebase'} .= '/';
 4499: 	    }  
 4500: 	    if (lc($tagname) eq 'applet' ||
 4501: 		lc($tagname) eq 'object' ||
 4502: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4503: 		) {
 4504: 		foreach my $item (keys(%javafiles)) {
 4505: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4506: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4507: 			&add_filetype($allfiles,$file,$item);
 4508: 		    }
 4509: 		}
 4510: 	    } 
 4511: 	    pop @state;
 4512: 	}
 4513:     }
 4514:     foreach my $id (sort(keys(%flashvars))) {
 4515:         if ($shockwave{$id} ne '') {
 4516:             my @pairs = split(/\&/,$flashvars{$id});
 4517:             foreach my $pair (@pairs) {
 4518:                 my ($key,$value) = split(/\=/,$pair);
 4519:                 if ($key eq 'thumb') {
 4520:                     &add_filetype($allfiles,$value,$key);
 4521:                 } elsif ($key eq 'content') {
 4522:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4523:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4524:                     if ($ext ne '') {
 4525:                         &add_filetype($allfiles,$path.$value,$ext);
 4526:                     }
 4527:                 }
 4528:             }
 4529:         }
 4530:     }
 4531:     return 'ok';
 4532: }
 4533: 
 4534: sub add_filetype {
 4535:     my ($allfiles,$file,$type)=@_;
 4536:     if (exists($allfiles->{$file})) {
 4537: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4538: 	    push(@{$allfiles->{$file}}, &escape($type));
 4539: 	}
 4540:     } else {
 4541: 	@{$allfiles->{$file}} = (&escape($type));
 4542:     }
 4543: }
 4544: 
 4545: sub embedded_dependency {
 4546:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4547:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4548:         if (($identifier ne '') &&
 4549:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4550:             ($pathfrom ne '')) {
 4551:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4552:             foreach my $dep (@{$related->{$identifier}}) {
 4553:                 &add_filetype($allfiles,$path.$dep,'object');
 4554:             }
 4555:         }
 4556:     }
 4557:     return;
 4558: }
 4559: 
 4560: sub bubblesheet_converter {
 4561:     my ($cdom,$fullpath,$config,$format) = @_;
 4562:     if ((&domain($cdom) ne '') &&
 4563:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4564:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4565:         my (%csvcols,%csvoptions);
 4566:         if (ref($config->{'fields'}) eq 'HASH') {  
 4567:             %csvcols = %{$config->{'fields'}};
 4568:         }
 4569:         if (ref($config->{'options'}) eq 'HASH') {
 4570:             %csvoptions = %{$config->{'options'}};
 4571:         }
 4572:         my %csvbynum = reverse(%csvcols);
 4573:         my %scantronconf = &get_scantron_config($format,$cdom);
 4574:         if (keys(%scantronconf)) {
 4575:             my %bynum = (
 4576:                           $scantronconf{CODEstart} => 'CODEstart',
 4577:                           $scantronconf{IDstart}   => 'IDstart',
 4578:                           $scantronconf{PaperID}   => 'PaperID',
 4579:                           $scantronconf{FirstName} => 'FirstName',
 4580:                           $scantronconf{LastName}  => 'LastName',
 4581:                           $scantronconf{Qstart}    => 'Qstart',
 4582:                         );
 4583:             my @ordered;
 4584:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4585:                 push(@ordered,$bynum{$item});
 4586:             }
 4587:             my %mapstart = (
 4588:                               CODEstart => 'CODE',
 4589:                               IDstart   => 'ID',
 4590:                               PaperID   => 'PaperID',
 4591:                               FirstName => 'FirstName',
 4592:                               LastName  => 'LastName',
 4593:                               Qstart    => 'FirstQuestion',
 4594:                            );
 4595:             my %maplength = (
 4596:                               CODEstart => 'CODElength',
 4597:                               IDstart   => 'IDlength',
 4598:                               PaperID   => 'PaperIDlength',
 4599:                               FirstName => 'FirstNamelength',
 4600:                               LastName  => 'LastNamelength',
 4601:             );
 4602:             if (open(my $fh,'<',$fullpath)) {
 4603:                 my $output;
 4604:                 my %lettdig = &letter_to_digits();
 4605:                 my %diglett = reverse(%lettdig);
 4606:                 my $numletts = scalar(keys(%lettdig));
 4607:                 my $num = 0;
 4608:                 while (my $line=<$fh>) {
 4609:                     $num ++;
 4610:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4611:                     $line =~ s{[\r\n]+$}{};
 4612:                     my %found;
 4613:                     my @values = split(/,/,$line);
 4614:                     my ($qstart,$record);
 4615:                     for (my $i=0; $i<@values; $i++) {
 4616:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4617:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4618:                             if ($values[$i] eq '') {
 4619:                                 $values[$i] = $scantronconf{'Qoff'};
 4620:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4621:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4622:                                     $values[$i] = $lettdig{uc($values[$i])};
 4623:                                 }
 4624:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4625:                                 if ($values[$i] =~ /^[0-9]$/) {
 4626:                                     $values[$i] = $diglett{$values[$i]};
 4627:                                 }
 4628:                             } else {
 4629:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4630:                                     my $digit;
 4631:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4632:                                         $digit = $lettdig{uc($values[$i])}-1;
 4633:                                         if ($values[$i] eq 'J') {
 4634:                                             $digit += $numletts;
 4635:                                         }
 4636:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4637:                                         $digit = $values[$i]-1;
 4638:                                         if ($values[$i] eq '0') {
 4639:                                             $digit += $numletts;
 4640:                                         }
 4641:                                     }
 4642:                                     my $qval='';
 4643:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4644:                                         if ($j == $digit) {
 4645:                                             $qval .= $scantronconf{'Qon'};
 4646:                                         } else {
 4647:                                             $qval .= $scantronconf{'Qoff'};
 4648:                                         }
 4649:                                     }
 4650:                                     $values[$i] = $qval;
 4651:                                 }
 4652:                             }
 4653:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4654:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4655:                             }
 4656:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4657:                             if ($numblank > 0) {
 4658:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4659:                             }
 4660:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4661:                                 $qstart = $i;
 4662:                                 $found{$csvbynum{$i}} = $values[$i];
 4663:                             } else {
 4664:                                 $found{'FirstQuestion'} .= $values[$i];
 4665:                             }
 4666:                         } elsif (exists($csvbynum{$i})) {
 4667:                             if ($csvoptions{'rem'}) {
 4668:                                 $values[$i] =~ s/^\s+//;
 4669:                             }
 4670:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4671:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4672:                                     $values[$i] = '0'.$values[$i];
 4673:                                 }
 4674:                             }
 4675:                             $found{$csvbynum{$i}} = $values[$i];
 4676:                         }
 4677:                     }
 4678:                     foreach my $item (@ordered) {
 4679:                         my $currlength = 1+length($record);
 4680:                         my $numspaces = $scantronconf{$item} - $currlength;
 4681:                         if ($numspaces > 0) {
 4682:                             $record .= (' ' x $numspaces);
 4683:                         }
 4684:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4685:                             unless ($item eq 'Qstart') {
 4686:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4687:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4688:                                 }
 4689:                             }
 4690:                             $record .= $found{$mapstart{$item}};
 4691:                         }
 4692:                     }
 4693:                     $output .= "$record\n";
 4694:                 }
 4695:                 close($fh);
 4696:                 if ($output) {
 4697:                     if (open(my $fh,'>',$fullpath)) {
 4698:                         print $fh $output;
 4699:                         close($fh);
 4700:                     }
 4701:                 }
 4702:             }
 4703:         }
 4704:         return;
 4705:     }
 4706: }
 4707: 
 4708: sub letter_to_digits {
 4709:     my %lettdig = (
 4710:                     A => 1,
 4711:                     B => 2,
 4712:                     C => 3,
 4713:                     D => 4,
 4714:                     E => 5,
 4715:                     F => 6,
 4716:                     G => 7,
 4717:                     H => 8,
 4718:                     I => 9,
 4719:                     J => 0,
 4720:                   );
 4721:     return %lettdig;
 4722: }
 4723: 
 4724: sub get_scantron_config {
 4725:     my ($which,$cdom) = @_;
 4726:     my @lines = &get_scantronformat_file($cdom);
 4727:     my %config;
 4728:     #FIXME probably should move to XML it has already gotten a bit much now
 4729:     foreach my $line (@lines) {
 4730:         my ($name,$descrip)=split(/:/,$line);
 4731:         if ($name ne $which ) { next; }
 4732:         chomp($line);
 4733:         my @config=split(/:/,$line);
 4734:         $config{'name'}=$config[0];
 4735:         $config{'description'}=$config[1];
 4736:         $config{'CODElocation'}=$config[2];
 4737:         $config{'CODEstart'}=$config[3];
 4738:         $config{'CODElength'}=$config[4];
 4739:         $config{'IDstart'}=$config[5];
 4740:         $config{'IDlength'}=$config[6];
 4741:         $config{'Qstart'}=$config[7];
 4742:         $config{'Qlength'}=$config[8];
 4743:         $config{'Qoff'}=$config[9];
 4744:         $config{'Qon'}=$config[10];
 4745:         $config{'PaperID'}=$config[11];
 4746:         $config{'PaperIDlength'}=$config[12];
 4747:         $config{'FirstName'}=$config[13];
 4748:         $config{'FirstNamelength'}=$config[14];
 4749:         $config{'LastName'}=$config[15];
 4750:         $config{'LastNamelength'}=$config[16];
 4751:         $config{'BubblesPerRow'}=$config[17];
 4752:         last;
 4753:     }
 4754:     return %config;
 4755: }
 4756: 
 4757: sub get_scantronformat_file {
 4758:     my ($cdom) = @_;
 4759:     if ($cdom eq '') {
 4760:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4761:     }
 4762:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4763:     my $gottab = 0;
 4764:     my @lines;
 4765:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4766:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4767:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4768:             if ($formatfile ne '-1') {
 4769:                 @lines = split("\n",$formatfile,-1);
 4770:                 $gottab = 1;
 4771:             }
 4772:         }
 4773:     }
 4774:     if (!$gottab) {
 4775:         my $confname = $cdom.'-domainconfig';
 4776:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4777:         my $formatfile = &getfile($default);
 4778:         if ($formatfile ne '-1') {
 4779:             @lines = split("\n",$formatfile,-1);
 4780:             $gottab = 1;
 4781:         }
 4782:     }
 4783:     if (!$gottab) {
 4784:         my @domains = &current_machine_domains();
 4785:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4786:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4787:                 @lines = <$fh>;
 4788:                 close($fh);
 4789:             }
 4790:         } else {
 4791:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4792:                 @lines = <$fh>;
 4793:                 close($fh);
 4794:             }
 4795:         }
 4796:     }
 4797:     return @lines;
 4798: }
 4799: 
 4800: sub removeuploadedurl {
 4801:     my ($url)=@_;	
 4802:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4803:     return &removeuserfile($uname,$udom,$fname);
 4804: }
 4805: 
 4806: sub removeuserfile {
 4807:     my ($docuname,$docudom,$fname)=@_;
 4808:     my $home=&homeserver($docuname,$docudom);    
 4809:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4810:     if ($result eq 'ok') {	
 4811:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4812:             my $metafile = $fname.'.meta';
 4813:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4814: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4815:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4816:             my $sqlresult = 
 4817:                 &update_portfolio_table($docuname,$docudom,$file,
 4818:                                         'portfolio_metadata',$group,
 4819:                                         'delete');
 4820:         }
 4821:     }
 4822:     return $result;
 4823: }
 4824: 
 4825: sub mkdiruserfile {
 4826:     my ($docuname,$docudom,$dir)=@_;
 4827:     my $home=&homeserver($docuname,$docudom);
 4828:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4829: }
 4830: 
 4831: sub renameuserfile {
 4832:     my ($docuname,$docudom,$old,$new)=@_;
 4833:     my $home=&homeserver($docuname,$docudom);
 4834:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4835:                         &escape("$old").':'.&escape("$new"),$home);
 4836:     if ($result eq 'ok') {
 4837:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4838:             my $oldmeta = $old.'.meta';
 4839:             my $newmeta = $new.'.meta';
 4840:             my $metaresult = 
 4841:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4842: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4843:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4844:             my $sqlresult = 
 4845:                 &update_portfolio_table($docuname,$docudom,$file,
 4846:                                         'portfolio_metadata',$group,
 4847:                                         'delete');
 4848:         }
 4849:     }
 4850:     return $result;
 4851: }
 4852: 
 4853: # ------------------------------------------------------------------------- Log
 4854: 
 4855: sub log {
 4856:     my ($dom,$nam,$hom,$what)=@_;
 4857:     return critical("log:$dom:$nam:$what",$hom);
 4858: }
 4859: 
 4860: # ------------------------------------------------------------------ Course Log
 4861: #
 4862: # This routine flushes several buffers of non-mission-critical nature
 4863: #
 4864: 
 4865: sub flushcourselogs {
 4866:     &logthis('Flushing log buffers');
 4867: #
 4868: # course logs
 4869: # This is a log of all transactions in a course, which can be used
 4870: # for data mining purposes
 4871: #
 4872: # It also collects the courseid database, which lists last transaction
 4873: # times and course titles for all courseids
 4874: #
 4875:     my %courseidbuffer=();
 4876:     foreach my $crsid (keys(%courselogs)) {
 4877:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4878: 		          &escape($courselogs{$crsid}),
 4879: 		          $coursehombuf{$crsid}) eq 'ok') {
 4880: 	    delete $courselogs{$crsid};
 4881:         } else {
 4882:             &logthis('Failed to flush log buffer for '.$crsid);
 4883:             if (length($courselogs{$crsid})>40000) {
 4884:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4885:                         " exceeded maximum size, deleting.</font>");
 4886:                delete $courselogs{$crsid};
 4887:             }
 4888:         }
 4889:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4890:             'description' => $coursedescrbuf{$crsid},
 4891:             'inst_code'    => $courseinstcodebuf{$crsid},
 4892:             'type'        => $coursetypebuf{$crsid},
 4893:             'owner'       => $courseownerbuf{$crsid},
 4894:         };
 4895:     }
 4896: #
 4897: # Write course id database (reverse lookup) to homeserver of courses 
 4898: # Is used in pickcourse
 4899: #
 4900:     foreach my $crs_home (keys(%courseidbuffer)) {
 4901:         my $response = &courseidput(&host_domain($crs_home),
 4902:                                     $courseidbuffer{$crs_home},
 4903:                                     $crs_home,'timeonly');
 4904:     }
 4905: #
 4906: # File accesses
 4907: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4908: #
 4909:     foreach my $entry (keys(%accesshash)) {
 4910:         if ($entry =~ /___count$/) {
 4911:             my ($dom,$name);
 4912:             ($dom,$name,undef)=
 4913: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4914:             if (! defined($dom) || $dom eq '' || 
 4915:                 ! defined($name) || $name eq '') {
 4916:                 my $cid = $env{'request.course.id'};
 4917:                 $dom  = $env{'request.'.$cid.'.domain'};
 4918:                 $name = $env{'request.'.$cid.'.num'};
 4919:             }
 4920:             my $value = $accesshash{$entry};
 4921:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4922:             my %temphash=($url => $value);
 4923:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4924:             if ($result eq 'ok') {
 4925:                 delete $accesshash{$entry};
 4926:             }
 4927:         } else {
 4928:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4929:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4930:             my %temphash=($entry => $accesshash{$entry});
 4931:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4932:                 delete $accesshash{$entry};
 4933:             }
 4934:         }
 4935:     }
 4936: #
 4937: # Roles
 4938: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4939: #
 4940:     foreach my $entry (keys(%userrolehash)) {
 4941:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4942: 	    split(/\:/,$entry);
 4943:         if (&Apache::lonnet::put('nohist_userroles',
 4944:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4945:                 $rudom,$runame) eq 'ok') {
 4946: 	    delete $userrolehash{$entry};
 4947:         }
 4948:     }
 4949: #
 4950: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4951: #
 4952:     my %domrolebuffer = ();
 4953:     foreach my $entry (keys(%domainrolehash)) {
 4954:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4955:         if ($domrolebuffer{$rudom}) {
 4956:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4957:                       '='.&escape($domainrolehash{$entry});
 4958:         } else {
 4959:             $domrolebuffer{$rudom}.=&escape($entry).
 4960:                       '='.&escape($domainrolehash{$entry});
 4961:         }
 4962:         delete $domainrolehash{$entry};
 4963:     }
 4964:     foreach my $dom (keys(%domrolebuffer)) {
 4965: 	my %servers;
 4966: 	if (defined(&domain($dom,'primary'))) {
 4967: 	    my $primary=&domain($dom,'primary');
 4968: 	    my $hostname=&hostname($primary);
 4969: 	    $servers{$primary} = $hostname;
 4970: 	} else { 
 4971: 	    %servers = &get_servers($dom,'library');
 4972: 	}
 4973: 	foreach my $tryserver (keys(%servers)) {
 4974: 	    if (&reply('domroleput:'.$dom.':'.
 4975: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4976: 		last;
 4977: 	    } else {  
 4978: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4979: 	    }
 4980:         }
 4981:     }
 4982:     $dumpcount++;
 4983: }
 4984: 
 4985: sub courselog {
 4986:     my $what=shift;
 4987:     $what=time.':'.$what;
 4988:     unless ($env{'request.course.id'}) { return ''; }
 4989:     $coursedombuf{$env{'request.course.id'}}=
 4990:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4991:     $coursenumbuf{$env{'request.course.id'}}=
 4992:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4993:     $coursehombuf{$env{'request.course.id'}}=
 4994:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4995:     $coursedescrbuf{$env{'request.course.id'}}=
 4996:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4997:     $courseinstcodebuf{$env{'request.course.id'}}=
 4998:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4999:     $courseownerbuf{$env{'request.course.id'}}=
 5000:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5001:     $coursetypebuf{$env{'request.course.id'}}=
 5002:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5003:     if (defined $courselogs{$env{'request.course.id'}}) {
 5004: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5005:     } else {
 5006: 	$courselogs{$env{'request.course.id'}}.=$what;
 5007:     }
 5008:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5009: 	&flushcourselogs();
 5010:     }
 5011: }
 5012: 
 5013: sub courseacclog {
 5014:     my $fnsymb=shift;
 5015:     unless ($env{'request.course.id'}) { return ''; }
 5016:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5017:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5018:         $what.=':POST';
 5019:         # FIXME: Probably ought to escape things....
 5020: 	foreach my $key (keys(%env)) {
 5021:             if ($key=~/^form\.(.*)/) {
 5022:                 my $formitem = $1;
 5023:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5024:                     $what.=':'.$formitem.'='.$env{$key};
 5025:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5026:                     if ($formitem eq 'proctorpassword') {
 5027:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5028:                     } else {
 5029:                         $what.=':'.$formitem.'='.$env{$key};
 5030:                     }
 5031:                 }
 5032:             }
 5033:         }
 5034:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5035:         # FIXME: We should not be depending on a form parameter that someone
 5036:         # editing lonsearchcat.pm might change in the future.
 5037:         if ($env{'form.phase'} eq 'course_search') {
 5038:             $what.= ':POST';
 5039:             # FIXME: Probably ought to escape things....
 5040:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5041:                                  'crsdiscuss') {
 5042:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5043:             }
 5044:         }
 5045:     }
 5046:     &courselog($what);
 5047: }
 5048: 
 5049: sub countacc {
 5050:     my $url=&declutter(shift);
 5051:     return if (! defined($url) || $url eq '');
 5052:     unless ($env{'request.course.id'}) { return ''; }
 5053: #
 5054: # Mark that this url was used in this course
 5055: #
 5056:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5057: #
 5058: # Increase the access count for this resource in this child process
 5059: #
 5060:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5061:     $accesshash{$key}++;
 5062: }
 5063: 
 5064: sub linklog {
 5065:     my ($from,$to)=@_;
 5066:     $from=&declutter($from);
 5067:     $to=&declutter($to);
 5068:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5069:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5070: }
 5071: 
 5072: sub statslog {
 5073:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5074:     if ($users<2) { return; }
 5075:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5076:             'course'       => $env{'request.course.id'},
 5077:             'sections'     => '"all"',
 5078:             'num_students' => $users,
 5079:             'part'         => $part,
 5080:             'symb'         => $symb,
 5081:             'mean_tries'   => $av_attempts,
 5082:             'deg_of_diff'  => $degdiff});
 5083:     foreach my $key (keys(%dynstore)) {
 5084:         $accesshash{$key}=$dynstore{$key};
 5085:     }
 5086: }
 5087:   
 5088: sub userrolelog {
 5089:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5090:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5091:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5092:        $userrolehash
 5093:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5094:                     =$tend.':'.$tstart;
 5095:     }
 5096:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5097:        $userrolehash
 5098:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5099:                     =$tend.':'.$tstart;
 5100:     }
 5101:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5102:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5103:        $domainrolehash
 5104:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5105:                     = $tend.':'.$tstart;
 5106:     }
 5107: }
 5108: 
 5109: sub courserolelog {
 5110:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5111:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5112:         my $cdom = $1;
 5113:         my $cnum = $2;
 5114:         my $sec = $3;
 5115:         my $namespace = 'rolelog';
 5116:         my %storehash = (
 5117:                            role    => $trole,
 5118:                            start   => $tstart,
 5119:                            end     => $tend,
 5120:                            selfenroll => $selfenroll,
 5121:                            context    => $context,
 5122:                         );
 5123:         if ($trole eq 'gr') {
 5124:             $namespace = 'groupslog';
 5125:             $storehash{'group'} = $sec;
 5126:         } else {
 5127:             $storehash{'section'} = $sec;
 5128:         }
 5129:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5130:                    $domain,$cnum,$cdom);
 5131:         if (($trole ne 'st') || ($sec ne '')) {
 5132:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5133:         }
 5134:     }
 5135:     return;
 5136: }
 5137: 
 5138: sub domainrolelog {
 5139:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5140:     if ($area =~ m{^/($match_domain)/$}) {
 5141:         my $cdom = $1;
 5142:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5143:         my $namespace = 'rolelog';
 5144:         my %storehash = (
 5145:                            role    => $trole,
 5146:                            start   => $tstart,
 5147:                            end     => $tend,
 5148:                            context => $context,
 5149:                         );
 5150:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5151:                    $domain,$domconfiguser,$cdom);
 5152:     }
 5153:     return;
 5154: 
 5155: }
 5156: 
 5157: sub coauthorrolelog {
 5158:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5159:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5160:         my $audom = $1;
 5161:         my $auname = $2;
 5162:         my $namespace = 'rolelog';
 5163:         my %storehash = (
 5164:                            role    => $trole,
 5165:                            start   => $tstart,
 5166:                            end     => $tend,
 5167:                            context => $context,
 5168:                         );
 5169:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5170:                    $domain,$auname,$audom);
 5171:     }
 5172:     return;
 5173: }
 5174: 
 5175: sub get_course_adv_roles {
 5176:     my ($cid,$codes) = @_;
 5177:     $cid=$env{'request.course.id'} unless (defined($cid));
 5178:     my %coursehash=&coursedescription($cid);
 5179:     my $crstype = &Apache::loncommon::course_type($cid);
 5180:     my %nothide=();
 5181:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5182:         if ($user !~ /:/) {
 5183: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5184:         } else {
 5185:             $nothide{$user}=1;
 5186:         }
 5187:     }
 5188:     my @possdoms = ($coursehash{'domain'});
 5189:     if ($coursehash{'checkforpriv'}) {
 5190:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5191:     }
 5192:     my %returnhash=();
 5193:     my %dumphash=
 5194:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5195:     my $now=time;
 5196:     my %privileged;
 5197:     foreach my $entry (keys(%dumphash)) {
 5198: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5199:         if (($tstart) && ($tstart<0)) { next; }
 5200:         if (($tend) && ($tend<$now)) { next; }
 5201:         if (($tstart) && ($now<$tstart)) { next; }
 5202:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5203: 	if ($username eq '' || $domain eq '') { next; }
 5204:         if ((&privileged($username,$domain,\@possdoms)) &&
 5205:             (!$nothide{$username.':'.$domain})) { next; }
 5206: 	if ($role eq 'cr') { next; }
 5207:         if ($codes) {
 5208:             if ($section) { $role .= ':'.$section; }
 5209:             if ($returnhash{$role}) {
 5210:                 $returnhash{$role}.=','.$username.':'.$domain;
 5211:             } else {
 5212:                 $returnhash{$role}=$username.':'.$domain;
 5213:             }
 5214:         } else {
 5215:             my $key=&plaintext($role,$crstype);
 5216:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5217:             if ($returnhash{$key}) {
 5218: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5219:             } else {
 5220:                 $returnhash{$key}=$username.':'.$domain;
 5221:             }
 5222:         }
 5223:     }
 5224:     return %returnhash;
 5225: }
 5226: 
 5227: sub get_my_roles {
 5228:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5229:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5230:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5231:     my (%dumphash,%nothide);
 5232:     if ($context eq 'userroles') {
 5233:         %dumphash = &dump('roles',$udom,$uname);
 5234:     } else {
 5235:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5236:         if ($hidepriv) {
 5237:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5238:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5239:                 if ($user !~ /:/) {
 5240:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5241:                 } else {
 5242:                     $nothide{$user} = 1;
 5243:                 }
 5244:             }
 5245:         }
 5246:     }
 5247:     my %returnhash=();
 5248:     my $now=time;
 5249:     my %privileged;
 5250:     foreach my $entry (keys(%dumphash)) {
 5251:         my ($role,$tend,$tstart);
 5252:         if ($context eq 'userroles') {
 5253:             next if ($entry =~ /^rolesdef/);
 5254: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5255:         } else {
 5256:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5257:         }
 5258:         if (($tstart) && ($tstart<0)) { next; }
 5259:         my $status = 'active';
 5260:         if (($tend) && ($tend<=$now)) {
 5261:             $status = 'previous';
 5262:         } 
 5263:         if (($tstart) && ($now<$tstart)) {
 5264:             $status = 'future';
 5265:         }
 5266:         if (ref($types) eq 'ARRAY') {
 5267:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5268:                 next;
 5269:             } 
 5270:         } else {
 5271:             if ($status ne 'active') {
 5272:                 next;
 5273:             }
 5274:         }
 5275:         my ($rolecode,$username,$domain,$section,$area);
 5276:         if ($context eq 'userroles') {
 5277:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5278:             (undef,$domain,$username,$section) = split(/\//,$area);
 5279:         } else {
 5280:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5281:         }
 5282:         if (ref($roledoms) eq 'ARRAY') {
 5283:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5284:                 next;
 5285:             }
 5286:         }
 5287:         if (ref($roles) eq 'ARRAY') {
 5288:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5289:                 if ($role =~ /^cr\//) {
 5290:                     if (!grep(/^cr$/,@{$roles})) {
 5291:                         next;
 5292:                     }
 5293:                 } elsif ($role =~ /^gr\//) {
 5294:                     if (!grep(/^gr$/,@{$roles})) {
 5295:                         next;
 5296:                     }
 5297:                 } else {
 5298:                     next;
 5299:                 }
 5300:             }
 5301:         }
 5302:         if ($hidepriv) {
 5303:             my @privroles = ('dc','su');
 5304:             if ($context eq 'userroles') {
 5305:                 next if (grep(/^\Q$role\E$/,@privroles));
 5306:             } else {
 5307:                 my $possdoms = [$domain];
 5308:                 if (ref($roledoms) eq 'ARRAY') {
 5309:                    push(@{$possdoms},@{$roledoms}); 
 5310:                 }
 5311:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5312:                     if (!$nothide{$username.':'.$domain}) {
 5313:                         next;
 5314:                     }
 5315:                 }
 5316:             }
 5317:         }
 5318:         if ($withsec) {
 5319:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5320:                 $tstart.':'.$tend;
 5321:         } else {
 5322:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5323:         }
 5324:     }
 5325:     return %returnhash;
 5326: }
 5327: 
 5328: sub get_all_adhocroles {
 5329:     my ($dom) = @_;
 5330:     my @roles_by_num = ();
 5331:     my %domdefaults = &get_domain_defaults($dom);
 5332:     my (%description,%access_in_dom,%access_info);
 5333:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5334:         my $count = 0;
 5335:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5336:         my %ordered;
 5337:         foreach my $role (sort(keys(%domcurrent))) {
 5338:             my ($order,$desc,$access_in_dom);
 5339:             if (ref($domcurrent{$role}) eq 'HASH') {
 5340:                 $order = $domcurrent{$role}{'order'};
 5341:                 $desc = $domcurrent{$role}{'desc'};
 5342:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5343:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5344:             }
 5345:             if ($order eq '') {
 5346:                 $order = $count;
 5347:             }
 5348:             $ordered{$order} = $role;
 5349:             if ($desc ne '') {
 5350:                 $description{$role} = $desc;
 5351:             } else {
 5352:                 $description{$role}= $role;
 5353:             }
 5354:             $count++;
 5355:         }
 5356:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5357:             push(@roles_by_num,$ordered{$item});
 5358:         }
 5359:     }
 5360:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5361: }
 5362: 
 5363: sub get_my_adhocroles {
 5364:     my ($cid,$checkreg) = @_;
 5365:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5366:     if ($env{'request.course.id'} eq $cid) {
 5367:         $cdom = $env{'course.'.$cid.'.domain'};
 5368:         $cnum = $env{'course.'.$cid.'.num'};
 5369:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5370:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5371:         $cdom = $1;
 5372:         $cnum = $2;
 5373:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5374:                                      $cdom,$cnum);
 5375:     }
 5376:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5377:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5378:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5379:         if ($rosterhash{$user} ne '') {
 5380:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5381:             return ([],{}) if ($type eq 'auto');
 5382:         }
 5383:     }
 5384:     if (($cdom ne '') && ($cnum ne ''))  {
 5385:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5386:             my $then=$env{'user.login.time'};
 5387:             my $update=$env{'user.update.time'};
 5388:             if (!$update) {
 5389:                 $update = $then;
 5390:             }
 5391:             my @liveroles;
 5392:             foreach my $role ('dh','da') {
 5393:                 if ($env{"user.role.$role./$cdom/"}) {
 5394:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5395:                     my $limit = $update;
 5396:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5397:                         $limit = $then;
 5398:                     }
 5399:                     my $activerole = 1;
 5400:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5401:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5402:                     if ($activerole) {
 5403:                         push(@liveroles,$role);
 5404:                     }
 5405:                 }
 5406:             }
 5407:             if (@liveroles) {
 5408:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5409:                     my ($accessref,$accessinfo,%access_in_dom);
 5410:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5411:                     if (ref($roles_by_num) eq 'ARRAY') {
 5412:                         if (@{$roles_by_num}) {
 5413:                             my %settings;
 5414:                             if ($env{'request.course.id'} eq $cid) {
 5415:                                 foreach my $envkey (keys(%env)) {
 5416:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5417:                                         $settings{$1} = $env{$envkey};
 5418:                                     }
 5419:                                 }
 5420:                             } else {
 5421:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5422:                             }
 5423:                             my %setincrs;
 5424:                             if ($settings{'internal.adhocaccess'}) {
 5425:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5426:                             }
 5427:                             my @statuses;
 5428:                             if ($env{'environment.inststatus'}) {
 5429:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5430:                             }
 5431:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5432:                             if (ref($accessref) eq 'HASH') {
 5433:                                 %access_in_dom = %{$accessref};
 5434:                             }
 5435:                             foreach my $role (@{$roles_by_num}) {
 5436:                                 my ($curraccess,@okstatus,@personnel);
 5437:                                 if ($setincrs{$role}) {
 5438:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5439:                                     if ($curraccess eq 'status') {
 5440:                                         @okstatus = split(/\&/,$rest);
 5441:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5442:                                         @personnel = split(/\&/,$rest);
 5443:                                     }
 5444:                                 } else {
 5445:                                     $curraccess = $access_in_dom{$role};
 5446:                                     if (ref($accessinfo) eq 'HASH') {
 5447:                                         if ($curraccess eq 'status') {
 5448:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5449:                                                 @okstatus = @{$accessinfo->{$role}};
 5450:                                             }
 5451:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5452:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5453:                                                 @personnel = @{$accessinfo->{$role}};
 5454:                                             }
 5455:                                         }
 5456:                                     }
 5457:                                 }
 5458:                                 if ($curraccess eq 'none') {
 5459:                                     next;
 5460:                                 } elsif ($curraccess eq 'all') {
 5461:                                     push(@possroles,$role);
 5462:                                 } elsif ($curraccess eq 'dh') {
 5463:                                     if (grep(/^dh$/,@liveroles)) {
 5464:                                         push(@possroles,$role);
 5465:                                     } else {
 5466:                                         next;
 5467:                                     }
 5468:                                 } elsif ($curraccess eq 'da') {
 5469:                                     if (grep(/^da$/,@liveroles)) {
 5470:                                         push(@possroles,$role);
 5471:                                     } else {
 5472:                                         next;
 5473:                                     }
 5474:                                 } elsif ($curraccess eq 'status') {
 5475:                                     if (@okstatus) {
 5476:                                         if (!@statuses) {
 5477:                                             if (grep(/^default$/,@okstatus)) {
 5478:                                                 push(@possroles,$role);
 5479:                                             }
 5480:                                         } else {
 5481:                                             foreach my $status (@okstatus) {
 5482:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5483:                                                     push(@possroles,$role);
 5484:                                                     last;
 5485:                                                 }
 5486:                                             }
 5487:                                         }
 5488:                                     }
 5489:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5490:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5491:                                         if ($curraccess eq 'exc') {
 5492:                                             push(@possroles,$role);
 5493:                                         }
 5494:                                     } elsif ($curraccess eq 'inc') {
 5495:                                         push(@possroles,$role);
 5496:                                     }
 5497:                                 }
 5498:                             }
 5499:                         }
 5500:                     }
 5501:                 }
 5502:             }
 5503:         }
 5504:     }
 5505:     unless (ref($description) eq 'HASH') {
 5506:         if (ref($roles_by_num) eq 'ARRAY') {
 5507:             my %desc;
 5508:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5509:             $description = \%desc;
 5510:         } else {
 5511:             $description = {};
 5512:         }
 5513:     }
 5514:     return (\@possroles,$description);
 5515: }
 5516: 
 5517: # ----------------------------------------------------- Frontpage Announcements
 5518: #
 5519: #
 5520: 
 5521: sub postannounce {
 5522:     my ($server,$text)=@_;
 5523:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5524:     unless ($text=~/\w/) { $text=''; }
 5525:     return &reply('setannounce:'.&escape($text),$server);
 5526: }
 5527: 
 5528: sub getannounce {
 5529: 
 5530:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5531: 	my $announcement='';
 5532: 	while (my $line = <$fh>) { $announcement .= $line; }
 5533: 	close($fh);
 5534: 	if ($announcement=~/\w/) { 
 5535: 	    return 
 5536:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5537:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5538: 	} else {
 5539: 	    return '';
 5540: 	}
 5541:     } else {
 5542: 	return '';
 5543:     }
 5544: }
 5545: 
 5546: # ---------------------------------------------------------- Course ID routines
 5547: # Deal with domain's nohist_courseid.db files
 5548: #
 5549: 
 5550: sub courseidput {
 5551:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5552:     return unless (ref($storehash) eq 'HASH');
 5553:     my $outcome;
 5554:     if ($caller eq 'timeonly') {
 5555:         my $cids = '';
 5556:         foreach my $item (keys(%$storehash)) {
 5557:             $cids.=&escape($item).'&';
 5558:         }
 5559:         $cids=~s/\&$//;
 5560:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5561:                           $coursehome);       
 5562:     } else {
 5563:         my $items = '';
 5564:         foreach my $item (keys(%$storehash)) {
 5565:             $items.= &escape($item).'='.
 5566:                      &freeze_escape($$storehash{$item}).'&';
 5567:         }
 5568:         $items=~s/\&$//;
 5569:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5570:                           $coursehome);
 5571:     }
 5572:     if ($outcome eq 'unknown_cmd') {
 5573:         my $what;
 5574:         foreach my $cid (keys(%$storehash)) {
 5575:             $what .= &escape($cid).'=';
 5576:             foreach my $item ('description','inst_code','owner','type') {
 5577:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5578:             }
 5579:             $what =~ s/\:$/&/;
 5580:         }
 5581:         $what =~ s/\&$//;  
 5582:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5583:     } else {
 5584:         return $outcome;
 5585:     }
 5586: }
 5587: 
 5588: sub courseiddump {
 5589:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5590:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5591:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5592:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5593:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5594:     my $as_hash = 1;
 5595:     my %returnhash;
 5596:     if (!$domfilter) { $domfilter=''; }
 5597:     my %libserv = &all_library();
 5598:     foreach my $tryserver (keys(%libserv)) {
 5599:         if ( (  $hostidflag == 1 
 5600: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5601: 	     || (!defined($hostidflag)) ) {
 5602: 
 5603: 	    if (($domfilter eq '') ||
 5604: 		(&host_domain($tryserver) eq $domfilter)) {
 5605:                 my $rep;
 5606:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5607:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5608:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5609:                                 &escape($descfilter), &escape($instcodefilter), 
 5610:                                 &escape($ownerfilter), &escape($coursefilter),
 5611:                                 &escape($typefilter), &escape($regexp_ok), 
 5612:                                 $as_hash, &escape($selfenrollonly), 
 5613:                                 &escape($catfilter), $showhidden, $caller, 
 5614:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5615:                                 &escape($createdbefore), &escape($createdafter), 
 5616:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5617:                                 $reqcrsdom,&escape($reqinstcode))));
 5618:                 } else {
 5619:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5620:                              $sincefilter.':'.&escape($descfilter).':'.
 5621:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5622:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5623:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5624:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5625:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5626:                              &escape($cc_clone).':'.$cloneonly.':'.
 5627:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5628:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5629:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5630:                 }
 5631:                      
 5632:                 my @pairs=split(/\&/,$rep);
 5633:                 foreach my $item (@pairs) {
 5634:                     my ($key,$value)=split(/\=/,$item,2);
 5635:                     $key = &unescape($key);
 5636:                     next if ($key =~ /^error: 2 /);
 5637:                     my $result = &thaw_unescape($value);
 5638:                     if (ref($result) eq 'HASH') {
 5639:                         $returnhash{$key}=$result;
 5640:                     } else {
 5641:                         my @responses = split(/:/,$value);
 5642:                         my @items = ('description','inst_code','owner','type');
 5643:                         for (my $i=0; $i<@responses; $i++) {
 5644:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5645:                         }
 5646:                     }
 5647:                 }
 5648:             }
 5649:         }
 5650:     }
 5651:     return %returnhash;
 5652: }
 5653: 
 5654: sub courselastaccess {
 5655:     my ($cdom,$cnum,$hostidref) = @_;
 5656:     my %returnhash;
 5657:     if ($cdom && $cnum) {
 5658:         my $chome = &homeserver($cnum,$cdom);
 5659:         if ($chome ne 'no_host') {
 5660:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5661:             &extract_lastaccess(\%returnhash,$rep);
 5662:         }
 5663:     } else {
 5664:         if (!$cdom) { $cdom=''; }
 5665:         my %libserv = &all_library();
 5666:         foreach my $tryserver (keys(%libserv)) {
 5667:             if (ref($hostidref) eq 'ARRAY') {
 5668:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5669:             } 
 5670:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5671:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5672:                 &extract_lastaccess(\%returnhash,$rep);
 5673:             }
 5674:         }
 5675:     }
 5676:     return %returnhash;
 5677: }
 5678: 
 5679: sub extract_lastaccess {
 5680:     my ($returnhash,$rep) = @_;
 5681:     if (ref($returnhash) eq 'HASH') {
 5682:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5683:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5684:                  $rep eq '') {
 5685:             my @pairs=split(/\&/,$rep);
 5686:             foreach my $item (@pairs) {
 5687:                 my ($key,$value)=split(/\=/,$item,2);
 5688:                 $key = &unescape($key);
 5689:                 next if ($key =~ /^error: 2 /);
 5690:                 $returnhash->{$key} = &thaw_unescape($value);
 5691:             }
 5692:         }
 5693:     }
 5694:     return;
 5695: }
 5696: 
 5697: # ---------------------------------------------------------- DC e-mail
 5698: 
 5699: sub dcmailput {
 5700:     my ($domain,$msgid,$message,$server)=@_;
 5701:     my $status = &Apache::lonnet::critical(
 5702:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5703:        &escape($message),$server);
 5704:     return $status;
 5705: }
 5706: 
 5707: sub dcmaildump {
 5708:     my ($dom,$startdate,$enddate,$senders) = @_;
 5709:     my %returnhash=();
 5710: 
 5711:     if (defined(&domain($dom,'primary'))) {
 5712:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5713:                                                          &escape($enddate).':';
 5714: 	my @esc_senders=map { &escape($_)} @$senders;
 5715: 	$cmd.=&escape(join('&',@esc_senders));
 5716: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5717:             my ($key,$value) = split(/\=/,$line,2);
 5718:             if (($key) && ($value)) {
 5719:                 $returnhash{&unescape($key)} = &unescape($value);
 5720:             }
 5721:         }
 5722:     }
 5723:     return %returnhash;
 5724: }
 5725: # ---------------------------------------------------------- Domain roles
 5726: 
 5727: sub get_domain_roles {
 5728:     my ($dom,$roles,$startdate,$enddate)=@_;
 5729:     if ((!defined($startdate)) || ($startdate eq '')) {
 5730:         $startdate = '.';
 5731:     }
 5732:     if ((!defined($enddate)) || ($enddate eq '')) {
 5733:         $enddate = '.';
 5734:     }
 5735:     my $rolelist;
 5736:     if (ref($roles) eq 'ARRAY') {
 5737:         $rolelist = join('&',@{$roles});
 5738:     }
 5739:     my %personnel = ();
 5740: 
 5741:     my %servers = &get_servers($dom,'library');
 5742:     foreach my $tryserver (keys(%servers)) {
 5743: 	%{$personnel{$tryserver}}=();
 5744: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5745: 					    &escape($startdate).':'.
 5746: 					    &escape($enddate).':'.
 5747: 					    &escape($rolelist), $tryserver))) {
 5748: 	    my ($key,$value) = split(/\=/,$line,2);
 5749: 	    if (($key) && ($value)) {
 5750: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5751: 	    }
 5752: 	}
 5753:     }
 5754:     return %personnel;
 5755: }
 5756: 
 5757: sub get_active_domroles {
 5758:     my ($dom,$roles) = @_;
 5759:     return () unless (ref($roles) eq 'ARRAY');
 5760:     my $now = time;
 5761:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5762:     my %domroles;
 5763:     foreach my $server (keys(%dompersonnel)) {
 5764:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5765:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5766:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5767:         }
 5768:     }
 5769:     return %domroles;
 5770: }
 5771: 
 5772: # ----------------------------------------------------------- Interval timing 
 5773: 
 5774: {
 5775: # Caches needed for speedup of navmaps
 5776: # We don't want to cache this for very long at all (5 seconds at most)
 5777: # 
 5778: # The user for whom we cache
 5779: my $cachedkey='';
 5780: # The cached times for this user
 5781: my %cachedtimes=();
 5782: # When this was last done
 5783: my $cachedtime='';
 5784: 
 5785: sub load_all_first_access {
 5786:     my ($uname,$udom,$ignorecache)=@_;
 5787:     if (($cachedkey eq $uname.':'.$udom) &&
 5788:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5789:         (!$ignorecache)) {
 5790:         return;
 5791:     }
 5792:     $cachedtime=time;
 5793:     $cachedkey=$uname.':'.$udom;
 5794:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5795: }
 5796: 
 5797: sub get_first_access {
 5798:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5799:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5800:     if ($argsymb) { $symb=$argsymb; }
 5801:     my ($map,$id,$res)=&decode_symb($symb);
 5802:     if ($argmap) { $map = $argmap; }
 5803:     if ($type eq 'course') {
 5804: 	$res='course';
 5805:     } elsif ($type eq 'map') {
 5806: 	$res=&symbread($map);
 5807:     } else {
 5808: 	$res=$symb;
 5809:     }
 5810:     &load_all_first_access($uname,$udom,$ignorecache);
 5811:     return $cachedtimes{"$courseid\0$res"};
 5812: }
 5813: 
 5814: sub set_first_access {
 5815:     my ($type,$interval)=@_;
 5816:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5817:     my ($map,$id,$res)=&decode_symb($symb);
 5818:     if ($type eq 'course') {
 5819: 	$res='course';
 5820:     } elsif ($type eq 'map') {
 5821: 	$res=&symbread($map);
 5822:     } else {
 5823: 	$res=$symb;
 5824:     }
 5825:     $cachedkey='';
 5826:     my $firstaccess=&get_first_access($type,$symb,$map);
 5827:     if ($firstaccess) {
 5828:         &logthis("First access time already set ($firstaccess) when attempting ".
 5829:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5830:                  "in $courseid");
 5831:         return 'already_set';
 5832:     } else {
 5833:         my $start = time;
 5834: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5835:                           $udom,$uname);
 5836:         if ($putres eq 'ok') {
 5837:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5838:                  $udom,$uname); 
 5839:             &appenv(
 5840:                      {
 5841:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5842:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5843:                      }
 5844:                   );
 5845:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5846:                 $cachedtimes{"$courseid\0$res"} = $start;
 5847:             }
 5848:         } elsif ($putres ne 'refused') {
 5849:             &logthis("Result: $putres when attempting to set first access time ".
 5850:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5851:         }
 5852:         return $putres;
 5853:     }
 5854:     return 'already_set';
 5855: }
 5856: }
 5857: 
 5858: # --------------------------------------------- Set Expire Date for Spreadsheet
 5859: 
 5860: sub expirespread {
 5861:     my ($uname,$udom,$stype,$usymb)=@_;
 5862:     my $cid=$env{'request.course.id'}; 
 5863:     if ($cid) {
 5864:        my $now=time;
 5865:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5866:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5867:                             $env{'course.'.$cid.'.num'}.
 5868: 	        	    ':nohist_expirationdates:'.
 5869:                             &escape($key).'='.$now,
 5870:                             $env{'course.'.$cid.'.home'})
 5871:     }
 5872:     return 'ok';
 5873: }
 5874: 
 5875: # ----------------------------------------------------- Devalidate Spreadsheets
 5876: 
 5877: sub devalidate {
 5878:     my ($symb,$uname,$udom)=@_;
 5879:     my $cid=$env{'request.course.id'}; 
 5880:     if ($cid) {
 5881:         # delete the stored spreadsheets for
 5882:         # - the student level sheet of this user in course's homespace
 5883:         # - the assessment level sheet for this resource 
 5884:         #   for this user in user's homespace
 5885: 	# - current conditional state info
 5886: 	my $key=$uname.':'.$udom.':';
 5887:         my $status=
 5888: 	    &del('nohist_calculatedsheets',
 5889: 		 [$key.'studentcalc:'],
 5890: 		 $env{'course.'.$cid.'.domain'},
 5891: 		 $env{'course.'.$cid.'.num'})
 5892: 		.' '.
 5893: 	    &del('nohist_calculatedsheets_'.$cid,
 5894: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5895:         unless ($status eq 'ok ok') {
 5896:            &logthis('Could not devalidate spreadsheet '.
 5897:                     $uname.' at '.$udom.' for '.
 5898: 		    $symb.': '.$status);
 5899:         }
 5900: 	&delenv('user.state.'.$cid);
 5901:     }
 5902: }
 5903: 
 5904: sub get_scalar {
 5905:     my ($string,$end) = @_;
 5906:     my $value;
 5907:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5908: 	$value = $1;
 5909:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5910: 	$value = $1;
 5911:     }
 5912:     return &unescape($value);
 5913: }
 5914: 
 5915: sub array2str {
 5916:   my (@array) = @_;
 5917:   my $result=&arrayref2str(\@array);
 5918:   $result=~s/^__ARRAY_REF__//;
 5919:   $result=~s/__END_ARRAY_REF__$//;
 5920:   return $result;
 5921: }
 5922: 
 5923: sub arrayref2str {
 5924:   my ($arrayref) = @_;
 5925:   my $result='__ARRAY_REF__';
 5926:   foreach my $elem (@$arrayref) {
 5927:     if(ref($elem) eq 'ARRAY') {
 5928:       $result.=&arrayref2str($elem).'&';
 5929:     } elsif(ref($elem) eq 'HASH') {
 5930:       $result.=&hashref2str($elem).'&';
 5931:     } elsif(ref($elem)) {
 5932:       #print("Got a ref of ".(ref($elem))." skipping.");
 5933:     } else {
 5934:       $result.=&escape($elem).'&';
 5935:     }
 5936:   }
 5937:   $result=~s/\&$//;
 5938:   $result .= '__END_ARRAY_REF__';
 5939:   return $result;
 5940: }
 5941: 
 5942: sub hash2str {
 5943:   my (%hash) = @_;
 5944:   my $result=&hashref2str(\%hash);
 5945:   $result=~s/^__HASH_REF__//;
 5946:   $result=~s/__END_HASH_REF__$//;
 5947:   return $result;
 5948: }
 5949: 
 5950: sub hashref2str {
 5951:   my ($hashref)=@_;
 5952:   my $result='__HASH_REF__';
 5953:   foreach my $key (sort(keys(%$hashref))) {
 5954:     if (ref($key) eq 'ARRAY') {
 5955:       $result.=&arrayref2str($key).'=';
 5956:     } elsif (ref($key) eq 'HASH') {
 5957:       $result.=&hashref2str($key).'=';
 5958:     } elsif (ref($key)) {
 5959:       $result.='=';
 5960:       #print("Got a ref of ".(ref($key))." skipping.");
 5961:     } else {
 5962: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5963:     }
 5964: 
 5965:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5966:       $result.=&arrayref2str($hashref->{$key}).'&';
 5967:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5968:       $result.=&hashref2str($hashref->{$key}).'&';
 5969:     } elsif(ref($hashref->{$key})) {
 5970:        $result.='&';
 5971:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5972:     } else {
 5973:       $result.=&escape($hashref->{$key}).'&';
 5974:     }
 5975:   }
 5976:   $result=~s/\&$//;
 5977:   $result .= '__END_HASH_REF__';
 5978:   return $result;
 5979: }
 5980: 
 5981: sub str2hash {
 5982:     my ($string)=@_;
 5983:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5984:     return %$hash;
 5985: }
 5986: 
 5987: sub str2hashref {
 5988:   my ($string) = @_;
 5989: 
 5990:   my %hash;
 5991: 
 5992:   if($string !~ /^__HASH_REF__/) {
 5993:       if (! ($string eq '' || !defined($string))) {
 5994: 	  $hash{'error'}='Not hash reference';
 5995:       }
 5996:       return (\%hash, $string);
 5997:   }
 5998: 
 5999:   $string =~ s/^__HASH_REF__//;
 6000: 
 6001:   while($string !~ /^__END_HASH_REF__/) {
 6002:       #key
 6003:       my $key='';
 6004:       if($string =~ /^__HASH_REF__/) {
 6005:           ($key, $string)=&str2hashref($string);
 6006:           if(defined($key->{'error'})) {
 6007:               $hash{'error'}='Bad data';
 6008:               return (\%hash, $string);
 6009:           }
 6010:       } elsif($string =~ /^__ARRAY_REF__/) {
 6011:           ($key, $string)=&str2arrayref($string);
 6012:           if($key->[0] eq 'Array reference error') {
 6013:               $hash{'error'}='Bad data';
 6014:               return (\%hash, $string);
 6015:           }
 6016:       } else {
 6017:           $string =~ s/^(.*?)=//;
 6018: 	  $key=&unescape($1);
 6019:       }
 6020:       $string =~ s/^=//;
 6021: 
 6022:       #value
 6023:       my $value='';
 6024:       if($string =~ /^__HASH_REF__/) {
 6025:           ($value, $string)=&str2hashref($string);
 6026:           if(defined($value->{'error'})) {
 6027:               $hash{'error'}='Bad data';
 6028:               return (\%hash, $string);
 6029:           }
 6030:       } elsif($string =~ /^__ARRAY_REF__/) {
 6031:           ($value, $string)=&str2arrayref($string);
 6032:           if($value->[0] eq 'Array reference error') {
 6033:               $hash{'error'}='Bad data';
 6034:               return (\%hash, $string);
 6035:           }
 6036:       } else {
 6037: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6038:       }
 6039:       $string =~ s/^&//;
 6040: 
 6041:       $hash{$key}=$value;
 6042:   }
 6043: 
 6044:   $string =~ s/^__END_HASH_REF__//;
 6045: 
 6046:   return (\%hash, $string);
 6047: }
 6048: 
 6049: sub str2array {
 6050:     my ($string)=@_;
 6051:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6052:     return @$array;
 6053: }
 6054: 
 6055: sub str2arrayref {
 6056:   my ($string) = @_;
 6057:   my @array;
 6058: 
 6059:   if($string !~ /^__ARRAY_REF__/) {
 6060:       if (! ($string eq '' || !defined($string))) {
 6061: 	  $array[0]='Array reference error';
 6062:       }
 6063:       return (\@array, $string);
 6064:   }
 6065: 
 6066:   $string =~ s/^__ARRAY_REF__//;
 6067: 
 6068:   while($string !~ /^__END_ARRAY_REF__/) {
 6069:       my $value='';
 6070:       if($string =~ /^__HASH_REF__/) {
 6071:           ($value, $string)=&str2hashref($string);
 6072:           if(defined($value->{'error'})) {
 6073:               $array[0] ='Array reference error';
 6074:               return (\@array, $string);
 6075:           }
 6076:       } elsif($string =~ /^__ARRAY_REF__/) {
 6077:           ($value, $string)=&str2arrayref($string);
 6078:           if($value->[0] eq 'Array reference error') {
 6079:               $array[0] ='Array reference error';
 6080:               return (\@array, $string);
 6081:           }
 6082:       } else {
 6083: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6084:       }
 6085:       $string =~ s/^&//;
 6086: 
 6087:       push(@array, $value);
 6088:   }
 6089: 
 6090:   $string =~ s/^__END_ARRAY_REF__//;
 6091: 
 6092:   return (\@array, $string);
 6093: }
 6094: 
 6095: # -------------------------------------------------------------------Temp Store
 6096: 
 6097: sub tmpreset {
 6098:   my ($symb,$namespace,$domain,$stuname) = @_;
 6099:   if (!$symb) {
 6100:     $symb=&symbread();
 6101:     if (!$symb) { $symb= $env{'request.url'}; }
 6102:   }
 6103:   $symb=escape($symb);
 6104: 
 6105:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6106:   $namespace=~s/\//\_/g;
 6107:   $namespace=~s/\W//g;
 6108: 
 6109:   if (!$domain) { $domain=$env{'user.domain'}; }
 6110:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6111:   if ($domain eq 'public' && $stuname eq 'public') {
 6112:       $stuname=&get_requestor_ip();
 6113:   }
 6114:   my $path=LONCAPA::tempdir();
 6115:   my %hash;
 6116:   if (tie(%hash,'GDBM_File',
 6117: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6118: 	  &GDBM_WRCREAT(),0640)) {
 6119:     foreach my $key (keys(%hash)) {
 6120:       if ($key=~ /:$symb/) {
 6121: 	delete($hash{$key});
 6122:       }
 6123:     }
 6124:   }
 6125: }
 6126: 
 6127: sub tmpstore {
 6128:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6129: 
 6130:   if (!$symb) {
 6131:     $symb=&symbread();
 6132:     if (!$symb) { $symb= $env{'request.url'}; }
 6133:   }
 6134:   $symb=escape($symb);
 6135: 
 6136:   if (!$namespace) {
 6137:     # I don't think we would ever want to store this for a course.
 6138:     # it seems this will only be used if we don't have a course.
 6139:     #$namespace=$env{'request.course.id'};
 6140:     #if (!$namespace) {
 6141:       $namespace=$env{'request.state'};
 6142:     #}
 6143:   }
 6144:   $namespace=~s/\//\_/g;
 6145:   $namespace=~s/\W//g;
 6146:   if (!$domain) { $domain=$env{'user.domain'}; }
 6147:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6148:   if ($domain eq 'public' && $stuname eq 'public') {
 6149:       $stuname=&get_requestor_ip();
 6150:   }
 6151:   my $now=time;
 6152:   my %hash;
 6153:   my $path=LONCAPA::tempdir();
 6154:   if (tie(%hash,'GDBM_File',
 6155: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6156: 	  &GDBM_WRCREAT(),0640)) {
 6157:     $hash{"version:$symb"}++;
 6158:     my $version=$hash{"version:$symb"};
 6159:     my $allkeys=''; 
 6160:     foreach my $key (keys(%$storehash)) {
 6161:       $allkeys.=$key.':';
 6162:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6163:     }
 6164:     $hash{"$version:$symb:timestamp"}=$now;
 6165:     $allkeys.='timestamp';
 6166:     $hash{"$version:keys:$symb"}=$allkeys;
 6167:     if (untie(%hash)) {
 6168:       return 'ok';
 6169:     } else {
 6170:       return "error:$!";
 6171:     }
 6172:   } else {
 6173:     return "error:$!";
 6174:   }
 6175: }
 6176: 
 6177: # -----------------------------------------------------------------Temp Restore
 6178: 
 6179: sub tmprestore {
 6180:   my ($symb,$namespace,$domain,$stuname) = @_;
 6181: 
 6182:   if (!$symb) {
 6183:     $symb=&symbread();
 6184:     if (!$symb) { $symb= $env{'request.url'}; }
 6185:   }
 6186:   $symb=escape($symb);
 6187: 
 6188:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6189: 
 6190:   if (!$domain) { $domain=$env{'user.domain'}; }
 6191:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6192:   if ($domain eq 'public' && $stuname eq 'public') {
 6193:       $stuname=&get_requestor_ip();
 6194:   }
 6195:   my %returnhash;
 6196:   $namespace=~s/\//\_/g;
 6197:   $namespace=~s/\W//g;
 6198:   my %hash;
 6199:   my $path=LONCAPA::tempdir();
 6200:   if (tie(%hash,'GDBM_File',
 6201: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6202: 	  &GDBM_READER(),0640)) {
 6203:     my $version=$hash{"version:$symb"};
 6204:     $returnhash{'version'}=$version;
 6205:     my $scope;
 6206:     for ($scope=1;$scope<=$version;$scope++) {
 6207:       my $vkeys=$hash{"$scope:keys:$symb"};
 6208:       my @keys=split(/:/,$vkeys);
 6209:       my $key;
 6210:       $returnhash{"$scope:keys"}=$vkeys;
 6211:       foreach $key (@keys) {
 6212: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6213: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6214:       }
 6215:     }
 6216:     if (!(untie(%hash))) {
 6217:       return "error:$!";
 6218:     }
 6219:   } else {
 6220:     return "error:$!";
 6221:   }
 6222:   return %returnhash;
 6223: }
 6224: 
 6225: # ----------------------------------------------------------------------- Store
 6226: 
 6227: sub store {
 6228:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6229:     my $home='';
 6230: 
 6231:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6232: 
 6233:     $symb=&symbclean($symb);
 6234:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6235: 
 6236:     if (!$domain) { $domain=$env{'user.domain'}; }
 6237:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6238: 
 6239:     &devalidate($symb,$stuname,$domain);
 6240: 
 6241:     $symb=escape($symb);
 6242:     if (!$namespace) { 
 6243:        unless ($namespace=$env{'request.course.id'}) { 
 6244:           return ''; 
 6245:        } 
 6246:     }
 6247:     if (!$home) { $home=$env{'user.home'}; }
 6248: 
 6249:     $$storehash{'ip'}=&get_requestor_ip();
 6250:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6251: 
 6252:     my $namevalue='';
 6253:     foreach my $key (keys(%$storehash)) {
 6254:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6255:     }
 6256:     $namevalue=~s/\&$//;
 6257:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6258:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6259: }
 6260: 
 6261: # -------------------------------------------------------------- Critical Store
 6262: 
 6263: sub cstore {
 6264:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6265:     my $home='';
 6266: 
 6267:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6268: 
 6269:     $symb=&symbclean($symb);
 6270:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6271: 
 6272:     if (!$domain) { $domain=$env{'user.domain'}; }
 6273:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6274: 
 6275:     &devalidate($symb,$stuname,$domain);
 6276: 
 6277:     $symb=escape($symb);
 6278:     if (!$namespace) { 
 6279:        unless ($namespace=$env{'request.course.id'}) { 
 6280:           return ''; 
 6281:        } 
 6282:     }
 6283:     if (!$home) { $home=$env{'user.home'}; }
 6284: 
 6285:     $$storehash{'ip'}=&get_requestor_ip();
 6286:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6287: 
 6288:     my $namevalue='';
 6289:     foreach my $key (keys(%$storehash)) {
 6290:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6291:     }
 6292:     $namevalue=~s/\&$//;
 6293:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6294:     return critical
 6295:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6296: }
 6297: 
 6298: # --------------------------------------------------------------------- Restore
 6299: 
 6300: sub restore {
 6301:     my ($symb,$namespace,$domain,$stuname) = @_;
 6302:     my $home='';
 6303: 
 6304:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6305: 
 6306:     if (!$symb) {
 6307:         return if ($namespace eq 'courserequests');
 6308:         unless ($symb=escape(&symbread())) { return ''; }
 6309:     } else {
 6310:         unless ($namespace eq 'courserequests') {
 6311:             $symb=&escape(&symbclean($symb));
 6312:         }
 6313:     }
 6314:     if (!$namespace) { 
 6315:        unless ($namespace=$env{'request.course.id'}) { 
 6316:           return ''; 
 6317:        } 
 6318:     }
 6319:     if (!$domain) { $domain=$env{'user.domain'}; }
 6320:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6321:     if (!$home) { $home=$env{'user.home'}; }
 6322:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6323: 
 6324:     my %returnhash=();
 6325:     foreach my $line (split(/\&/,$answer)) {
 6326: 	my ($name,$value)=split(/\=/,$line);
 6327:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6328:     }
 6329:     my $version;
 6330:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6331:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6332:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6333:        }
 6334:     }
 6335:     return %returnhash;
 6336: }
 6337: 
 6338: # ---------------------------------------------------------- Course Description
 6339: #
 6340: #  
 6341: 
 6342: sub coursedescription {
 6343:     my ($courseid,$args)=@_;
 6344:     $courseid=~s/^\///;
 6345:     $courseid=~s/\_/\//g;
 6346:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6347:     my $chome=&homeserver($cnum,$cdomain);
 6348:     my $normalid=$cdomain.'_'.$cnum;
 6349:     # need to always cache even if we get errors otherwise we keep 
 6350:     # trying and trying and trying to get the course description.
 6351:     my %envhash=();
 6352:     my %returnhash=();
 6353:     
 6354:     my $expiretime=600;
 6355:     if ($env{'request.course.id'} eq $normalid) {
 6356: 	$expiretime=120;
 6357:     }
 6358: 
 6359:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6360:     if (!$args->{'freshen_cache'}
 6361: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6362: 	foreach my $key (keys(%env)) {
 6363: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6364: 	    my ($setting) = $1;
 6365: 	    $returnhash{$setting} = $env{$key};
 6366: 	}
 6367: 	return %returnhash;
 6368:     }
 6369: 
 6370:     # get the data again
 6371: 
 6372:     if (!$args->{'one_time'}) {
 6373: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6374:     }
 6375: 
 6376:     if ($chome ne 'no_host') {
 6377:        %returnhash=&dump('environment',$cdomain,$cnum);
 6378:        if (!exists($returnhash{'con_lost'})) {
 6379: 	   my $username = $env{'user.name'}; # Defult username
 6380: 	   if(defined $args->{'user'}) {
 6381: 	       $username = $args->{'user'};
 6382: 	   }
 6383:            $returnhash{'home'}= $chome;
 6384: 	   $returnhash{'domain'} = $cdomain;
 6385: 	   $returnhash{'num'} = $cnum;
 6386:            if (!defined($returnhash{'type'})) {
 6387:                $returnhash{'type'} = 'Course';
 6388:            }
 6389:            while (my ($name,$value) = each %returnhash) {
 6390:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6391:            }
 6392:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6393:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6394: 	       $username.'_'.$cdomain.'_'.$cnum;
 6395:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6396:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6397:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6398:        }
 6399:     }
 6400:     if (!$args->{'one_time'}) {
 6401: 	&appenv(\%envhash);
 6402:     }
 6403:     return %returnhash;
 6404: }
 6405: 
 6406: sub update_released_required {
 6407:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6408:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6409:         $cid = $env{'request.course.id'};
 6410:         $cdom = $env{'course.'.$cid.'.domain'};
 6411:         $cnum = $env{'course.'.$cid.'.num'};
 6412:         $chome = $env{'course.'.$cid.'.home'};
 6413:     }
 6414:     if ($needsrelease) {
 6415:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6416:         my $needsupdate;
 6417:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6418:             $needsupdate = 1;
 6419:         } else {
 6420:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6421:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6422:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6423:                 $needsupdate = 1;
 6424:             }
 6425:         }
 6426:         if ($needsupdate) {
 6427:             my %needshash = (
 6428:                              'internal.releaserequired' => $needsrelease,
 6429:                             );
 6430:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6431:             if ($putresult eq 'ok') {
 6432:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6433:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6434:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6435:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6436:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6437:                 }
 6438:             }
 6439:         }
 6440:     }
 6441:     return;
 6442: }
 6443: 
 6444: # -------------------------------------------------See if a user is privileged
 6445: 
 6446: sub privileged {
 6447:     my ($username,$domain,$possdomains,$possroles)=@_;
 6448:     my $now = time;
 6449:     my $roles;
 6450:     if (ref($possroles) eq 'ARRAY') {
 6451:         $roles = $possroles; 
 6452:     } else {
 6453:         $roles = ['dc','su'];
 6454:     }
 6455:     if (ref($possdomains) eq 'ARRAY') {
 6456:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6457:         foreach my $dom (@{$possdomains}) {
 6458:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6459:                 (ref($privileged{$dom}) eq 'HASH')) {
 6460:                 foreach my $role (@{$roles}) {
 6461:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6462:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6463:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6464:                             return 1 unless (($end && $end < $now) ||
 6465:                                              ($start && $start > $now));
 6466:                         }
 6467:                     }
 6468:                 }
 6469:             }
 6470:         }
 6471:     } else {
 6472:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6473:         my $now = time;
 6474: 
 6475:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6476:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6477:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6478:                 return 1 unless ($tend && $tend < $now) 
 6479:                         or ($tstart && $tstart > $now);
 6480:             }
 6481:         }
 6482:     }
 6483:     return 0;
 6484: }
 6485: 
 6486: sub privileged_by_domain {
 6487:     my ($domains,$roles) = @_;
 6488:     my %privileged = ();
 6489:     my $cachetime = 60*60*24;
 6490:     my $now = time;
 6491:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6492:         return %privileged;
 6493:     }
 6494:     foreach my $dom (@{$domains}) {
 6495:         next if (ref($privileged{$dom}) eq 'HASH');
 6496:         my $needroles;
 6497:         foreach my $role (@{$roles}) {
 6498:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6499:             if (defined($cached)) {
 6500:                 if (ref($result) eq 'HASH') {
 6501:                     $privileged{$dom}{$role} = $result;
 6502:                 }
 6503:             } else {
 6504:                 $needroles = 1;
 6505:             }
 6506:         }
 6507:         if ($needroles) {
 6508:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6509:             $privileged{$dom} = {};
 6510:             foreach my $server (keys(%dompersonnel)) {
 6511:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6512:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6513:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6514:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6515:                         next if ($end && $end < $now);
 6516:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6517:                             $dompersonnel{$server}{$item};
 6518:                     }
 6519:                 }
 6520:             }
 6521:             if (ref($privileged{$dom}) eq 'HASH') {
 6522:                 foreach my $role (@{$roles}) {
 6523:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6524:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6525:                     } else {
 6526:                         my %hash = ();
 6527:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6528:                     }
 6529:                 }
 6530:             }
 6531:         }
 6532:     }
 6533:     return %privileged;
 6534: }
 6535: 
 6536: # -------------------------------------------------------- Get user privileges
 6537: 
 6538: sub rolesinit {
 6539:     my ($domain, $username) = @_;
 6540:     my %userroles = ('user.login.time' => time);
 6541:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6542: 
 6543:     # firstaccess and timerinterval are related to timed maps/resources. 
 6544:     # also, blocking can be triggered by an activating timer
 6545:     # it's saved in the user's %env.
 6546:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6547:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6548:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6549:         %timerintchk, %timerintenv);
 6550: 
 6551:     foreach my $key (keys(%firstaccess)) {
 6552:         my ($cid, $rest) = split(/\0/, $key);
 6553:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6554:     }
 6555: 
 6556:     foreach my $key (keys(%timerinterval)) {
 6557:         my ($cid,$rest) = split(/\0/,$key);
 6558:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6559:     }
 6560: 
 6561:     my %allroles=();
 6562:     my %allgroups=();
 6563: 
 6564:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6565:         my $role = $rolesdump{$area};
 6566:         $area =~ s/\_\w\w$//;
 6567: 
 6568:         my ($trole, $tend, $tstart, $group_privs);
 6569: 
 6570:         if ($role =~ /^cr/) {
 6571:         # Custom role, defined by a user 
 6572:         # e.g., user.role.cr/msu/smith/mynewrole
 6573:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6574:                 $trole = $1;
 6575:                 ($tend, $tstart) = split('_', $2);
 6576:             } else {
 6577:                 $trole = $role;
 6578:             }
 6579:         } elsif ($role =~ m|^gr/|) {
 6580:         # Role of member in a group, defined within a course/community
 6581:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6582:             ($trole, $tend, $tstart) = split(/_/, $role);
 6583:             next if $tstart eq '-1';
 6584:             ($trole, $group_privs) = split(/\//, $trole);
 6585:             $group_privs = &unescape($group_privs);
 6586:         } else {
 6587:         # Just a normal role, defined in roles.tab
 6588:             ($trole, $tend, $tstart) = split(/_/,$role);
 6589:         }
 6590: 
 6591:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6592:                  $username);
 6593:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6594: 
 6595:         # role expired or not available yet?
 6596:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6597:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6598: 
 6599:         next if $area eq '' or $trole eq '';
 6600: 
 6601:         my $spec = "$trole.$area";
 6602:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6603: 
 6604:         if ($trole =~ /^cr\//) {
 6605:         # Custom role, defined by a user
 6606:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6607:         } elsif ($trole eq 'gr') {
 6608:         # Role of a member in a group, defined within a course/community
 6609:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6610:             next;
 6611:         } else {
 6612:         # Normal role, defined in roles.tab
 6613:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6614:         }
 6615: 
 6616:         my $cid = $tdomain.'_'.$trest;
 6617:         unless ($firstaccchk{$cid}) {
 6618:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6619:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6620:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6621:                         $coursetimerstarts{$cid}{$item}; 
 6622:                 }
 6623:             }
 6624:             $firstaccchk{$cid} = 1;
 6625:         }
 6626:         unless ($timerintchk{$cid}) {
 6627:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6628:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6629:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6630:                        $coursetimerintervals{$cid}{$item};
 6631:                 }
 6632:             }
 6633:             $timerintchk{$cid} = 1;
 6634:         }
 6635:     }
 6636: 
 6637:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6638:                                                           \%allroles, \%allgroups);
 6639:     $env{'user.adv'} = $userroles{'user.adv'};
 6640:     $env{'user.rar'} = $userroles{'user.rar'};
 6641: 
 6642:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6643: }
 6644: 
 6645: sub set_arearole {
 6646:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6647:     unless ($nolog) {
 6648: # log the associated role with the area
 6649:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6650:     }
 6651:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6652: }
 6653: 
 6654: sub custom_roleprivs {
 6655:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6656:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6657:     my $homsvr = &homeserver($rauthor,$rdomain);
 6658:     if (&hostname($homsvr) ne '') {
 6659:         my ($rdummy,$roledef)=
 6660:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6661:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6662:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6663:             if (defined($syspriv)) {
 6664:                 if ($trest =~ /^$match_community$/) {
 6665:                     $syspriv =~ s/bre\&S//; 
 6666:                 }
 6667:                 $$allroles{'cm./'}.=':'.$syspriv;
 6668:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6669:             }
 6670:             if ($tdomain ne '') {
 6671:                 if (defined($dompriv)) {
 6672:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6673:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6674:                 }
 6675:                 if (($trest ne '') && (defined($coursepriv))) {
 6676:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6677:                         my $rolename = $1;
 6678:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6679:                     }
 6680:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6681:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6682:                 }
 6683:             }
 6684:         }
 6685:     }
 6686: }
 6687: 
 6688: sub course_adhocrole_privs {
 6689:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6690:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6691:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6692:         my (%currprivs,%storeprivs);
 6693:         foreach my $item (split(/:/,$coursepriv)) {
 6694:             my ($priv,$restrict) = split(/\&/,$item);
 6695:             $currprivs{$priv} = $restrict;
 6696:         }
 6697:         my (%possadd,%possremove,%full);
 6698:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6699:             my ($priv,$restrict)=split(/\&/,$item);
 6700:             $full{$priv} = $restrict;
 6701:         }
 6702:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6703:              next if ($item eq '');
 6704:              my ($rule,$rest) = split(/=/,$item);
 6705:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6706:              foreach my $priv (split(/:/,$rest)) {
 6707:                  if ($priv ne '') {
 6708:                      if ($rule eq 'off') {
 6709:                          $possremove{$priv} = 1;
 6710:                      } else {
 6711:                          $possadd{$priv} = 1;
 6712:                      }
 6713:                  }
 6714:              }
 6715:          }
 6716:          foreach my $priv (sort(keys(%full))) {
 6717:              if (exists($currprivs{$priv})) {
 6718:                  unless (exists($possremove{$priv})) {
 6719:                      $storeprivs{$priv} = $currprivs{$priv};
 6720:                  }
 6721:              } elsif (exists($possadd{$priv})) {
 6722:                  $storeprivs{$priv} = $full{$priv};
 6723:              }
 6724:          }
 6725:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6726:      }
 6727:      return $coursepriv;
 6728: }
 6729: 
 6730: sub group_roleprivs {
 6731:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6732:     my $access = 1;
 6733:     my $now = time;
 6734:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6735:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6736:     if ($access) {
 6737:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6738:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6739:     }
 6740: }
 6741: 
 6742: sub standard_roleprivs {
 6743:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6744:     if (defined($pr{$trole.':s'})) {
 6745:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6746:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6747:     }
 6748:     if ($tdomain ne '') {
 6749:         if (defined($pr{$trole.':d'})) {
 6750:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6751:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6752:         }
 6753:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6754:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6755:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6756:         }
 6757:     }
 6758: }
 6759: 
 6760: sub set_userprivs {
 6761:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6762:     my $author=0;
 6763:     my $adv=0;
 6764:     my $rar=0;
 6765:     my %grouproles = ();
 6766:     if (keys(%{$allgroups}) > 0) {
 6767:         my @groupkeys; 
 6768:         foreach my $role (keys(%{$allroles})) {
 6769:             push(@groupkeys,$role);
 6770:         }
 6771:         if (ref($groups_roles) eq 'HASH') {
 6772:             foreach my $key (keys(%{$groups_roles})) {
 6773:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6774:                     push(@groupkeys,$key);
 6775:                 }
 6776:             }
 6777:         }
 6778:         if (@groupkeys > 0) {
 6779:             foreach my $role (@groupkeys) {
 6780:                 my ($trole,$area,$sec,$extendedarea);
 6781:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6782:                     $trole = $1;
 6783:                     $area = $2;
 6784:                     $sec = $3;
 6785:                     $extendedarea = $area.$sec;
 6786:                     if (exists($$allgroups{$area})) {
 6787:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6788:                             my $spec = $trole.'.'.$extendedarea;
 6789:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6790:                                                 $$allgroups{$area}{$group};
 6791:                         }
 6792:                     }
 6793:                 }
 6794:             }
 6795:         }
 6796:     }
 6797:     foreach my $group (keys(%grouproles)) {
 6798:         $$allroles{$group} = $grouproles{$group};
 6799:     }
 6800:     foreach my $role (keys(%{$allroles})) {
 6801:         my %thesepriv;
 6802:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6803:         foreach my $item (split(/:/,$$allroles{$role})) {
 6804:             if ($item ne '') {
 6805:                 my ($privilege,$restrictions)=split(/&/,$item);
 6806:                 if ($restrictions eq '') {
 6807:                     $thesepriv{$privilege}='F';
 6808:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6809:                     $thesepriv{$privilege}.=$restrictions;
 6810:                 }
 6811:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6812:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6813:             }
 6814:         }
 6815:         my $thesestr='';
 6816:         foreach my $priv (sort(keys(%thesepriv))) {
 6817: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6818: 	}
 6819:         $userroles->{'user.priv.'.$role} = $thesestr;
 6820:     }
 6821:     return ($author,$adv,$rar);
 6822: }
 6823: 
 6824: sub role_status {
 6825:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6826:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6827:         my ($one,$two) = split(m{\./},$rolekey,2);
 6828:         (undef,undef,$$role) = split(/\./,$one,3);
 6829:         unless (!defined($$role) || $$role eq '') {
 6830:             $$where = '/'.$two;
 6831:             $$trolecode=$$role.'.'.$$where;
 6832:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6833:             $$tstatus='is';
 6834:             if ($$tstart && $$tstart>$update) {
 6835:                 $$tstatus='future';
 6836:                 if ($$tstart<$now) {
 6837:                     if ($$tstart && $$tstart>$refresh) {
 6838:                         if (($$where ne '') && ($$role ne '')) {
 6839:                             my (%allroles,%allgroups,$group_privs,
 6840:                                 %groups_roles,@rolecodes);
 6841:                             my %userroles = (
 6842:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6843:                             );
 6844:                             @rolecodes = ('cm'); 
 6845:                             my $spec=$$role.'.'.$$where;
 6846:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6847:                             if ($$role =~ /^cr\//) {
 6848:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6849:                                 push(@rolecodes,'cr');
 6850:                             } elsif ($$role eq 'gr') {
 6851:                                 push(@rolecodes,$$role);
 6852:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6853:                                                     $env{'user.name'});
 6854:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6855:                                 (undef,my $group_privs) = split(/\//,$trole);
 6856:                                 $group_privs = &unescape($group_privs);
 6857:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6858:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6859:                                 &get_groups_roles($tdomain,$trest,
 6860:                                                   \%course_roles,\@rolecodes,
 6861:                                                   \%groups_roles);
 6862:                             } else {
 6863:                                 push(@rolecodes,$$role);
 6864:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6865:                             }
 6866:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6867:                                                                    \%groups_roles);
 6868:                             &appenv(\%userroles,\@rolecodes);
 6869:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6870:                         }
 6871:                     }
 6872:                     $$tstatus = 'is';
 6873:                 }
 6874:             }
 6875:             if ($$tend) {
 6876:                 if ($$tend<$update) {
 6877:                     $$tstatus='expired';
 6878:                 } elsif ($$tend<$now) {
 6879:                     $$tstatus='will_not';
 6880:                 }
 6881:             }
 6882:         }
 6883:     }
 6884: }
 6885: 
 6886: sub get_groups_roles {
 6887:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6888:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6889:                   (ref($rolecodes) eq 'ARRAY') && 
 6890:                   (ref($groups_roles) eq 'HASH')); 
 6891:     if (keys(%{$cdom_courseroles}) > 0) {
 6892:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6893:         if ($cdom ne '' && $cnum ne '') {
 6894:             foreach my $key (keys(%{$cdom_courseroles})) {
 6895:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6896:                     my $crsrole = $1;
 6897:                     my $crssec = $2;
 6898:                     if ($crsrole =~ /^cr/) {
 6899:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6900:                             push(@{$rolecodes},'cr');
 6901:                         }
 6902:                     } else {
 6903:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6904:                             push(@{$rolecodes},$crsrole);
 6905:                         }
 6906:                     }
 6907:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6908:                     if ($crssec ne '') {
 6909:                         $rolekey .= "/$crssec";
 6910:                     }
 6911:                     $rolekey .= './';
 6912:                     $groups_roles->{$rolekey} = $rolecodes;
 6913:                 }
 6914:             }
 6915:         }
 6916:     }
 6917:     return;
 6918: }
 6919: 
 6920: sub delete_env_groupprivs {
 6921:     my ($where,$courseroles,$possroles) = @_;
 6922:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6923:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6924:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6925:         %{$courseroles->{$udom}} =
 6926:             &get_my_roles('','','userroles',['active'],
 6927:                           $possroles,[$udom],1);
 6928:     }
 6929:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6930:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6931:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6932:             my $area = '/'.$cdom.'/'.$cnum;
 6933:             my $privkey = "user.priv.$crsrole.$area";
 6934:             if ($crssec ne '') {
 6935:                 $privkey .= '/'.$crssec;
 6936:             }
 6937:             $privkey .= ".$area/$group";
 6938:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6939:         }
 6940:     }
 6941:     return;
 6942: }
 6943: 
 6944: sub check_adhoc_privs {
 6945:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6946:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6947:     if ($sec) {
 6948:         $cckey .= '/'.$sec;
 6949:     } 
 6950:     my $setprivs;
 6951:     if ($env{$cckey}) {
 6952:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6953:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6954:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6955:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6956:             $setprivs = 1;
 6957:         }
 6958:     } else {
 6959:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6960:         $setprivs = 1;
 6961:     }
 6962:     return $setprivs;
 6963: }
 6964: 
 6965: sub set_adhoc_privileges {
 6966: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6967:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6968:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6969:     if ($sec ne '') {
 6970:         $area .= '/'.$sec;
 6971:     }
 6972:     my $spec = $role.'.'.$area;
 6973:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6974:                                   $env{'user.name'},1);
 6975:     my %rolehash = ();
 6976:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6977:         my $rolename = $1;
 6978:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6979:         my %domdef = &get_domain_defaults($dcdom);
 6980:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6981:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6982:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6983:             }
 6984:         }
 6985:     } else {
 6986:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6987:     }
 6988:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6989:     &appenv(\%userroles,[$role,'cm']);
 6990:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6991:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 6992:             ($caller eq 'tiny')) {
 6993:         &appenv( {'request.role'        => $spec,
 6994:                   'request.role.domain' => $dcdom,
 6995:                   'request.course.sec'  => $sec,
 6996:                  }
 6997:                );
 6998:         my $tadv=0;
 6999:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7000:         &appenv({'request.role.adv'    => $tadv});
 7001:     }
 7002: }
 7003: 
 7004: # --------------------------------------------------------------- get interface
 7005: 
 7006: sub get {
 7007:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7008:    my $items='';
 7009:    foreach my $item (@$storearr) {
 7010:        $items.=&escape($item).'&';
 7011:    }
 7012:    $items=~s/\&$//;
 7013:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7014:    if (!$uname) { $uname=$env{'user.name'}; }
 7015:    my $uhome=&homeserver($uname,$udomain);
 7016: 
 7017:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7018:    my @pairs=split(/\&/,$rep);
 7019:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7020:      return @pairs;
 7021:    }
 7022:    my %returnhash=();
 7023:    my $i=0;
 7024:    foreach my $item (@$storearr) {
 7025:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7026:       $i++;
 7027:    }
 7028:    return %returnhash;
 7029: }
 7030: 
 7031: # --------------------------------------------------------------- del interface
 7032: 
 7033: sub del {
 7034:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7035:    my $items='';
 7036:    foreach my $item (@$storearr) {
 7037:        $items.=&escape($item).'&';
 7038:    }
 7039: 
 7040:    $items=~s/\&$//;
 7041:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7042:    if (!$uname) { $uname=$env{'user.name'}; }
 7043:    my $uhome=&homeserver($uname,$udomain);
 7044:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7045: }
 7046: 
 7047: # -------------------------------------------------------------- dump interface
 7048: 
 7049: sub unserialize {
 7050:     my ($rep, $escapedkeys) = @_;
 7051: 
 7052:     return {} if $rep =~ /^error/;
 7053: 
 7054:     my %returnhash=();
 7055: 	foreach my $item (split(/\&/,$rep)) {
 7056: 	    my ($key, $value) = split(/=/, $item, 2);
 7057: 	    $key = unescape($key) unless $escapedkeys;
 7058: 	    next if $key =~ /^error: 2 /;
 7059: 	    $returnhash{$key} = &thaw_unescape($value);
 7060: 	}
 7061:     #return %returnhash;
 7062:     return \%returnhash;
 7063: }        
 7064: 
 7065: # see Lond::dump_with_regexp
 7066: # if $escapedkeys hash keys won't get unescaped.
 7067: sub dump {
 7068:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 7069:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7070:     if (!$uname) { $uname=$env{'user.name'}; }
 7071:     my $uhome=&homeserver($uname,$udomain);
 7072: 
 7073:     if ($regexp) {
 7074:         $regexp=&escape($regexp);
 7075:     } else {
 7076:         $regexp='.';
 7077:     }
 7078:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7079:         # user is hosted on this machine
 7080:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7081:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7082:         return %{unserialize($reply, $escapedkeys)};
 7083:     }
 7084:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7085:     my @pairs=split(/\&/,$rep);
 7086:     my %returnhash=();
 7087:     if (!($rep =~ /^error/ )) {
 7088: 	foreach my $item (@pairs) {
 7089: 	    my ($key,$value)=split(/=/,$item,2);
 7090:         $key = unescape($key) unless $escapedkeys;
 7091:         #$key = &unescape($key);
 7092: 	    next if ($key =~ /^error: 2 /);
 7093: 	    $returnhash{$key}=&thaw_unescape($value);
 7094: 	}
 7095:     }
 7096:     return %returnhash;
 7097: }
 7098: 
 7099: 
 7100: # --------------------------------------------------------- dumpstore interface
 7101: 
 7102: sub dumpstore {
 7103:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7104:    # same as dump but keys must be escaped. They may contain colon separated
 7105:    # lists of values that may themself contain colons (e.g. symbs).
 7106:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7107: }
 7108: 
 7109: # -------------------------------------------------------------- keys interface
 7110: 
 7111: sub getkeys {
 7112:    my ($namespace,$udomain,$uname)=@_;
 7113:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7114:    if (!$uname) { $uname=$env{'user.name'}; }
 7115:    my $uhome=&homeserver($uname,$udomain);
 7116:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7117:    my @keyarray=();
 7118:    foreach my $key (split(/\&/,$rep)) {
 7119:       next if ($key =~ /^error: 2 /);
 7120:       push(@keyarray,&unescape($key));
 7121:    }
 7122:    return @keyarray;
 7123: }
 7124: 
 7125: # --------------------------------------------------------------- currentdump
 7126: sub currentdump {
 7127:    my ($courseid,$sdom,$sname)=@_;
 7128:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7129:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7130:    $sname    = $env{'user.name'}         if (! defined($sname));
 7131:    my $uhome = &homeserver($sname,$sdom);
 7132:    my $rep;
 7133: 
 7134:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7135:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7136:                    $courseid)));
 7137:    } else {
 7138:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7139:    }
 7140: 
 7141:    return if ($rep =~ /^(error:|no_such_host)/);
 7142:    #
 7143:    my %returnhash=();
 7144:    #
 7145:    if ($rep eq 'unknown_cmd') {
 7146:        # an old lond will not know currentdump
 7147:        # Do a dump and make it look like a currentdump
 7148:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7149:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7150:        my %hash = @tmp;
 7151:        @tmp=();
 7152:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7153:    } else {
 7154:        my @pairs=split(/\&/,$rep);
 7155:        foreach my $pair (@pairs) {
 7156:            my ($key,$value)=split(/=/,$pair,2);
 7157:            my ($symb,$param) = split(/:/,$key);
 7158:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7159:                                                         &thaw_unescape($value);
 7160:        }
 7161:    }
 7162:    return %returnhash;
 7163: }
 7164: 
 7165: sub convert_dump_to_currentdump{
 7166:     my %hash = %{shift()};
 7167:     my %returnhash;
 7168:     # Code ripped from lond, essentially.  The only difference
 7169:     # here is the unescaping done by lonnet::dump().  Conceivably
 7170:     # we might run in to problems with parameter names =~ /^v\./
 7171:     while (my ($key,$value) = each(%hash)) {
 7172:         my ($v,$symb,$param) = split(/:/,$key);
 7173: 	$symb  = &unescape($symb);
 7174: 	$param = &unescape($param);
 7175:         next if ($v eq 'version' || $symb eq 'keys');
 7176:         next if (exists($returnhash{$symb}) &&
 7177:                  exists($returnhash{$symb}->{$param}) &&
 7178:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7179:         $returnhash{$symb}->{$param}=$value;
 7180:         $returnhash{$symb}->{'v.'.$param}=$v;
 7181:     }
 7182:     #
 7183:     # Remove all of the keys in the hashes which keep track of
 7184:     # the version of the parameter.
 7185:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7186:         # use a foreach because we are going to delete from the hash.
 7187:         foreach my $key (keys(%$param_hash)) {
 7188:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7189:         }
 7190:     }
 7191:     return \%returnhash;
 7192: }
 7193: 
 7194: # ------------------------------------------------------ critical inc interface
 7195: 
 7196: sub cinc {
 7197:     return &inc(@_,'critical');
 7198: }
 7199: 
 7200: # --------------------------------------------------------------- inc interface
 7201: 
 7202: sub inc {
 7203:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7204:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7205:     if (!$uname) { $uname=$env{'user.name'}; }
 7206:     my $uhome=&homeserver($uname,$udomain);
 7207:     my $items='';
 7208:     if (! ref($store)) {
 7209:         # got a single value, so use that instead
 7210:         $items = &escape($store).'=&';
 7211:     } elsif (ref($store) eq 'SCALAR') {
 7212:         $items = &escape($$store).'=&';        
 7213:     } elsif (ref($store) eq 'ARRAY') {
 7214:         $items = join('=&',map {&escape($_);} @{$store});
 7215:     } elsif (ref($store) eq 'HASH') {
 7216:         while (my($key,$value) = each(%{$store})) {
 7217:             $items.= &escape($key).'='.&escape($value).'&';
 7218:         }
 7219:     }
 7220:     $items=~s/\&$//;
 7221:     if ($critical) {
 7222: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7223:     } else {
 7224: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7225:     }
 7226: }
 7227: 
 7228: # --------------------------------------------------------------- put interface
 7229: 
 7230: sub put {
 7231:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7232:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7233:    if (!$uname) { $uname=$env{'user.name'}; }
 7234:    my $uhome=&homeserver($uname,$udomain);
 7235:    my $items='';
 7236:    foreach my $item (keys(%$storehash)) {
 7237:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7238:    }
 7239:    $items=~s/\&$//;
 7240:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7241: }
 7242: 
 7243: # ------------------------------------------------------------ newput interface
 7244: 
 7245: sub newput {
 7246:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7247:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7248:    if (!$uname) { $uname=$env{'user.name'}; }
 7249:    my $uhome=&homeserver($uname,$udomain);
 7250:    my $items='';
 7251:    foreach my $key (keys(%$storehash)) {
 7252:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7253:    }
 7254:    $items=~s/\&$//;
 7255:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7256: }
 7257: 
 7258: # ---------------------------------------------------------  putstore interface
 7259: 
 7260: sub putstore {
 7261:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7262:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7263:    if (!$uname) { $uname=$env{'user.name'}; }
 7264:    my $uhome=&homeserver($uname,$udomain);
 7265:    my $items='';
 7266:    foreach my $key (keys(%$storehash)) {
 7267:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7268:    }
 7269:    $items=~s/\&$//;
 7270:    my $esc_symb=&escape($symb);
 7271:    my $esc_v=&escape($version);
 7272:    my $reply =
 7273:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7274: 	      $uhome);
 7275:    if (($tolog) && ($reply eq 'ok')) {
 7276:        my $namevalue='';
 7277:        foreach my $key (keys(%{$storehash})) {
 7278:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7279:        }
 7280:        my $ip = &get_requestor_ip();
 7281:        $namevalue .= 'ip='.&escape($ip).
 7282:                      '&host='.&escape($perlvar{'lonHostID'}).
 7283:                      '&version='.$esc_v.
 7284:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7285:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7286:    }
 7287:    if ($reply eq 'unknown_cmd') {
 7288:        # gfall back to way things use to be done
 7289:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7290: 			    $uname);
 7291:    }
 7292:    return $reply;
 7293: }
 7294: 
 7295: sub old_putstore {
 7296:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7297:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7298:     if (!$uname) { $uname=$env{'user.name'}; }
 7299:     my $uhome=&homeserver($uname,$udomain);
 7300:     my %newstorehash;
 7301:     foreach my $item (keys(%$storehash)) {
 7302: 	my $key = $version.':'.&escape($symb).':'.$item;
 7303: 	$newstorehash{$key} = $storehash->{$item};
 7304:     }
 7305:     my $items='';
 7306:     my %allitems = ();
 7307:     foreach my $item (keys(%newstorehash)) {
 7308: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7309: 	    my $key = $1.':keys:'.$2;
 7310: 	    $allitems{$key} .= $3.':';
 7311: 	}
 7312: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7313:     }
 7314:     foreach my $item (keys(%allitems)) {
 7315: 	$allitems{$item} =~ s/\:$//;
 7316: 	$items.= $item.'='.$allitems{$item}.'&';
 7317:     }
 7318:     $items=~s/\&$//;
 7319:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7320: }
 7321: 
 7322: # ------------------------------------------------------ critical put interface
 7323: 
 7324: sub cput {
 7325:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7326:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7327:    if (!$uname) { $uname=$env{'user.name'}; }
 7328:    my $uhome=&homeserver($uname,$udomain);
 7329:    my $items='';
 7330:    foreach my $item (keys(%$storehash)) {
 7331:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7332:    }
 7333:    $items=~s/\&$//;
 7334:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7335: }
 7336: 
 7337: # -------------------------------------------------------------- eget interface
 7338: 
 7339: sub eget {
 7340:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7341:    my $items='';
 7342:    foreach my $item (@$storearr) {
 7343:        $items.=&escape($item).'&';
 7344:    }
 7345:    $items=~s/\&$//;
 7346:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7347:    if (!$uname) { $uname=$env{'user.name'}; }
 7348:    my $uhome=&homeserver($uname,$udomain);
 7349:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7350:    my @pairs=split(/\&/,$rep);
 7351:    my %returnhash=();
 7352:    my $i=0;
 7353:    foreach my $item (@$storearr) {
 7354:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7355:       $i++;
 7356:    }
 7357:    return %returnhash;
 7358: }
 7359: 
 7360: # ------------------------------------------------------------ tmpput interface
 7361: sub tmpput {
 7362:     my ($storehash,$server,$context)=@_;
 7363:     my $items='';
 7364:     foreach my $item (keys(%$storehash)) {
 7365: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7366:     }
 7367:     $items=~s/\&$//;
 7368:     if (defined($context)) {
 7369:         $items .= ':'.&escape($context);
 7370:     }
 7371:     return &reply("tmpput:$items",$server);
 7372: }
 7373: 
 7374: # ------------------------------------------------------------ tmpget interface
 7375: sub tmpget {
 7376:     my ($token,$server)=@_;
 7377:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7378:     my $rep=&reply("tmpget:$token",$server);
 7379:     my %returnhash;
 7380:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7381:         return %returnhash;
 7382:     }
 7383:     foreach my $item (split(/\&/,$rep)) {
 7384: 	my ($key,$value)=split(/=/,$item);
 7385: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7386:     }
 7387:     return %returnhash;
 7388: }
 7389: 
 7390: # ------------------------------------------------------------ tmpdel interface
 7391: sub tmpdel {
 7392:     my ($token,$server)=@_;
 7393:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7394:     return &reply("tmpdel:$token",$server);
 7395: }
 7396: 
 7397: # ------------------------------------------------------------ get_timebased_id 
 7398: 
 7399: sub get_timebased_id {
 7400:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7401:         $maxtries) = @_;
 7402:     my ($newid,$error,$dellock);
 7403:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7404:         return ('','ok','invalid call to get suffix');
 7405:     }
 7406: 
 7407: # set defaults for any optional args for which values were not supplied
 7408:     if ($who eq '') {
 7409:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7410:     }
 7411:     if (!$locktries) {
 7412:         $locktries = 3;
 7413:     }
 7414:     if (!$maxtries) {
 7415:         $maxtries = 10;
 7416:     }
 7417:     
 7418:     if (($cdom eq '') || ($cnum eq '')) {
 7419:         if ($env{'request.course.id'}) {
 7420:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7421:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7422:         }
 7423:         if (($cdom eq '') || ($cnum eq '')) {
 7424:             return ('','ok','call to get suffix not in course context');
 7425:         }
 7426:     }
 7427: 
 7428: # construct locking item
 7429:     my $lockhash = {
 7430:                       $prefix."\0".'locked_'.$keyid => $who,
 7431:                    };
 7432:     my $tries = 0;
 7433: 
 7434: # attempt to get lock on nohist_$namespace file
 7435:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7436:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7437:         $tries ++;
 7438:         sleep 1;
 7439:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7440:     }
 7441: 
 7442: # attempt to get unique identifier, based on current timestamp
 7443:     if ($gotlock eq 'ok') {
 7444:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7445:         my $id = time;
 7446:         $newid = $id;
 7447:         if ($idtype eq 'addcode') {
 7448:             $newid .= &sixnum_code();
 7449:         }
 7450:         my $idtries = 0;
 7451:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7452:             if ($idtype eq 'concat') {
 7453:                 $newid = $id.$idtries;
 7454:             } elsif ($idtype eq 'addcode') {
 7455:                 $newid = $newid.&sixnum_code();
 7456:             } else {
 7457:                 $newid ++;
 7458:             }
 7459:             $idtries ++;
 7460:         }
 7461:         if (!exists($inuse{$prefix."\0".$newid})) {
 7462:             my %new_item =  (
 7463:                               $prefix."\0".$newid => $who,
 7464:                             );
 7465:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7466:                                                  $cdom,$cnum);
 7467:             if ($putresult ne 'ok') {
 7468:                 undef($newid);
 7469:                 $error = 'error saving new item: '.$putresult;
 7470:             }
 7471:         } else {
 7472:              undef($newid);
 7473:              $error = ('error: no unique suffix available for the new item ');
 7474:         }
 7475: #  remove lock
 7476:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7477:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7478:     } else {
 7479:         $error = "error: could not obtain lockfile\n";
 7480:         $dellock = 'ok';
 7481:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7482:             $dellock = 'nolock';
 7483:         }
 7484:     }
 7485:     return ($newid,$dellock,$error);
 7486: }
 7487: 
 7488: sub sixnum_code {
 7489:     my $code;
 7490:     for (0..6) {
 7491:         $code .= int( rand(9) );
 7492:     }
 7493:     return $code;
 7494: }
 7495: 
 7496: # -------------------------------------------------- portfolio access checking
 7497: 
 7498: sub portfolio_access {
 7499:     my ($requrl,$clientip) = @_;
 7500:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7501:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7502:     if ($result) {
 7503:         my %setters;
 7504:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7505:             my ($startblock,$endblock) =
 7506:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7507:             if ($startblock && $endblock) {
 7508:                 return 'B';
 7509:             }
 7510:         } else {
 7511:             my ($startblock,$endblock) =
 7512:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7513:             if ($startblock && $endblock) {
 7514:                 return 'B';
 7515:             }
 7516:         }
 7517:     }
 7518:     if ($result eq 'ok') {
 7519:        return 'F';
 7520:     } elsif ($result =~ /^[^:]+:guest_/) {
 7521:        return 'A';
 7522:     }
 7523:     return '';
 7524: }
 7525: 
 7526: sub get_portfolio_access {
 7527:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7528: 
 7529:     if (!ref($access_hash)) {
 7530: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7531: 	my %access_controls = &get_access_controls($current_perms,$group,
 7532: 						   $file_name);
 7533: 	$access_hash = $access_controls{$file_name};
 7534:     }
 7535: 
 7536:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7537:     my $now = time;
 7538:     if (ref($access_hash) eq 'HASH') {
 7539:         foreach my $key (keys(%{$access_hash})) {
 7540:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7541:             if ($start > $now) {
 7542:                 next;
 7543:             }
 7544:             if ($end && $end<$now) {
 7545:                 next;
 7546:             }
 7547:             if ($scope eq 'public') {
 7548:                 $public = $key;
 7549:                 last;
 7550:             } elsif ($scope eq 'guest') {
 7551:                 $guest = $key;
 7552:             } elsif ($scope eq 'domains') {
 7553:                 push(@domains,$key);
 7554:             } elsif ($scope eq 'users') {
 7555:                 push(@users,$key);
 7556:             } elsif ($scope eq 'course') {
 7557:                 push(@courses,$key);
 7558:             } elsif ($scope eq 'group') {
 7559:                 push(@groups,$key);
 7560:             } elsif ($scope eq 'ip') {
 7561:                 push(@ips,$key);
 7562:             }
 7563:         }
 7564:         if ($public) {
 7565:             return 'ok';
 7566:         } elsif (@ips > 0) {
 7567:             my $allowed;
 7568:             foreach my $ipkey (@ips) {
 7569:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7570:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7571:                         $allowed = 1;
 7572:                         last; 
 7573:                     }
 7574:                 }
 7575:             }
 7576:             if ($allowed) {
 7577:                 return 'ok';
 7578:             }
 7579:         }
 7580:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7581:             if ($guest) {
 7582:                 return $guest;
 7583:             }
 7584:         } else {
 7585:             if (@domains > 0) {
 7586:                 foreach my $domkey (@domains) {
 7587:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7588:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7589:                             return 'ok';
 7590:                         }
 7591:                     }
 7592:                 }
 7593:             }
 7594:             if (@users > 0) {
 7595:                 foreach my $userkey (@users) {
 7596:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7597:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7598:                             if (ref($item) eq 'HASH') {
 7599:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7600:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7601:                                     return 'ok';
 7602:                                 }
 7603:                             }
 7604:                         }
 7605:                     } 
 7606:                 }
 7607:             }
 7608:             my %roleshash;
 7609:             my @courses_and_groups = @courses;
 7610:             push(@courses_and_groups,@groups); 
 7611:             if (@courses_and_groups > 0) {
 7612:                 my (%allgroups,%allroles); 
 7613:                 my ($start,$end,$role,$sec,$group);
 7614:                 foreach my $envkey (%env) {
 7615:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7616:                         my $cid = $2.'_'.$3; 
 7617:                         if ($1 eq 'gr') {
 7618:                             $group = $4;
 7619:                             $allgroups{$cid}{$group} = $env{$envkey};
 7620:                         } else {
 7621:                             if ($4 eq '') {
 7622:                                 $sec = 'none';
 7623:                             } else {
 7624:                                 $sec = $4;
 7625:                             }
 7626:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7627:                         }
 7628:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7629:                         my $cid = $2.'_'.$3;
 7630:                         if ($4 eq '') {
 7631:                             $sec = 'none';
 7632:                         } else {
 7633:                             $sec = $4;
 7634:                         }
 7635:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7636:                     }
 7637:                 }
 7638:                 if (keys(%allroles) == 0) {
 7639:                     return;
 7640:                 }
 7641:                 foreach my $key (@courses_and_groups) {
 7642:                     my %content = %{$$access_hash{$key}};
 7643:                     my $cnum = $content{'number'};
 7644:                     my $cdom = $content{'domain'};
 7645:                     my $cid = $cdom.'_'.$cnum;
 7646:                     if (!exists($allroles{$cid})) {
 7647:                         next;
 7648:                     }    
 7649:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7650:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7651:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7652:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7653:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7654:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7655:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7656:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7657:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7658:                                         if (grep/^all$/,@sections) {
 7659:                                             return 'ok';
 7660:                                         } else {
 7661:                                             if (grep/^$sec$/,@sections) {
 7662:                                                 return 'ok';
 7663:                                             }
 7664:                                         }
 7665:                                     }
 7666:                                 }
 7667:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7668:                                     if (grep/^none$/,@groups) {
 7669:                                         return 'ok';
 7670:                                     }
 7671:                                 } else {
 7672:                                     if (grep/^all$/,@groups) {
 7673:                                         return 'ok';
 7674:                                     } 
 7675:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7676:                                         if (grep/^$group$/,@groups) {
 7677:                                             return 'ok';
 7678:                                         }
 7679:                                     }
 7680:                                 } 
 7681:                             }
 7682:                         }
 7683:                     }
 7684:                 }
 7685:             }
 7686:             if ($guest) {
 7687:                 return $guest;
 7688:             }
 7689:         }
 7690:     }
 7691:     return;
 7692: }
 7693: 
 7694: sub course_group_datechecker {
 7695:     my ($dates,$now,$status) = @_;
 7696:     my ($start,$end) = split(/\./,$dates);
 7697:     if (!$start && !$end) {
 7698:         return 'ok';
 7699:     }
 7700:     if (grep/^active$/,@{$status}) {
 7701:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7702:             return 'ok';
 7703:         }
 7704:     }
 7705:     if (grep/^previous$/,@{$status}) {
 7706:         if ($end > $now ) {
 7707:             return 'ok';
 7708:         }
 7709:     }
 7710:     if (grep/^future$/,@{$status}) {
 7711:         if ($start > $now) {
 7712:             return 'ok';
 7713:         }
 7714:     }
 7715:     return; 
 7716: }
 7717: 
 7718: sub parse_portfolio_url {
 7719:     my ($url) = @_;
 7720: 
 7721:     my ($type,$udom,$unum,$group,$file_name);
 7722:     
 7723:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7724: 	$type = 1;
 7725:         $udom = $1;
 7726:         $unum = $2;
 7727:         $file_name = $3;
 7728:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7729: 	$type = 2;
 7730:         $udom = $1;
 7731:         $unum = $2;
 7732:         $group = $3;
 7733:         $file_name = $3.'/'.$4;
 7734:     }
 7735:     if (wantarray) {
 7736: 	return ($type,$udom,$unum,$file_name,$group);
 7737:     }
 7738:     return $type;
 7739: }
 7740: 
 7741: sub is_portfolio_url {
 7742:     my ($url) = @_;
 7743:     return scalar(&parse_portfolio_url($url));
 7744: }
 7745: 
 7746: sub is_portfolio_file {
 7747:     my ($file) = @_;
 7748:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7749:         return 1;
 7750:     }
 7751:     return;
 7752: }
 7753: 
 7754: sub usertools_access {
 7755:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7756:     my ($access,%tools);
 7757:     if ($context eq '') {
 7758:         $context = 'tools';
 7759:     }
 7760:     if ($context eq 'requestcourses') {
 7761:         %tools = (
 7762:                       official   => 1,
 7763:                       unofficial => 1,
 7764:                       community  => 1,
 7765:                       textbook   => 1,
 7766:                       placement  => 1,
 7767:                       lti        => 1,
 7768:                  );
 7769:     } elsif ($context eq 'requestauthor') {
 7770:         %tools = (
 7771:                       requestauthor => 1,
 7772:                  );
 7773:     } else {
 7774:         %tools = (
 7775:                       aboutme   => 1,
 7776:                       blog      => 1,
 7777:                       webdav    => 1,
 7778:                       portfolio => 1,
 7779:                  );
 7780:     }
 7781:     return if (!defined($tools{$tool}));
 7782: 
 7783:     if (($udom eq '') || ($uname eq '')) {
 7784:         $udom = $env{'user.domain'};
 7785:         $uname = $env{'user.name'};
 7786:     }
 7787: 
 7788:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7789:         if ($action ne 'reload') {
 7790:             if ($context eq 'requestcourses') {
 7791:                 return $env{'environment.canrequest.'.$tool};
 7792:             } elsif ($context eq 'requestauthor') {
 7793:                 return $env{'environment.canrequest.author'};
 7794:             } else {
 7795:                 return $env{'environment.availabletools.'.$tool};
 7796:             }
 7797:         }
 7798:     }
 7799: 
 7800:     my ($toolstatus,$inststatus,$envkey);
 7801:     if ($context eq 'requestauthor') {
 7802:         $envkey = $context; 
 7803:     } else {
 7804:         $envkey = $context.'.'.$tool;
 7805:     }
 7806: 
 7807:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7808:          ($action ne 'reload')) {
 7809:         $toolstatus = $env{'environment.'.$envkey};
 7810:         $inststatus = $env{'environment.inststatus'};
 7811:     } else {
 7812:         if (ref($userenvref) eq 'HASH') {
 7813:             $toolstatus = $userenvref->{$envkey};
 7814:             $inststatus = $userenvref->{'inststatus'};
 7815:         } else {
 7816:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7817:             $toolstatus = $userenv{$envkey};
 7818:             $inststatus = $userenv{'inststatus'};
 7819:         }
 7820:     }
 7821: 
 7822:     if ($toolstatus ne '') {
 7823:         if ($toolstatus) {
 7824:             $access = 1;
 7825:         } else {
 7826:             $access = 0;
 7827:         }
 7828:         return $access;
 7829:     }
 7830: 
 7831:     my ($is_adv,%domdef);
 7832:     if (ref($is_advref) eq 'HASH') {
 7833:         $is_adv = $is_advref->{'is_adv'};
 7834:     } else {
 7835:         $is_adv = &is_advanced_user($udom,$uname);
 7836:     }
 7837:     if (ref($domdefref) eq 'HASH') {
 7838:         %domdef = %{$domdefref};
 7839:     } else {
 7840:         %domdef = &get_domain_defaults($udom);
 7841:     }
 7842:     if (ref($domdef{$tool}) eq 'HASH') {
 7843:         if ($is_adv) {
 7844:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7845:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7846:                     $access = 1;
 7847:                 } else {
 7848:                     $access = 0;
 7849:                 }
 7850:                 return $access;
 7851:             }
 7852:         }
 7853:         if ($inststatus ne '') {
 7854:             my ($hasaccess,$hasnoaccess);
 7855:             foreach my $affiliation (split(/:/,$inststatus)) {
 7856:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7857:                     if ($domdef{$tool}{$affiliation}) {
 7858:                         $hasaccess = 1;
 7859:                     } else {
 7860:                         $hasnoaccess = 1;
 7861:                     }
 7862:                 }
 7863:             }
 7864:             if ($hasaccess || $hasnoaccess) {
 7865:                 if ($hasaccess) {
 7866:                     $access = 1;
 7867:                 } elsif ($hasnoaccess) {
 7868:                     $access = 0; 
 7869:                 }
 7870:                 return $access;
 7871:             }
 7872:         } else {
 7873:             if ($domdef{$tool}{'default'} ne '') {
 7874:                 if ($domdef{$tool}{'default'}) {
 7875:                     $access = 1;
 7876:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7877:                     $access = 0;
 7878:                 }
 7879:                 return $access;
 7880:             }
 7881:         }
 7882:     } else {
 7883:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7884:             $access = 1;
 7885:         } else {
 7886:             $access = 0;
 7887:         }
 7888:         return $access;
 7889:     }
 7890: }
 7891: 
 7892: sub is_course_owner {
 7893:     my ($cdom,$cnum,$udom,$uname) = @_;
 7894:     if (($udom eq '') || ($uname eq '')) {
 7895:         $udom = $env{'user.domain'};
 7896:         $uname = $env{'user.name'};
 7897:     }
 7898:     unless (($udom eq '') || ($uname eq '')) {
 7899:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7900:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7901:                 return 1;
 7902:             } else {
 7903:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7904:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7905:                     return 1;
 7906:                 }
 7907:             }
 7908:         }
 7909:     }
 7910:     return;
 7911: }
 7912: 
 7913: sub is_advanced_user {
 7914:     my ($udom,$uname) = @_;
 7915:     if ($udom ne '' && $uname ne '') {
 7916:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7917:             if (wantarray) {
 7918:                 return ($env{'user.adv'},$env{'user.author'});
 7919:             } else {
 7920:                 return $env{'user.adv'};
 7921:             }
 7922:         }
 7923:     }
 7924:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7925:     my %allroles;
 7926:     my ($is_adv,$is_author);
 7927:     foreach my $role (keys(%roleshash)) {
 7928:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7929:         my $area = '/'.$tdomain.'/'.$trest;
 7930:         if ($sec ne '') {
 7931:             $area .= '/'.$sec;
 7932:         }
 7933:         if (($area ne '') && ($trole ne '')) {
 7934:             my $spec=$trole.'.'.$area;
 7935:             if ($trole =~ /^cr\//) {
 7936:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7937:             } elsif ($trole ne 'gr') {
 7938:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7939:             }
 7940:             if ($trole eq 'au') {
 7941:                 $is_author = 1;
 7942:             }
 7943:         }
 7944:     }
 7945:     foreach my $role (keys(%allroles)) {
 7946:         last if ($is_adv);
 7947:         foreach my $item (split(/:/,$allroles{$role})) {
 7948:             if ($item ne '') {
 7949:                 my ($privilege,$restrictions)=split(/&/,$item);
 7950:                 if ($privilege eq 'adv') {
 7951:                     $is_adv = 1;
 7952:                     last;
 7953:                 }
 7954:             }
 7955:         }
 7956:     }
 7957:     if (wantarray) {
 7958:         return ($is_adv,$is_author);
 7959:     }
 7960:     return $is_adv;
 7961: }
 7962: 
 7963: sub check_can_request {
 7964:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7965:     my $canreq = 0;
 7966:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7967:         $uname = $env{'user.name'};
 7968:         $udom = $env{'user.domain'};
 7969:     }
 7970:     my ($types,$typename) = &Apache::loncommon::course_types();
 7971:     my @options = ('approval','validate','autolimit');
 7972:     my $optregex = join('|',@options);
 7973:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7974:         foreach my $type (@{$types}) {
 7975:             if (&usertools_access($uname,$udom,$type,undef,
 7976:                                   'requestcourses')) {
 7977:                 $canreq ++;
 7978:                 if (ref($request_domains) eq 'HASH') {
 7979:                     push(@{$request_domains->{$type}},$udom);
 7980:                 }
 7981:                 if ($dom eq $udom) {
 7982:                     $can_request->{$type} = 1;
 7983:                 }
 7984:             }
 7985:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7986:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7987:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7988:                 if (@curr > 0) {
 7989:                     foreach my $item (@curr) {
 7990:                         if (ref($request_domains) eq 'HASH') {
 7991:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7992:                             if ($otherdom ne '') {
 7993:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7994:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7995:                                         push(@{$request_domains->{$type}},$otherdom);
 7996:                                     }
 7997:                                 } else {
 7998:                                     push(@{$request_domains->{$type}},$otherdom);
 7999:                                 }
 8000:                             }
 8001:                         }
 8002:                     }
 8003:                     unless ($dom eq $env{'user.domain'}) {
 8004:                         $canreq ++;
 8005:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8006:                             $can_request->{$type} = 1;
 8007:                         }
 8008:                     }
 8009:                 }
 8010:             }
 8011:         }
 8012:     }
 8013:     return $canreq;
 8014: }
 8015: 
 8016: # ---------------------------------------------- Custom access rule evaluation
 8017: 
 8018: sub customaccess {
 8019:     my ($priv,$uri)=@_;
 8020:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8021:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8022:     $udom = &LONCAPA::clean_domain($udom);
 8023:     $ucrs = &LONCAPA::clean_username($ucrs);
 8024:     my $access=0;
 8025:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8026: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8027: 	if ($type eq 'user') {
 8028: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8029: 		my ($tdom,$tuname)=split(m{/},$scope);
 8030: 		if ($tdom) {
 8031: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8032: 		}
 8033: 		if ($tuname) {
 8034: 		    if ($tuname ne $env{'user.name'}) { next; }
 8035: 		}
 8036: 		$access=($effect eq 'allow');
 8037: 		last;
 8038: 	    }
 8039: 	} else {
 8040: 	    if ($role) {
 8041: 		if ($role ne $urole) { next; }
 8042: 	    }
 8043: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8044: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8045: 		if ($tdom) {
 8046: 		    if ($tdom ne $udom) { next; }
 8047: 		}
 8048: 		if ($tcrs) {
 8049: 		    if ($tcrs ne $ucrs) { next; }
 8050: 		}
 8051: 		if ($tsec) {
 8052: 		    if ($tsec ne $usec) { next; }
 8053: 		}
 8054: 		$access=($effect eq 'allow');
 8055: 		last;
 8056: 	    }
 8057: 	    if ($realm eq '' && $role eq '') {
 8058: 		$access=($effect eq 'allow');
 8059: 	    }
 8060: 	}
 8061:     }
 8062:     return $access;
 8063: }
 8064: 
 8065: # ------------------------------------------------- Check for a user privilege
 8066: 
 8067: sub allowed {
 8068:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
 8069:     my $ver_orguri=$uri;
 8070:     $uri=&deversion($uri);
 8071:     my $orguri=$uri;
 8072:     $uri=&declutter($uri);
 8073: 
 8074:     if ($priv eq 'evb') {
 8075: # Evade communication block restrictions for specified role in a course
 8076:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8077:             return $1;
 8078:         } else {
 8079:             return;
 8080:         }
 8081:     }
 8082: 
 8083:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8084: # Free bre access to adm and meta resources
 8085:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8086: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8087: 	&& ($priv eq 'bre')) {
 8088: 	return 'F';
 8089:     }
 8090: 
 8091: # Free bre access to user's own portfolio contents
 8092:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8093:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8094: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8095:         my %setters;
 8096:         my ($startblock,$endblock) = 
 8097:             &Apache::loncommon::blockcheck(\%setters,'port');
 8098:         if ($startblock && $endblock) {
 8099:             return 'B';
 8100:         } else {
 8101:             return 'F';
 8102:         }
 8103:     }
 8104: 
 8105: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8106:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8107:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8108:         if (exists($env{'request.course.id'})) {
 8109:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8110:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8111:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8112:                 my $courseprivid=$env{'request.course.id'};
 8113:                 $courseprivid=~s/\_/\//;
 8114:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8115:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8116:                     return $1; 
 8117:                 } else {
 8118:                     if ($env{'request.course.sec'}) {
 8119:                         $courseprivid.='/'.$env{'request.course.sec'};
 8120:                     }
 8121:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8122:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8123:                         return $2;
 8124:                     }
 8125:                 }
 8126:             }
 8127:         }
 8128:     }
 8129: 
 8130: # Free bre to public access
 8131: 
 8132:     if ($priv eq 'bre') {
 8133:         my $copyright;
 8134:         unless ($uri =~ /ext\.tool/) {
 8135:             $copyright=&metadata($uri,'copyright');
 8136:         }
 8137: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8138:            return 'F'; 
 8139:         }
 8140:         if ($copyright eq 'priv') {
 8141:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8142: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8143: 		return '';
 8144:             }
 8145:         }
 8146:         if ($copyright eq 'domain') {
 8147:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8148: 	    unless (($env{'user.domain'} eq $1) ||
 8149:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8150: 		return '';
 8151:             }
 8152:         }
 8153:         if ($env{'request.role'}=~ /li\.\//) {
 8154:             # Library role, so allow browsing of resources in this domain.
 8155:             return 'F';
 8156:         }
 8157:         if ($copyright eq 'custom') {
 8158: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8159:         }
 8160:     }
 8161:     # Domain coordinator is trying to create a course
 8162:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8163:         # uri is the requested domain in this case.
 8164:         # comparison to 'request.role.domain' shows if the user has selected
 8165:         # a role of dc for the domain in question.
 8166:         return 'F' if ($uri eq $env{'request.role.domain'});
 8167:     }
 8168: 
 8169:     my $thisallowed='';
 8170:     my $statecond=0;
 8171:     my $courseprivid='';
 8172: 
 8173:     my $ownaccess;
 8174:     # Community Coordinator or Assistant Co-author browsing resource space.
 8175:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8176:         if ($uri eq '') {
 8177:             $ownaccess = 1;
 8178:         } else {
 8179:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8180:                 my $udom = $env{'user.domain'};
 8181:                 my $uname = $env{'user.name'};
 8182:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8183:                     $ownaccess = 1;
 8184:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8185:                     unless ($uri =~ m{\.\./}) {
 8186:                         $ownaccess = 1;
 8187:                     }
 8188:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8189:                     my $now = time;
 8190:                     if ($uri =~ m{^([^/]+)/?$}) {
 8191:                         my $adom = $1;
 8192:                         foreach my $key (keys(%env)) {
 8193:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8194:                                 my ($start,$end) = split('.',$env{$key});
 8195:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8196:                                     $ownaccess = 1;
 8197:                                     last;
 8198:                                 }
 8199:                             }
 8200:                         }
 8201:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8202:                         my $adom = $1;
 8203:                         my $aname = $2;
 8204:                         foreach my $role ('ca','aa') { 
 8205:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8206:                                 my ($start,$end) =
 8207:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8208:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8209:                                     $ownaccess = 1;
 8210:                                     last;
 8211:                                 }
 8212:                             }
 8213:                         }
 8214:                     }
 8215:                 }
 8216:             }
 8217:         }
 8218:     }
 8219: 
 8220: # Course
 8221: 
 8222:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8223:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8224:             $thisallowed.=$1;
 8225:         }
 8226:     }
 8227: 
 8228: # Domain
 8229: 
 8230:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8231:        =~/\Q$priv\E\&([^\:]*)/) {
 8232:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8233:             $thisallowed.=$1;
 8234:         }
 8235:     }
 8236: 
 8237: # User who is not author or co-author might still be able to edit
 8238: # resource of an author in the domain (e.g., if Domain Coordinator).
 8239:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8240:         (&allowed('mdc',$env{'request.course.id'}))) {
 8241:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8242:             $thisallowed.=$1;
 8243:         }
 8244:     }
 8245: 
 8246: # Course: uri itself is a course
 8247:     my $courseuri=$uri;
 8248:     $courseuri=~s/\_(\d)/\/$1/;
 8249:     $courseuri=~s/^([^\/])/\/$1/;
 8250: 
 8251:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8252:        =~/\Q$priv\E\&([^\:]*)/) {
 8253:         if ($priv eq 'mip') {
 8254:             my $rem = $1;
 8255:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8256:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8257:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8258:                 if ($cdom ne '') {
 8259:                     my %passwdconf = &get_passwdconf($cdom);
 8260:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8261:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8262:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8263:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8264:                                 unless (@inststatuses) {
 8265:                                     @inststatuses = ('default');
 8266:                                 }
 8267:                                 foreach my $status (@inststatuses) {
 8268:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8269:                                         $thisallowed.=$rem;
 8270:                                     }
 8271:                                 }
 8272:                             }
 8273:                         }
 8274:                     }
 8275:                 }
 8276:             }
 8277:         } else {
 8278:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8279:                 $thisallowed.=$1;
 8280:             }
 8281:         }
 8282:     }
 8283: 
 8284: # URI is an uploaded document for this course, default permissions don't matter
 8285: # not allowing 'edit' access (editupload) to uploaded course docs
 8286:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8287: 	$thisallowed='';
 8288:         my ($match)=&is_on_map($uri);
 8289:         if ($match) {
 8290:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8291:                   =~/\Q$priv\E\&([^\:]*)/) {
 8292:                 my $value = $1;
 8293:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8294:                 if ($deeplinkblock) {
 8295:                     $thisallowed='D';
 8296:                 } elsif ($noblockcheck) {
 8297:                     $thisallowed.=$value;
 8298:                 } else {
 8299:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8300:                     if (@blockers > 0) {
 8301:                         $thisallowed = 'B';
 8302:                     } else {
 8303:                         $thisallowed.=$value;
 8304:                     }
 8305:                 }
 8306:             }
 8307:         } else {
 8308:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8309:             if ($refuri) {
 8310:                 if ($refuri =~ m|^/adm/|) {
 8311:                     $thisallowed='F';
 8312:                 } else {
 8313:                     $refuri=&declutter($refuri);
 8314:                     my ($match) = &is_on_map($refuri);
 8315:                     if ($match) {
 8316:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8317:                         if ($deeplinkblock) {
 8318:                             $thisallowed='D';
 8319:                         } elsif ($noblockcheck) {
 8320:                             $thisallowed='F';
 8321:                         } else {
 8322:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8323:                             if (@blockers > 0) {
 8324:                                 $thisallowed = 'B';
 8325:                             } else {
 8326:                                 $thisallowed='F';
 8327:                             }
 8328:                         }
 8329:                     }
 8330:                 }
 8331:             }
 8332:         }
 8333:     }
 8334: 
 8335:     if ($priv eq 'bre'
 8336: 	&& $thisallowed ne 'F' 
 8337: 	&& $thisallowed ne '2'
 8338: 	&& &is_portfolio_url($uri)) {
 8339: 	$thisallowed = &portfolio_access($uri,$clientip);
 8340:     }
 8341: 
 8342: # Full access at system, domain or course-wide level? Exit.
 8343:     if ($thisallowed=~/F/) {
 8344: 	return 'F';
 8345:     }
 8346: 
 8347: # If this is generating or modifying users, exit with special codes
 8348: 
 8349:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8350: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8351: 	    my ($audom,$auname)=split('/',$uri);
 8352: # no author name given, so this just checks on the general right to make a co-author in this domain
 8353: 	    unless ($auname) { return $thisallowed; }
 8354: # an author name is given, so we are about to actually make a co-author for a certain account
 8355: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8356: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8357: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8358: 	}
 8359: 	return $thisallowed;
 8360:     }
 8361: #
 8362: # Gathered so far: system, domain and course wide privileges
 8363: #
 8364: # Course: See if uri or referer is an individual resource that is part of 
 8365: # the course
 8366: 
 8367:     if ($env{'request.course.id'}) {
 8368: 
 8369: # If this is modifying password (internal auth) domains must match for user and user's role.
 8370: 
 8371:         if ($priv eq 'mip') {
 8372:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8373:                 return $thisallowed;
 8374:             } else {
 8375:                 return '';
 8376:             }
 8377:         }
 8378: 
 8379:        $courseprivid=$env{'request.course.id'};
 8380:        if ($env{'request.course.sec'}) {
 8381:           $courseprivid.='/'.$env{'request.course.sec'};
 8382:        }
 8383:        $courseprivid=~s/\_/\//;
 8384:        my $checkreferer=1;
 8385:        my ($match,$cond)=&is_on_map($uri);
 8386:        if ($match) {
 8387:            $statecond=$cond;
 8388:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8389:                =~/\Q$priv\E\&([^\:]*)/) {
 8390:                my $value = $1;
 8391:                if ($priv eq 'bre') {
 8392:                    if ($noblockcheck) {
 8393:                        $thisallowed.=$value;
 8394:                    } else {
 8395:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8396:                        if (@blockers > 0) {
 8397:                            $thisallowed = 'B';
 8398:                        } else {
 8399:                            $thisallowed.=$value;
 8400:                        }
 8401:                    }
 8402:                } else {
 8403:                    $thisallowed.=$value;
 8404:                }
 8405:                $checkreferer=0;
 8406:            }
 8407:        }
 8408: 
 8409:        if ($checkreferer) {
 8410: 	  my $refuri=$env{'httpref.'.$orguri};
 8411:             unless ($refuri) {
 8412:                 foreach my $key (keys(%env)) {
 8413: 		    if ($key=~/^httpref\..*\*/) {
 8414: 			my $pattern=$key;
 8415:                         $pattern=~s/^httpref\.\/res\///;
 8416:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8417:                         $pattern=~s/\//\\\//g;
 8418:                         if ($orguri=~/$pattern/) {
 8419: 			    $refuri=$env{$key};
 8420:                         }
 8421:                     }
 8422:                 }
 8423:             }
 8424: 
 8425:          if ($refuri) { 
 8426: 	  $refuri=&declutter($refuri);
 8427:           my ($match,$cond)=&is_on_map($refuri);
 8428:             if ($match) {
 8429:               my $refstatecond=$cond;
 8430:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8431:                   =~/\Q$priv\E\&([^\:]*)/) {
 8432:                   my $value = $1;
 8433:                   if ($priv eq 'bre') {
 8434:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8435:                       if ($deeplinkblock) {
 8436:                           $thisallowed = 'D';
 8437:                       } elsif ($noblockcheck) {
 8438:                           $thisallowed.=$value;
 8439:                       } else {
 8440:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8441:                           if (@blockers > 0) {
 8442:                               $thisallowed = 'B';
 8443:                           } else {
 8444:                               $thisallowed.=$value;
 8445:                           }
 8446:                       }
 8447:                   } else {
 8448:                       $thisallowed.=$value;
 8449:                   }
 8450:                   $uri=$refuri;
 8451:                   $statecond=$refstatecond;
 8452:               }
 8453:           }
 8454:         }
 8455:        }
 8456:    }
 8457: 
 8458: #
 8459: # Gathered now: all privileges that could apply, and condition number
 8460: # 
 8461: #
 8462: # Full or no access?
 8463: #
 8464: 
 8465:     if ($thisallowed=~/F/) {
 8466: 	return 'F';
 8467:     }
 8468: 
 8469:     unless ($thisallowed) {
 8470:         return '';
 8471:     }
 8472: 
 8473: # Restrictions exist, deal with them
 8474: #
 8475: #   C:according to course preferences
 8476: #   R:according to resource settings
 8477: #   L:unless locked
 8478: #   X:according to user session state
 8479: #
 8480: 
 8481: # Possibly locked functionality, check all courses
 8482: # Locks might take effect only after 10 minutes cache expiration for other
 8483: # courses, and 2 minutes for current course
 8484: 
 8485:     my $envkey;
 8486:     if ($thisallowed=~/L/) {
 8487:         foreach $envkey (keys(%env)) {
 8488:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8489:                my $courseid=$2;
 8490:                my $roleid=$1.'.'.$2;
 8491:                $courseid=~s/^\///;
 8492:                my $expiretime=600;
 8493:                if ($env{'request.role'} eq $roleid) {
 8494: 		  $expiretime=120;
 8495:                }
 8496: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8497:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8498:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8499: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8500:                }
 8501:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8502:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8503: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8504:                        &log($env{'user.domain'},$env{'user.name'},
 8505:                             $env{'user.home'},
 8506:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8507:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8508:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8509: 		       return '';
 8510:                    }
 8511:                }
 8512:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8513:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8514: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8515:                        &log($env{'user.domain'},$env{'user.name'},
 8516:                             $env{'user.home'},
 8517:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8518:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8519:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8520: 		       return '';
 8521:                    }
 8522:                }
 8523: 	   }
 8524:        }
 8525:     }
 8526: 
 8527: #
 8528: # Rest of the restrictions depend on selected course
 8529: #
 8530: 
 8531:     unless ($env{'request.course.id'}) {
 8532: 	if ($thisallowed eq 'A') {
 8533: 	    return 'A';
 8534:         } elsif ($thisallowed eq 'B') {
 8535:             return 'B';
 8536: 	} else {
 8537: 	    return '1';
 8538: 	}
 8539:     }
 8540: 
 8541: #
 8542: # Now user is definitely in a course
 8543: #
 8544: 
 8545: 
 8546: # Course preferences
 8547: 
 8548:    if ($thisallowed=~/C/) {
 8549:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8550:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8551:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8552: 	   =~/\Q$rolecode\E/) {
 8553: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8554: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8555: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8556: 			$env{'request.course.id'});
 8557: 	   }
 8558:            return '';
 8559:        }
 8560: 
 8561:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8562: 	   =~/\Q$unamedom\E/) {
 8563: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8564: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8565: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8566: 			$env{'request.course.id'});
 8567: 	   }
 8568:            return '';
 8569:        }
 8570:    }
 8571: 
 8572: # Resource preferences
 8573: 
 8574:    if ($thisallowed=~/R/) {
 8575:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8576:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8577: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8578: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8579: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8580: 	   }
 8581: 	   return '';
 8582:        }
 8583:    }
 8584: 
 8585: # Restricted by state or randomout?
 8586: 
 8587:    if ($thisallowed=~/X/) {
 8588:       if ($env{'acc.randomout'}) {
 8589: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8590:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8591:             return ''; 
 8592:          }
 8593:       }
 8594:       if (&condval($statecond)) {
 8595: 	 return '2';
 8596:       } else {
 8597:          return '';
 8598:       }
 8599:    }
 8600: 
 8601:     if ($thisallowed eq 'A') {
 8602: 	return 'A';
 8603:     } elsif ($thisallowed eq 'B') {
 8604:         return 'B';
 8605:     } elsif ($thisallowed eq 'D') {
 8606:         return 'D';
 8607:     }
 8608:    return 'F';
 8609: }
 8610: 
 8611: # ------------------------------------------- Check construction space access
 8612: 
 8613: sub constructaccess {
 8614:     my ($url,$setpriv)=@_;
 8615: 
 8616: # We do not allow editing of previous versions of files
 8617:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8618: 
 8619: # Get username and domain from URL
 8620:     my ($ownername,$ownerdomain,$ownerhome);
 8621: 
 8622:     ($ownerdomain,$ownername) =
 8623:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8624: 
 8625: # The URL does not really point to any authorspace, forget it
 8626:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8627: 
 8628: # Now we need to see if the user has access to the authorspace of
 8629: # $ownername at $ownerdomain
 8630: 
 8631:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8632: # Real author for this?
 8633:        $ownerhome = $env{'user.home'};
 8634:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8635:           return ($ownername,$ownerdomain,$ownerhome);
 8636:        }
 8637:     } else {
 8638: # Co-author for this?
 8639:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8640:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8641:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8642:             return ($ownername,$ownerdomain,$ownerhome);
 8643:         }
 8644:         if ($env{'request.course.id'}) {
 8645:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8646:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8647:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8648:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8649:                     return ($ownername,$ownerdomain,$ownerhome);
 8650:                 }
 8651:             }
 8652:         }
 8653:     }
 8654: 
 8655: # We don't have any access right now. If we are not possibly going to do anything about this,
 8656: # we might as well leave
 8657:    unless ($setpriv) { return ''; }
 8658: 
 8659: # Backdoor access?
 8660:     my $allowed=&allowed('eco',$ownerdomain);
 8661: # Nope
 8662:     unless ($allowed) { return ''; }
 8663: # Looks like we may have access, but could be locked by the owner of the construction space
 8664:     if ($allowed eq 'U') {
 8665:         my %blocked=&get('environment',['domcoord.author'],
 8666:                          $ownerdomain,$ownername);
 8667: # Is blocked by owner
 8668:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8669:     }
 8670:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8671: # Grant temporary access
 8672:         my $then=$env{'user.login.time'};
 8673:         my $update=$env{'user.update.time'};
 8674:         if (!$update) { $update = $then; }
 8675:         my $refresh=$env{'user.refresh.time'};
 8676:         if (!$refresh) { $refresh = $update; }
 8677:         my $now = time;
 8678:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8679:                            $now,'ca','constructaccess');
 8680:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8681:         return($ownername,$ownerdomain,$ownerhome);
 8682:     }
 8683: # No business here
 8684:     return '';
 8685: }
 8686: 
 8687: # ----------------------------------------------------------- Content Blocking
 8688: 
 8689: {
 8690: # Caches for faster Course Contents display where content blocking
 8691: # is in operation (i.e., interval param set) for timed quiz.
 8692: #
 8693: # User for whom data are being temporarily cached.
 8694: my $cacheduser='';
 8695: # Course for which data are being temporarily cached.
 8696: my $cachedcid='';
 8697: # Cached blockers for this user (a hash of blocking items). 
 8698: my %cachedblockers=();
 8699: # When the data were last cached.
 8700: my $cachedlast='';
 8701: 
 8702: sub load_all_blockers {
 8703:     my ($uname,$udom)=@_;
 8704:     if (($uname ne '') && ($udom ne '')) { 
 8705:         if (($cacheduser eq $uname.':'.$udom) &&
 8706:             ($cachedcid eq $env{'request.course.id'}) &&
 8707:             (abs($cachedlast-time)<5)) {
 8708:             return;
 8709:         }
 8710:     }
 8711:     $cachedlast=time;
 8712:     $cacheduser=$uname.':'.$udom;
 8713:     $cachedcid=$env{'request.course.id'};
 8714:     %cachedblockers = &get_commblock_resources();
 8715:     return;
 8716: }
 8717: 
 8718: sub get_comm_blocks {
 8719:     my ($cdom,$cnum) = @_;
 8720:     if ($cdom eq '' || $cnum eq '') {
 8721:         return unless ($env{'request.course.id'});
 8722:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8723:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8724:     }
 8725:     my %commblocks;
 8726:     my $hashid=$cdom.'_'.$cnum;
 8727:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8728:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8729:         %commblocks = %{$blocksref};
 8730:     } else {
 8731:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8732:         my $cachetime = 600;
 8733:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8734:     }
 8735:     return %commblocks;
 8736: }
 8737: 
 8738: sub get_commblock_resources {
 8739:     my ($blocks) = @_;
 8740:     my %blockers = ();
 8741:     return %blockers unless ($env{'request.course.id'});
 8742:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8743:     my %commblocks;
 8744:     if (ref($blocks) eq 'HASH') {
 8745:         %commblocks = %{$blocks};
 8746:     } else {
 8747:         %commblocks = &get_comm_blocks();
 8748:     }
 8749:     return %blockers unless (keys(%commblocks) > 0); 
 8750:     my $navmap = Apache::lonnavmaps::navmap->new();
 8751:     return %blockers unless (ref($navmap));
 8752:     my $now = time;
 8753:     foreach my $block (keys(%commblocks)) {
 8754:         if ($block =~ /^(\d+)____(\d+)$/) {
 8755:             my ($start,$end) = ($1,$2);
 8756:             if ($start <= $now && $end >= $now) {
 8757:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8758:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8759:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8760:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8761:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8762:                             }
 8763:                         }
 8764:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8765:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8766:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8767:                             }
 8768:                         }
 8769:                     }
 8770:                 }
 8771:             }
 8772:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8773:             my $item = $1;
 8774:             my @to_test;
 8775:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8776:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8777:                     my @interval;
 8778:                     my $type = 'map';
 8779:                     if ($item eq 'course') {
 8780:                         $type = 'course';
 8781:                         @interval=&EXT("resource.0.interval");
 8782:                     } else {
 8783:                         if ($item =~ /___\d+___/) {
 8784:                             $type = 'resource';
 8785:                             @interval=&EXT("resource.0.interval",$item);
 8786:                             if (ref($navmap)) {                        
 8787:                                 my $res = $navmap->getBySymb($item); 
 8788:                                 push(@to_test,$res);
 8789:                             }
 8790:                         } else {
 8791:                             my $mapsymb = &symbread($item,1);
 8792:                             if ($mapsymb) {
 8793:                                 if (ref($navmap)) {
 8794:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8795:                                     if (ref($mapres)) {
 8796:                                         my $first = $mapres->map_start();
 8797:                                         my $finish = $mapres->map_finish();
 8798:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
 8799:                                         if (ref($it)) {
 8800:                                             my $res;
 8801:                                             while ($res = $it->next(undef,1)) {
 8802:                                                 next unless (ref($res));
 8803:                                                 my $symb = $res->symb();
 8804:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
 8805:                                                 @interval=&EXT("resource.0.interval",$symb);
 8806:                                                 if ($interval[1] eq 'map') {
 8807:                                                     if ($res->answerable()) {
 8808:                                                         push(@to_test,$res);
 8809:                                                         last;
 8810:                                                     }
 8811:                                                 }
 8812:                                             }
 8813:                                         }
 8814:                                     }
 8815:                                 }
 8816:                             }
 8817:                         }
 8818:                     }
 8819:                     if ($interval[0] =~ /^(\d+)/) {
 8820:                         my $timelimit = $1; 
 8821:                         my $first_access;
 8822:                         if ($type eq 'resource') {
 8823:                             $first_access=&get_first_access($interval[1],$item);
 8824:                         } elsif ($type eq 'map') {
 8825:                             $first_access=&get_first_access($interval[1],undef,$item);
 8826:                         } else {
 8827:                             $first_access=&get_first_access($interval[1]);
 8828:                         }
 8829:                         if ($first_access) {
 8830:                             my $timesup = $first_access+$timelimit;
 8831:                             if ($timesup > $now) {
 8832:                                 my $activeblock;
 8833:                                 foreach my $res (@to_test) {
 8834:                                     if ($res->answerable()) {
 8835:                                         $activeblock = 1;
 8836:                                         last;
 8837:                                     }
 8838:                                 }
 8839:                                 if ($activeblock) {
 8840:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8841:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8842:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8843:                                          }
 8844:                                     }
 8845:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8846:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8847:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8848:                                         }
 8849:                                     }
 8850:                                 }
 8851:                             }
 8852:                         }
 8853:                     }
 8854:                 }
 8855:             }
 8856:         }
 8857:     }
 8858:     return %blockers;
 8859: }
 8860: 
 8861: sub has_comm_blocking {
 8862:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 8863:     my @blockers;
 8864:     return unless ($env{'request.course.id'});
 8865:     return unless ($priv eq 'bre');
 8866:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8867:     return if ($env{'request.state'} eq 'construct');
 8868:     my %blockinfo;
 8869:     if (ref($blocks) eq 'HASH') {
 8870:         %blockinfo = &get_commblock_resources($blocks);
 8871:     } else {
 8872:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 8873:         %blockinfo = %cachedblockers;
 8874:     }
 8875:     return unless (keys(%blockinfo) > 0);
 8876:     my (%possibles,@symbs);
 8877:     if (!$symb) {
 8878:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 8879:     }
 8880:     if ($symb) {
 8881:         @symbs = ($symb);
 8882:     } elsif (keys(%possibles)) { 
 8883:         @symbs = keys(%possibles);
 8884:     }
 8885:     my $noblock;
 8886:     foreach my $symb (@symbs) {
 8887:         last if ($noblock);
 8888:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8889:         foreach my $block (keys(%blockinfo)) {
 8890:             if ($block =~ /^firstaccess____(.+)$/) {
 8891:                 my $item = $1;
 8892:                 unless ($blocked) {
 8893:                     if (($item eq $map) || ($item eq $symb)) {
 8894:                         $noblock = 1;
 8895:                         last;
 8896:                     }
 8897:                 }
 8898:             }
 8899:             if (ref($blockinfo{$block}) eq 'HASH') {
 8900:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 8901:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 8902:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8903:                             push(@blockers,$block);
 8904:                         }
 8905:                     }
 8906:                 }
 8907:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 8908:                     if ($blockinfo{$block}{'maps'}{$map}) {
 8909:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8910:                             push(@blockers,$block);
 8911:                         }
 8912:                     }
 8913:                 }
 8914:             }
 8915:         }
 8916:     }
 8917:     unless ($noblock) { 
 8918:         return @blockers;
 8919:     }
 8920:     return;
 8921: }
 8922: }
 8923: 
 8924: sub deeplink_check {
 8925:     my ($priv,$symb,$uri) = @_;
 8926:     return unless ($env{'request.course.id'});
 8927:     return unless ($priv eq 'bre');
 8928:     return if ($env{'request.state'} eq 'construct');
 8929:     return if ($env{'request.role.adv'});
 8930:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8931:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8932:     my (%possibles,@symbs);
 8933:     if (!$symb) {
 8934:         $symb = &symbread($uri,1,1,1,\%possibles);
 8935:     }
 8936:     if ($symb) {
 8937:         @symbs = ($symb);
 8938:     } elsif (keys(%possibles)) {
 8939:         @symbs = keys(%possibles);
 8940:     }
 8941: 
 8942:     my ($login,$switchrole,$allow);
 8943:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8944:         my $key = $1;
 8945:         my $tinyurl;
 8946:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8947:         if (defined($cached)) {
 8948:              $tinyurl = $result;
 8949:         } else {
 8950:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8951:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8952:              if ($currtiny{$key} ne '') {
 8953:                  $tinyurl = $currtiny{$key};
 8954:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8955:              }
 8956:         }
 8957:         if ($tinyurl ne '') {
 8958:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 8959:             if ($cnumreq eq $cnum) {
 8960:                 $login = $posslogin;
 8961:             } else {
 8962:                 $switchrole = 1;
 8963:             }
 8964:         }
 8965:     }
 8966:     foreach my $symb (@symbs) {
 8967:         last if ($allow);
 8968:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8969:         if ($deeplink eq '') {
 8970:             $allow = 1;
 8971:         } else {
 8972:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 8973:             if ($access eq 'any') {
 8974:                 $allow = 1;
 8975:             } elsif ($login) {
 8976:                 if ($access eq 'only') {
 8977:                     if ($scope eq 'res') {
 8978:                         if ($symb eq $login) {
 8979:                             $allow = 1;
 8980:                         }
 8981:                     } elsif ($scope eq 'map') {
 8982: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 8983:                     } elsif ($scope eq 'rec') {
 8984: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 8985:                     }
 8986:                 } else {
 8987:                     my ($acctype,$item) = split(/:/,$access);
 8988:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 8989:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 8990:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8991:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 8992:                                 $allow = 1;
 8993:                             }
 8994:                         }
 8995:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 8996:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 8997:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8998:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 8999:                                 $allow = 1;
 9000:                             }
 9001:                         }
 9002:                     }
 9003:                 }
 9004:             }
 9005:         }
 9006:     }
 9007:     return if ($allow);
 9008:     return 1;
 9009: }
 9010: 
 9011: # -------------------------------- Deversion and split uri into path an filename   
 9012: 
 9013: #
 9014: #   Removes the version from a URI and
 9015: #   splits it in to its filename and path to the filename.
 9016: #   Seems like File::Basename could have done this more clearly.
 9017: #   Parameters:
 9018: #      $uri   - input URI
 9019: #   Returns:
 9020: #     Two element list consisting of 
 9021: #     $pathname  - the URI up to and excluding the trailing /
 9022: #     $filename  - The part of the URI following the last /
 9023: #  NOTE:
 9024: #    Another realization of this is simply:
 9025: #    use File::Basename;
 9026: #    ...
 9027: #    $uri = shift;
 9028: #    $filename = basename($uri);
 9029: #    $path     = dirname($uri);
 9030: #    return ($filename, $path);
 9031: #
 9032: #     The implementation below is probably faster however.
 9033: #
 9034: sub split_uri_for_cond {
 9035:     my $uri=&deversion(&declutter(shift));
 9036:     my @uriparts=split(/\//,$uri);
 9037:     my $filename=pop(@uriparts);
 9038:     my $pathname=join('/',@uriparts);
 9039:     return ($pathname,$filename);
 9040: }
 9041: # --------------------------------------------------- Is a resource on the map?
 9042: 
 9043: sub is_on_map {
 9044:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9045:     #Trying to find the conditional for the file
 9046:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9047: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9048:     if ($match) {
 9049: 	return (1,$1);
 9050:     } else {
 9051: 	return (0,0);
 9052:     }
 9053: }
 9054: 
 9055: # --------------------------------------------------------- Get symb from alias
 9056: 
 9057: sub get_symb_from_alias {
 9058:     my $symb=shift;
 9059:     my ($map,$resid,$url)=&decode_symb($symb);
 9060: # Already is a symb
 9061:     if ($url) { return $symb; }
 9062: # Must be an alias
 9063:     my $aliassymb='';
 9064:     my %bighash;
 9065:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9066:                             &GDBM_READER(),0640)) {
 9067:         my $rid=$bighash{'mapalias_'.$symb};
 9068: 	if ($rid) {
 9069: 	    my ($mapid,$resid)=split(/\./,$rid);
 9070: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9071: 				    $resid,$bighash{'src_'.$rid});
 9072: 	}
 9073:         untie %bighash;
 9074:     }
 9075:     return $aliassymb;
 9076: }
 9077: 
 9078: # ----------------------------------------------------------------- Define Role
 9079: 
 9080: sub definerole {
 9081:   if (allowed('mcr','/')) {
 9082:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9083:     foreach my $role (split(':',$sysrole)) {
 9084: 	my ($crole,$cqual)=split(/\&/,$role);
 9085:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9086:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9087: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9088:                return "refused:s:$crole&$cqual"; 
 9089:             }
 9090:         }
 9091:     }
 9092:     foreach my $role (split(':',$domrole)) {
 9093: 	my ($crole,$cqual)=split(/\&/,$role);
 9094:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9095:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9096: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9097:                return "refused:d:$crole&$cqual"; 
 9098:             }
 9099:         }
 9100:     }
 9101:     foreach my $role (split(':',$courole)) {
 9102: 	my ($crole,$cqual)=split(/\&/,$role);
 9103:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9104:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9105: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9106:                return "refused:c:$crole&$cqual"; 
 9107:             }
 9108:         }
 9109:     }
 9110:     my $uhome;
 9111:     if (($uname ne '') && ($udom ne '')) {
 9112:         $uhome = &homeserver($uname,$udom);
 9113:         return $uhome if ($uhome eq 'no_host');
 9114:     } else {
 9115:         $uname = $env{'user.name'};
 9116:         $udom = $env{'user.domain'};
 9117:         $uhome = $env{'user.home'};
 9118:     }
 9119:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9120:                 "$udom:$uname:rolesdef_$rolename=".
 9121:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9122:     return reply($command,$uhome);
 9123:   } else {
 9124:     return 'refused';
 9125:   }
 9126: }
 9127: 
 9128: # ---------------- Make a metadata query against the network of library servers
 9129: 
 9130: sub metadata_query {
 9131:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9132:     my %rhash;
 9133:     my %libserv = &all_library();
 9134:     my @server_list = (defined($server_array) ? @$server_array
 9135:                                               : keys(%libserv) );
 9136:     for my $server (@server_list) {
 9137:         my $domains = ''; 
 9138:         if (ref($domains_hash) eq 'HASH') {
 9139:             $domains = $domains_hash->{$server}; 
 9140:         }
 9141: 	unless ($custom or $customshow) {
 9142: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9143: 	    $rhash{$server}=$reply;
 9144: 	}
 9145: 	else {
 9146: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9147: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9148: 			     $server);
 9149: 	    $rhash{$server}=$reply;
 9150: 	}
 9151:     }
 9152:     return \%rhash;
 9153: }
 9154: 
 9155: # ----------------------------------------- Send log queries and wait for reply
 9156: 
 9157: sub log_query {
 9158:     my ($uname,$udom,$query,%filters)=@_;
 9159:     my $uhome=&homeserver($uname,$udom);
 9160:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9161:     my $uhost=&hostname($uhome);
 9162:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9163:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9164:                        $uhome);
 9165:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9166:     return get_query_reply($queryid);
 9167: }
 9168: 
 9169: # -------------------------- Update MySQL table for portfolio file
 9170: 
 9171: sub update_portfolio_table {
 9172:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9173:     if ($group ne '') {
 9174:         $file_name =~s /^\Q$group\E//;
 9175:     }
 9176:     my $homeserver = &homeserver($uname,$udom);
 9177:     my $queryid=
 9178:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9179:                ':'.&escape($file_name).':'.$action,$homeserver);
 9180:     my $reply = &get_query_reply($queryid);
 9181:     return $reply;
 9182: }
 9183: 
 9184: # -------------------------- Update MySQL allusers table
 9185: 
 9186: sub update_allusers_table {
 9187:     my ($uname,$udom,$names) = @_;
 9188:     my $homeserver = &homeserver($uname,$udom);
 9189:     my $queryid=
 9190:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9191:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9192:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9193:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9194:                'generation='.&escape($names->{'generation'}).'%%'.
 9195:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9196:                'id='.&escape($names->{'id'}),$homeserver);
 9197:     return;
 9198: }
 9199: 
 9200: # ------- Request retrieval of institutional classlists for course(s)
 9201: 
 9202: sub fetch_enrollment_query {
 9203:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9204:     my ($homeserver,$sleep,$loopmax);
 9205:     my $maxtries = 1;
 9206:     if ($context eq 'automated') {
 9207:         $homeserver = $perlvar{'lonHostID'};
 9208:         $sleep = 2;
 9209:         $loopmax = 100;
 9210:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9211:     } else {
 9212:         $homeserver = &homeserver($cnum,$dom);
 9213:     }
 9214:     my $host=&hostname($homeserver);
 9215:     my $cmd = '';
 9216:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9217:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9218:     }
 9219:     $cmd =~ s/%%$//;
 9220:     $cmd = &escape($cmd);
 9221:     my $query = 'fetchenrollment';
 9222:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9223:     unless ($queryid=~/^\Q$host\E\_/) { 
 9224:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9225:         return 'error: '.$queryid;
 9226:     }
 9227:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9228:     my $tries = 1;
 9229:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9230:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9231:         $tries ++;
 9232:     }
 9233:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9234:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9235:     } else {
 9236:         my @responses = split(/:/,$reply);
 9237:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9238:             foreach my $line (@responses) {
 9239:                 my ($key,$value) = split(/=/,$line,2);
 9240:                 $$replyref{$key} = $value;
 9241:             }
 9242:         } else {
 9243:             my $pathname = LONCAPA::tempdir();
 9244:             foreach my $line (@responses) {
 9245:                 my ($key,$value) = split(/=/,$line);
 9246:                 $$replyref{$key} = $value;
 9247:                 if ($value > 0) {
 9248:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9249:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9250:                         my $destname = $pathname.'/'.$filename;
 9251:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9252:                         if ($xml_classlist =~ /^error/) {
 9253:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9254:                         } else {
 9255:                             if ( open(FILE,">",$destname) ) {
 9256:                                 print FILE &unescape($xml_classlist);
 9257:                                 close(FILE);
 9258:                             } else {
 9259:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9260:                             }
 9261:                         }
 9262:                     }
 9263:                 }
 9264:             }
 9265:         }
 9266:         return 'ok';
 9267:     }
 9268:     return 'error';
 9269: }
 9270: 
 9271: sub get_query_reply {
 9272:     my ($queryid,$sleep,$loopmax) = @_;;
 9273:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9274:         $sleep = 0.2;
 9275:     }
 9276:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9277:         $loopmax = 100;
 9278:     }
 9279:     my $replyfile=LONCAPA::tempdir().$queryid;
 9280:     my $reply='';
 9281:     for (1..$loopmax) {
 9282: 	sleep($sleep);
 9283:         if (-e $replyfile.'.end') {
 9284: 	    if (open(my $fh,"<",$replyfile)) {
 9285: 		$reply = join('',<$fh>);
 9286: 		close($fh);
 9287: 	   } else { return 'error: reply_file_error'; }
 9288:            return &unescape($reply);
 9289: 	}
 9290:     }
 9291:     return 'timeout:'.$queryid;
 9292: }
 9293: 
 9294: sub courselog_query {
 9295: #
 9296: # possible filters:
 9297: # url: url or symb
 9298: # username
 9299: # domain
 9300: # action: view, submit, grade
 9301: # start: timestamp
 9302: # end: timestamp
 9303: #
 9304:     my (%filters)=@_;
 9305:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9306:     if ($filters{'url'}) {
 9307: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9308:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9309:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9310:     }
 9311:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9312:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9313:     return &log_query($cname,$cdom,'courselog',%filters);
 9314: }
 9315: 
 9316: sub userlog_query {
 9317: #
 9318: # possible filters:
 9319: # action: log check role
 9320: # start: timestamp
 9321: # end: timestamp
 9322: #
 9323:     my ($uname,$udom,%filters)=@_;
 9324:     return &log_query($uname,$udom,'userlog',%filters);
 9325: }
 9326: 
 9327: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9328: 
 9329: sub auto_run {
 9330:     my ($cnum,$cdom) = @_;
 9331:     my $response = 0;
 9332:     my $settings;
 9333:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9334:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9335:         $settings = $domconfig{'autoenroll'};
 9336:         if ($settings->{'run'} eq '1') {
 9337:             $response = 1;
 9338:         }
 9339:     } else {
 9340:         my $homeserver;
 9341:         if (&is_course($cdom,$cnum)) {
 9342:             $homeserver = &homeserver($cnum,$cdom);
 9343:         } else {
 9344:             $homeserver = &domain($cdom,'primary');
 9345:         }
 9346:         if ($homeserver ne 'no_host') {
 9347:             $response = &reply('autorun:'.$cdom,$homeserver);
 9348:         }
 9349:     }
 9350:     return $response;
 9351: }
 9352: 
 9353: sub auto_get_sections {
 9354:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9355:     my $homeserver;
 9356:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9357:         $homeserver = &homeserver($cnum,$cdom);
 9358:     }
 9359:     if (!defined($homeserver)) { 
 9360:         if ($cdom =~ /^$match_domain$/) {
 9361:             $homeserver = &domain($cdom,'primary');
 9362:         }
 9363:     }
 9364:     my @secs;
 9365:     if (defined($homeserver)) {
 9366:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9367:         unless ($response eq 'refused') {
 9368:             @secs = split(/:/,$response);
 9369:         }
 9370:     }
 9371:     return @secs;
 9372: }
 9373: 
 9374: sub auto_new_course {
 9375:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9376:     my $homeserver = &homeserver($cnum,$cdom);
 9377:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9378:     return $response;
 9379: }
 9380: 
 9381: sub auto_validate_courseID {
 9382:     my ($cnum,$cdom,$inst_course_id) = @_;
 9383:     my $homeserver = &homeserver($cnum,$cdom);
 9384:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9385:     return $response;
 9386: }
 9387: 
 9388: sub auto_validate_instcode {
 9389:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9390:     my ($homeserver,$response);
 9391:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9392:         $homeserver = &homeserver($cnum,$cdom);
 9393:     }
 9394:     if (!defined($homeserver)) {
 9395:         if ($cdom =~ /^$match_domain$/) {
 9396:             $homeserver = &domain($cdom,'primary');
 9397:         }
 9398:     }
 9399:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9400:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9401:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9402:     return ($outcome,$description,$defaultcredits);
 9403: }
 9404: 
 9405: sub auto_create_password {
 9406:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9407:     my ($homeserver,$response);
 9408:     my $create_passwd = 0;
 9409:     my $authchk = '';
 9410:     if ($udom =~ /^$match_domain$/) {
 9411:         $homeserver = &domain($udom,'primary');
 9412:     }
 9413:     if ($homeserver eq '') {
 9414:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9415:             $homeserver = &homeserver($cnum,$cdom);
 9416:         }
 9417:     }
 9418:     if ($homeserver eq '') {
 9419:         $authchk = 'nodomain';
 9420:     } else {
 9421:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9422:         if ($response eq 'refused') {
 9423:             $authchk = 'refused';
 9424:         } else {
 9425:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9426:         }
 9427:     }
 9428:     return ($authparam,$create_passwd,$authchk);
 9429: }
 9430: 
 9431: sub auto_photo_permission {
 9432:     my ($cnum,$cdom,$students) = @_;
 9433:     my $homeserver = &homeserver($cnum,$cdom);
 9434:     my ($outcome,$perm_reqd,$conditions) = 
 9435: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9436:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9437: 	return (undef,undef);
 9438:     }
 9439:     return ($outcome,$perm_reqd,$conditions);
 9440: }
 9441: 
 9442: sub auto_checkphotos {
 9443:     my ($uname,$udom,$pid) = @_;
 9444:     my $homeserver = &homeserver($uname,$udom);
 9445:     my ($result,$resulttype);
 9446:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9447: 				   &escape($uname).':'.&escape($pid),
 9448: 				   $homeserver));
 9449:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9450: 	return (undef,undef);
 9451:     }
 9452:     if ($outcome) {
 9453:         ($result,$resulttype) = split(/:/,$outcome);
 9454:     } 
 9455:     return ($result,$resulttype);
 9456: }
 9457: 
 9458: sub auto_photochoice {
 9459:     my ($cnum,$cdom) = @_;
 9460:     my $homeserver = &homeserver($cnum,$cdom);
 9461:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9462: 						       &escape($cdom),
 9463: 						       $homeserver)));
 9464:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9465: 	return (undef,undef);
 9466:     }
 9467:     return ($update,$comment);
 9468: }
 9469: 
 9470: sub auto_photoupdate {
 9471:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9472:     my $homeserver = &homeserver($cnum,$dom);
 9473:     my $host=&hostname($homeserver);
 9474:     my $cmd = '';
 9475:     my $maxtries = 1;
 9476:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9477:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9478:     }
 9479:     $cmd =~ s/%%$//;
 9480:     $cmd = &escape($cmd);
 9481:     my $query = 'institutionalphotos';
 9482:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9483:     unless ($queryid=~/^\Q$host\E\_/) {
 9484:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9485:         return 'error: '.$queryid;
 9486:     }
 9487:     my $reply = &get_query_reply($queryid);
 9488:     my $tries = 1;
 9489:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9490:         $reply = &get_query_reply($queryid);
 9491:         $tries ++;
 9492:     }
 9493:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9494:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9495:     } else {
 9496:         my @responses = split(/:/,$reply);
 9497:         my $outcome = shift(@responses); 
 9498:         foreach my $item (@responses) {
 9499:             my ($key,$value) = split(/=/,$item);
 9500:             $$photo{$key} = $value;
 9501:         }
 9502:         return $outcome;
 9503:     }
 9504:     return 'error';
 9505: }
 9506: 
 9507: sub auto_instcode_format {
 9508:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9509: 	$cat_order) = @_;
 9510:     my $courses = '';
 9511:     my @homeservers;
 9512:     if ($caller eq 'global') {
 9513: 	my %servers = &get_servers($codedom,'library');
 9514: 	foreach my $tryserver (keys(%servers)) {
 9515: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9516: 		push(@homeservers,$tryserver);
 9517: 	    }
 9518:         }
 9519:     } elsif ($caller eq 'requests') {
 9520:         if ($codedom =~ /^$match_domain$/) {
 9521:             my $chome = &domain($codedom,'primary');
 9522:             unless ($chome eq 'no_host') {
 9523:                 push(@homeservers,$chome);
 9524:             }
 9525:         }
 9526:     } else {
 9527:         push(@homeservers,&homeserver($caller,$codedom));
 9528:     }
 9529:     foreach my $code (keys(%{$instcodes})) {
 9530:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9531:     }
 9532:     chop($courses);
 9533:     my $ok_response = 0;
 9534:     my $response;
 9535:     while (@homeservers > 0 && $ok_response == 0) {
 9536:         my $server = shift(@homeservers); 
 9537:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9538:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9539:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9540: 		split(/:/,$response);
 9541:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9542:             push(@{$codetitles},&str2array($codetitles_str));
 9543:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9544:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9545:             $ok_response = 1;
 9546:         }
 9547:     }
 9548:     if ($ok_response) {
 9549:         return 'ok';
 9550:     } else {
 9551:         return $response;
 9552:     }
 9553: }
 9554: 
 9555: sub auto_instcode_defaults {
 9556:     my ($domain,$returnhash,$code_order) = @_;
 9557:     my @homeservers;
 9558: 
 9559:     my %servers = &get_servers($domain,'library');
 9560:     foreach my $tryserver (keys(%servers)) {
 9561: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9562: 	    push(@homeservers,$tryserver);
 9563: 	}
 9564:     }
 9565: 
 9566:     my $response;
 9567:     foreach my $server (@homeservers) {
 9568:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9569:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9570: 	
 9571: 	foreach my $pair (split(/\&/,$response)) {
 9572: 	    my ($name,$value)=split(/\=/,$pair);
 9573: 	    if ($name eq 'code_order') {
 9574: 		@{$code_order} = split(/\&/,&unescape($value));
 9575: 	    } else {
 9576: 		$returnhash->{&unescape($name)}=&unescape($value);
 9577: 	    }
 9578: 	}
 9579: 	return 'ok';
 9580:     }
 9581: 
 9582:     return $response;
 9583: }
 9584: 
 9585: sub auto_possible_instcodes {
 9586:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9587:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9588:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9589:         return;
 9590:     }
 9591:     my (@homeservers,$uhome);
 9592:     if (defined(&domain($domain,'primary'))) {
 9593:         $uhome=&domain($domain,'primary');
 9594:         push(@homeservers,&domain($domain,'primary'));
 9595:     } else {
 9596:         my %servers = &get_servers($domain,'library');
 9597:         foreach my $tryserver (keys(%servers)) {
 9598:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9599:                 push(@homeservers,$tryserver);
 9600:             }
 9601:         }
 9602:     }
 9603:     my $response;
 9604:     foreach my $server (@homeservers) {
 9605:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9606:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9607:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9608:             split(':',$response);
 9609:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9610:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9611:         foreach my $item (split('&',$cat_title)) {   
 9612:             my ($name,$value)=split('=',$item);
 9613:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9614:         }
 9615:         foreach my $item (split('&',$cat_order)) {
 9616:             my ($name,$value)=split('=',$item);
 9617:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9618:         }
 9619:         return 'ok';
 9620:     }
 9621:     return $response;
 9622: }
 9623: 
 9624: sub auto_courserequest_checks {
 9625:     my ($dom) = @_;
 9626:     my ($homeserver,%validations);
 9627:     if ($dom =~ /^$match_domain$/) {
 9628:         $homeserver = &domain($dom,'primary');
 9629:     }
 9630:     unless ($homeserver eq 'no_host') {
 9631:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9632:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9633:             my @items = split(/&/,$response);
 9634:             foreach my $item (@items) {
 9635:                 my ($key,$value) = split('=',$item);
 9636:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9637:             }
 9638:         }
 9639:     }
 9640:     return %validations; 
 9641: }
 9642: 
 9643: sub auto_courserequest_validation {
 9644:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9645:     my ($homeserver,$response);
 9646:     if ($dom =~ /^$match_domain$/) {
 9647:         $homeserver = &domain($dom,'primary');
 9648:     }
 9649:     unless ($homeserver eq 'no_host') {
 9650:         my $customdata;
 9651:         if (ref($custominfo) eq 'HASH') {
 9652:             $customdata = &freeze_escape($custominfo);
 9653:         }
 9654:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9655:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9656:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9657:                                     $customdata,$homeserver));
 9658:     }
 9659:     return $response;
 9660: }
 9661: 
 9662: sub auto_validate_class_sec {
 9663:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9664:     my $homeserver = &homeserver($cnum,$cdom);
 9665:     my $ownerlist;
 9666:     if (ref($owners) eq 'ARRAY') {
 9667:         $ownerlist = join(',',@{$owners});
 9668:     } else {
 9669:         $ownerlist = $owners;
 9670:     }
 9671:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9672:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9673:     return $response;
 9674: }
 9675: 
 9676: sub auto_validate_instclasses {
 9677:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9678:     my ($homeserver,%validations);
 9679:     $homeserver = &homeserver($cnum,$cdom);
 9680:     unless ($homeserver eq 'no_host') {
 9681:         my $ownerlist;
 9682:         if (ref($owners) eq 'ARRAY') {
 9683:             $ownerlist = join(',',@{$owners});
 9684:         } else {
 9685:             $ownerlist = $owners;
 9686:         }
 9687:         if (ref($classesref) eq 'HASH') {
 9688:             my $classes = &freeze_escape($classesref);
 9689:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9690:                                 ':'.$cdom.':'.$classes,$homeserver);
 9691:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9692:                 my @items = split(/&/,$response);
 9693:                 foreach my $item (@items) {
 9694:                     my ($key,$value) = split('=',$item);
 9695:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9696:                 }
 9697:             }
 9698:         }
 9699:     }
 9700:     return %validations;
 9701: }
 9702: 
 9703: sub auto_crsreq_update {
 9704:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9705:         $code,$accessstart,$accessend,$inbound) = @_;
 9706:     my ($homeserver,%crsreqresponse);
 9707:     if ($cdom =~ /^$match_domain$/) {
 9708:         $homeserver = &domain($cdom,'primary');
 9709:     }
 9710:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9711:         my $info;
 9712:         if (ref($inbound) eq 'HASH') {
 9713:             $info = &freeze_escape($inbound);
 9714:         }
 9715:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9716:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9717:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9718:                             &escape($title).':'.&escape($code).':'.
 9719:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9720:                             $homeserver);
 9721:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9722:             my @items = split(/&/,$response);
 9723:             foreach my $item (@items) {
 9724:                 my ($key,$value) = split('=',$item);
 9725:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9726:             }
 9727:         }
 9728:     }
 9729:     return \%crsreqresponse;
 9730: }
 9731: 
 9732: sub auto_export_grades {
 9733:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9734:     my ($homeserver,%exportresponse);
 9735:     if ($cdom =~ /^$match_domain$/) {
 9736:         $homeserver = &domain($cdom,'primary');
 9737:     }
 9738:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9739:         my $info;
 9740:         if (ref($inforef) eq 'HASH') {
 9741:             $info = &freeze_escape($inforef);
 9742:         }
 9743:         if (ref($gradesref) eq 'HASH') {
 9744:             my $grades = &freeze_escape($gradesref);
 9745:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9746:                                 $info.':'.$grades,$homeserver);
 9747:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9748:                 my @items = split(/&/,$response);
 9749:                 foreach my $item (@items) {
 9750:                     my ($key,$value) = split('=',$item);
 9751:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9752:                 }
 9753:             }
 9754:         }
 9755:     }
 9756:     return \%exportresponse;
 9757: }
 9758: 
 9759: sub check_instcode_cloning {
 9760:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9761:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9762:         return;
 9763:     }
 9764:     my $canclone;
 9765:     if (@{$code_order} > 0) {
 9766:         my $instcoderegexp ='^';
 9767:         my @clonecodes = split(/\&/,$cloner);
 9768:         foreach my $item (@{$code_order}) {
 9769:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9770:                 foreach my $pair (@clonecodes) {
 9771:                     my ($key,$val) = split(/\=/,$pair,2);
 9772:                     $val = &unescape($val);
 9773:                     if ($key eq $item) {
 9774:                         $instcoderegexp .= '('.$val.')';
 9775:                         last;
 9776:                     }
 9777:                 }
 9778:             } else {
 9779:                 $instcoderegexp .= $codedefaults->{$item};
 9780:             }
 9781:         }
 9782:         $instcoderegexp .= '$';
 9783:         my (@from,@to);
 9784:         eval {
 9785:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9786:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9787:         };
 9788:         if ((@from > 0) && (@to > 0)) {
 9789:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9790:             if (!@diffs) {
 9791:                 $canclone = 1;
 9792:             }
 9793:         }
 9794:     }
 9795:     return $canclone;
 9796: }
 9797: 
 9798: sub default_instcode_cloning {
 9799:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9800:     my (%codedefaults,@code_order,$canclone);
 9801:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9802:         %codedefaults = %{$codedefaultsref};
 9803:         @code_order = @{$codeorderref};
 9804:     } elsif ($clonedom) {
 9805:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9806:     }
 9807:     if (($domdefclone) && (@code_order)) {
 9808:         my @clonecodes = split(/\+/,$domdefclone);
 9809:         my $instcoderegexp ='^';
 9810:         foreach my $item (@code_order) {
 9811:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9812:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9813:             } else {
 9814:                 $instcoderegexp .= $codedefaults{$item};
 9815:             }
 9816:         }
 9817:         $instcoderegexp .= '$';
 9818:         my (@from,@to);
 9819:         eval {
 9820:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9821:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9822:         };
 9823:         if ((@from > 0) && (@to > 0)) {
 9824:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9825:             if (!@diffs) {
 9826:                 $canclone = 1;
 9827:             }
 9828:         }
 9829:     }
 9830:     return $canclone;
 9831: }
 9832: 
 9833: # ------------------------------------------------------- Course Group routines
 9834: 
 9835: sub get_coursegroups {
 9836:     my ($cdom,$cnum,$group,$namespace) = @_;
 9837:     return(&dump($namespace,$cdom,$cnum,$group));
 9838: }
 9839: 
 9840: sub modify_coursegroup {
 9841:     my ($cdom,$cnum,$groupsettings) = @_;
 9842:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9843: }
 9844: 
 9845: sub toggle_coursegroup_status {
 9846:     my ($cdom,$cnum,$group,$action) = @_;
 9847:     my ($from_namespace,$to_namespace);
 9848:     if ($action eq 'delete') {
 9849:         $from_namespace = 'coursegroups';
 9850:         $to_namespace = 'deleted_groups';
 9851:     } else {
 9852:         $from_namespace = 'deleted_groups';
 9853:         $to_namespace = 'coursegroups';
 9854:     }
 9855:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9856:     if (my $tmp = &error(%curr_group)) {
 9857:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9858:         return ('read error',$tmp);
 9859:     } else {
 9860:         my %savedsettings = %curr_group; 
 9861:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9862:         my $deloutcome;
 9863:         if ($result eq 'ok') {
 9864:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9865:         } else {
 9866:             return ('write error',$result);
 9867:         }
 9868:         if ($deloutcome eq 'ok') {
 9869:             return 'ok';
 9870:         } else {
 9871:             return ('delete error',$deloutcome);
 9872:         }
 9873:     }
 9874: }
 9875: 
 9876: sub modify_group_roles {
 9877:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9878:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9879:     my $role = 'gr/'.&escape($userprivs);
 9880:     my ($uname,$udom) = split(/:/,$user);
 9881:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9882:     if ($result eq 'ok') {
 9883:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9884:     }
 9885:     return $result;
 9886: }
 9887: 
 9888: sub modify_coursegroup_membership {
 9889:     my ($cdom,$cnum,$membership) = @_;
 9890:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9891:     return $result;
 9892: }
 9893: 
 9894: sub get_active_groups {
 9895:     my ($udom,$uname,$cdom,$cnum) = @_;
 9896:     my $now = time;
 9897:     my %groups = ();
 9898:     foreach my $key (keys(%env)) {
 9899:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9900:             my ($start,$end) = split(/\./,$env{$key});
 9901:             if (($end!=0) && ($end<$now)) { next; }
 9902:             if (($start!=0) && ($start>$now)) { next; }
 9903:             if ($1 eq $cdom && $2 eq $cnum) {
 9904:                 $groups{$3} = $env{$key} ;
 9905:             }
 9906:         }
 9907:     }
 9908:     return %groups;
 9909: }
 9910: 
 9911: sub get_group_membership {
 9912:     my ($cdom,$cnum,$group) = @_;
 9913:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9914: }
 9915: 
 9916: sub get_users_groups {
 9917:     my ($udom,$uname,$courseid) = @_;
 9918:     my @usersgroups;
 9919:     my $cachetime=1800;
 9920: 
 9921:     my $hashid="$udom:$uname:$courseid";
 9922:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9923:     if (defined($cached)) {
 9924:         @usersgroups = split(/:/,$grouplist);
 9925:     } else {  
 9926:         $grouplist = '';
 9927:         my $courseurl = &courseid_to_courseurl($courseid);
 9928:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9929:         my $access_end = $env{'course.'.$courseid.
 9930:                               '.default_enrollment_end_date'};
 9931:         my $now = time;
 9932:         foreach my $key (keys(%roleshash)) {
 9933:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9934:                 my $group = $1;
 9935:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9936:                     my $start = $2;
 9937:                     my $end = $1;
 9938:                     if ($start == -1) { next; } # deleted from group
 9939:                     if (($start!=0) && ($start>$now)) { next; }
 9940:                     if (($end!=0) && ($end<$now)) {
 9941:                         if ($access_end && $access_end < $now) {
 9942:                             if ($access_end - $end < 86400) {
 9943:                                 push(@usersgroups,$group);
 9944:                             }
 9945:                         }
 9946:                         next;
 9947:                     }
 9948:                     push(@usersgroups,$group);
 9949:                 }
 9950:             }
 9951:         }
 9952:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9953:         $grouplist = join(':',@usersgroups);
 9954:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9955:     }
 9956:     return @usersgroups;
 9957: }
 9958: 
 9959: sub devalidate_getgroups_cache {
 9960:     my ($udom,$uname,$cdom,$cnum)=@_;
 9961:     my $courseid = $cdom.'_'.$cnum;
 9962: 
 9963:     my $hashid="$udom:$uname:$courseid";
 9964:     &devalidate_cache_new('getgroups',$hashid);
 9965: }
 9966: 
 9967: # ------------------------------------------------------------------ Plain Text
 9968: 
 9969: sub plaintext {
 9970:     my ($short,$type,$cid,$forcedefault) = @_;
 9971:     if ($short =~ m{^cr/}) {
 9972: 	return (split('/',$short))[-1];
 9973:     }
 9974:     if (!defined($cid)) {
 9975:         $cid = $env{'request.course.id'};
 9976:     }
 9977:     my %rolenames = (
 9978:                       Course    => 'std',
 9979:                       Community => 'alt1',
 9980:                       Placement => 'std',
 9981:                     );
 9982:     if ($cid ne '') {
 9983:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9984:             unless ($forcedefault) {
 9985:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9986:                 &Apache::lonlocal::mt_escape(\$roletext);
 9987:                 return &Apache::lonlocal::mt($roletext);
 9988:             }
 9989:         }
 9990:     }
 9991:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9992:         (defined($rolenames{$type})) && 
 9993:         (defined($prp{$short}{$rolenames{$type}}))) {
 9994:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9995:     } elsif ($cid ne '') {
 9996:         my $crstype = $env{'course.'.$cid.'.type'};
 9997:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9998:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9999:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10000:         }
10001:     }
10002:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10003: }
10004: 
10005: # ----------------------------------------------------------------- Assign Role
10006: 
10007: sub assignrole {
10008:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10009:         $context)=@_;
10010:     my $mrole;
10011:     if ($role =~ /^cr\//) {
10012:         my $cwosec=$url;
10013:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10014: 	unless (&allowed('ccr',$cwosec)) {
10015:            my $refused = 1;
10016:            if ($context eq 'requestcourses') {
10017:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10018:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10019:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10020:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10021:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10022:                            if ($crsenv{'internal.courseowner'} eq
10023:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10024:                                $refused = '';
10025:                            }
10026:                        }
10027:                    }
10028:                }
10029:            }
10030:            if ($refused) {
10031:                &logthis('Refused custom assignrole: '.
10032:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10033:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10034:                return 'refused';
10035:            }
10036:         }
10037:         $mrole='cr';
10038:     } elsif ($role =~ /^gr\//) {
10039:         my $cwogrp=$url;
10040:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10041:         unless (&allowed('mdg',$cwogrp)) {
10042:             &logthis('Refused group assignrole: '.
10043:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10044:                     $env{'user.name'}.' at '.$env{'user.domain'});
10045:             return 'refused';
10046:         }
10047:         $mrole='gr';
10048:     } else {
10049:         my $cwosec=$url;
10050:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10051:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10052:             my $refused;
10053:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10054:                 if (!(&allowed('c'.$role,$url))) {
10055:                     $refused = 1;
10056:                 }
10057:             } else {
10058:                 $refused = 1;
10059:             }
10060:             if ($refused) {
10061:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10062:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10063:                     my %crsenv;
10064:                     if ($role eq 'cc' || $role eq 'co') {
10065:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10066:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10067:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10068:                                 if ($crsenv{'internal.courseowner'} eq 
10069:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10070:                                     $refused = '';
10071:                                 }
10072:                             }
10073:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10074:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10075:                                 if ($crsenv{'internal.courseowner'} eq 
10076:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10077:                                     $refused = '';
10078:                                 }
10079:                             }
10080:                         }
10081:                     }
10082:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10083:                     if ($role eq 'st') {
10084:                         $refused = '';
10085:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10086:                         $refused = '';
10087:                     }
10088:                 } elsif ($context eq 'requestcourses') {
10089:                     my @possroles = ('st','ta','ep','in','cc','co');
10090:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10091:                         my $wrongcc;
10092:                         if ($cnum =~ /^$match_community$/) {
10093:                             $wrongcc = 1 if ($role eq 'cc');
10094:                         } else {
10095:                             $wrongcc = 1 if ($role eq 'co');
10096:                         }
10097:                         unless ($wrongcc) {
10098:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10099:                             if ($crsenv{'internal.courseowner'} eq 
10100:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10101:                                 $refused = '';
10102:                             }
10103:                         }
10104:                     }
10105:                 } elsif ($context eq 'requestauthor') {
10106:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10107:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10108:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10109:                             $refused = '';
10110:                         } else {
10111:                             my %domdefaults = &get_domain_defaults($udom);
10112:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10113:                                 my $checkbystatus;
10114:                                 if ($env{'user.adv'}) { 
10115:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10116:                                     if ($disposition eq 'automatic') {
10117:                                         $refused = '';
10118:                                     } elsif ($disposition eq '') {
10119:                                         $checkbystatus = 1;
10120:                                     } 
10121:                                 } else {
10122:                                     $checkbystatus = 1;
10123:                                 }
10124:                                 if ($checkbystatus) {
10125:                                     if ($env{'environment.inststatus'}) {
10126:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10127:                                         foreach my $type (@inststatuses) {
10128:                                             if (($type ne '') &&
10129:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10130:                                                 $refused = '';
10131:                                             }
10132:                                         }
10133:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10134:                                         $refused = '';
10135:                                     }
10136:                                 }
10137:                             }
10138:                         }
10139:                     }
10140:                 }
10141:                 if ($refused) {
10142:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10143:                              ' '.$role.' '.$end.' '.$start.' by '.
10144: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10145:                     return 'refused';
10146:                 }
10147:             }
10148:         } elsif ($role eq 'au') {
10149:             if ($url ne '/'.$udom.'/') {
10150:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10151:                          ' to assign author role for '.$uname.':'.$udom.
10152:                          ' in domain: '.$url.' refused (wrong domain).');
10153:                 return 'refused';
10154:             }
10155:         }
10156:         $mrole=$role;
10157:     }
10158:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10159:                 "$udom:$uname:$url".'_'."$mrole=$role";
10160:     if ($end) { $command.='_'.$end; }
10161:     if ($start) {
10162: 	if ($end) { 
10163:            $command.='_'.$start; 
10164:         } else {
10165:            $command.='_0_'.$start;
10166:         }
10167:     }
10168:     my $origstart = $start;
10169:     my $origend = $end;
10170:     my $delflag;
10171: # actually delete
10172:     if ($deleteflag) {
10173: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10174: # modify command to delete the role
10175:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10176:                 "$udom:$uname:$url".'_'."$mrole";
10177: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10178: # set start and finish to negative values for userrolelog
10179:            $start=-1;
10180:            $end=-1;
10181:            $delflag = 1;
10182:         }
10183:     }
10184: # send command
10185:     my $answer=&reply($command,&homeserver($uname,$udom));
10186: # log new user role if status is ok
10187:     if ($answer eq 'ok') {
10188: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10189:         if (($role eq 'cc') || ($role eq 'in') ||
10190:             ($role eq 'ep') || ($role eq 'ad') ||
10191:             ($role eq 'ta') || ($role eq 'st') ||
10192:             ($role=~/^cr/) || ($role eq 'gr') ||
10193:             ($role eq 'co')) {
10194: # for course roles, perform group memberships changes triggered by role change.
10195:             unless ($role =~ /^gr/) {
10196:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10197:                                                  $origstart,$selfenroll,$context);
10198:             }
10199:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10200:                            $selfenroll,$context);
10201:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10202:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10203:                  ($role eq 'da')) {
10204:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10205:                            $context);
10206:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10207:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10208:                              $context); 
10209:         }
10210:         if ($role eq 'cc') {
10211:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10212:         }
10213:     }
10214:     return $answer;
10215: }
10216: 
10217: sub autoupdate_coowners {
10218:     my ($url,$end,$start,$uname,$udom) = @_;
10219:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10220:     if (($cdom ne '') && ($cnum ne '')) {
10221:         my $now = time;
10222:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10223:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10224:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10225:             my $instcode = $coursehash{'internal.coursecode'};
10226:             if ($instcode ne '') {
10227:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10228:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10229:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10230:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10231:                         if ($result eq 'valid') {
10232:                             if ($coursehash{'internal.co-owners'}) {
10233:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10234:                                     push(@newcoowners,$coowner);
10235:                                 }
10236:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10237:                                     push(@newcoowners,$uname.':'.$udom);
10238:                                 }
10239:                                 @newcoowners = sort(@newcoowners);
10240:                             } else {
10241:                                 push(@newcoowners,$uname.':'.$udom);
10242:                             }
10243:                         } else {
10244:                             if ($coursehash{'internal.co-owners'}) {
10245:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10246:                                     unless ($coowner eq $uname.':'.$udom) {
10247:                                         push(@newcoowners,$coowner);
10248:                                     }
10249:                                 }
10250:                                 unless (@newcoowners > 0) {
10251:                                     $delcoowners = 1;
10252:                                     $coowners = '';
10253:                                 }
10254:                             }
10255:                         }
10256:                         if (@newcoowners || $delcoowners) {
10257:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10258:                                             $delcoowners,@newcoowners);
10259:                         }
10260:                     }
10261:                 }
10262:             }
10263:         }
10264:     }
10265: }
10266: 
10267: sub store_coowners {
10268:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10269:     my $cid = $cdom.'_'.$cnum;
10270:     my ($coowners,$delresult,$putresult);
10271:     if (@newcoowners) {
10272:         $coowners = join(',',@newcoowners);
10273:         my %coownershash = (
10274:                             'internal.co-owners' => $coowners,
10275:                            );
10276:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10277:         if ($putresult eq 'ok') {
10278:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10279:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10280:             }
10281:         }
10282:     }
10283:     if ($delcoowners) {
10284:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10285:         if ($delresult eq 'ok') {
10286:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10287:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10288:             }
10289:         }
10290:     }
10291:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10292:         my %crsinfo =
10293:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10294:         if (ref($crsinfo{$cid}) eq 'HASH') {
10295:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10296:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10297:         }
10298:     }
10299: }
10300: 
10301: # -------------------------------------------------- Modify user authentication
10302: # Overrides without validation
10303: 
10304: sub modifyuserauth {
10305:     my ($udom,$uname,$umode,$upass)=@_;
10306:     my $uhome=&homeserver($uname,$udom);
10307:     my $allowed;
10308:     if (&allowed('mau',$udom)) {
10309:         $allowed = 1;
10310:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10311:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10312:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10313:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10314:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10315:         if (($cdom ne '') && ($cnum ne '')) {
10316:             my $is_owner = &is_course_owner($cdom,$cnum);
10317:             if ($is_owner) {
10318:                 $allowed = 1;
10319:             }
10320:         }
10321:     }
10322:     unless ($allowed) { return 'refused'; }
10323:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10324:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10325:              ' in domain '.$env{'request.role.domain'});  
10326:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10327: 		     &escape($upass),$uhome);
10328:     my $ip = &get_requestor_ip();
10329:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10330:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10331:          '(Remote '.$ip.'): '.$reply);
10332:     &log($udom,,$uname,$uhome,
10333:         'Authentication changed by '.$env{'user.domain'}.', '.
10334:                                      $env{'user.name'}.', '.$umode.
10335:          '(Remote '.$ip.'): '.$reply);
10336:     unless ($reply eq 'ok') {
10337:         &logthis('Authentication mode error: '.$reply);
10338: 	return 'error: '.$reply;
10339:     }   
10340:     return 'ok';
10341: }
10342: 
10343: # --------------------------------------------------------------- Modify a user
10344: 
10345: sub modifyuser {
10346:     my ($udom,    $uname, $uid,
10347:         $umode,   $upass, $first,
10348:         $middle,  $last,  $gene,
10349:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10350:     $udom= &LONCAPA::clean_domain($udom);
10351:     $uname=&LONCAPA::clean_username($uname);
10352:     my $showcandelete = 'none';
10353:     if (ref($candelete) eq 'ARRAY') {
10354:         if (@{$candelete} > 0) {
10355:             $showcandelete = join(', ',@{$candelete});
10356:         }
10357:     }
10358:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10359:              $umode.', '.$first.', '.$middle.', '.
10360: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10361:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10362:                                      ' desiredhome not specified'). 
10363:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10364:              ' in domain '.$env{'request.role.domain'});
10365:     my $uhome=&homeserver($uname,$udom,'true');
10366:     my $newuser;
10367:     if ($uhome eq 'no_host') {
10368:         $newuser = 1;
10369:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10370:                 ($umode eq 'lti')) {
10371:             return 'error: more information needed to create new user';
10372:         }
10373:     }
10374: # ----------------------------------------------------------------- Create User
10375:     if (($uhome eq 'no_host') && 
10376: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10377:         my $unhome='';
10378:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10379:             $unhome = $desiredhome;
10380: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10381: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10382:         } else { # load balancing routine for determining $unhome
10383:             my $loadm=10000000;
10384: 	    my %servers = &get_servers($udom,'library');
10385: 	    foreach my $tryserver (keys(%servers)) {
10386: 		my $answer=reply('load',$tryserver);
10387: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10388: 		    $loadm=$answer;
10389: 		    $unhome=$tryserver;
10390: 		}
10391: 	    }
10392:         }
10393:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10394: 	    return 'error: unable to find a home server for '.$uname.
10395:                    ' in domain '.$udom;
10396:         }
10397:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10398:                          &escape($upass),$unhome);
10399: 	unless ($reply eq 'ok') {
10400:             return 'error: '.$reply;
10401:         }   
10402:         $uhome=&homeserver($uname,$udom,'true');
10403:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10404: 	    return 'error: unable verify users home machine.';
10405:         }
10406:     }   # End of creation of new user
10407: # ---------------------------------------------------------------------- Add ID
10408:     if ($uid) {
10409:        $uid=~tr/A-Z/a-z/;
10410:        my %uidhash=&idrget($udom,$uname);
10411:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10412:          && (!$forceid)) {
10413: 	  unless ($uid eq $uidhash{$uname}) {
10414: 	      return 'error: user id "'.$uid.'" does not match '.
10415:                   'current user id "'.$uidhash{$uname}.'".';
10416:           }
10417:        } else {
10418: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10419:        }
10420:     }
10421: # -------------------------------------------------------------- Add names, etc
10422:     my @tmp=&get('environment',
10423: 		   ['firstname','middlename','lastname','generation','id',
10424:                     'permanentemail','inststatus'],
10425: 		   $udom,$uname);
10426:     my (%names,%oldnames);
10427:     if ($tmp[0] =~ m/^error:.*/) { 
10428:         %names=(); 
10429:     } else {
10430:         %names = @tmp;
10431:         %oldnames = %names;
10432:     }
10433: #
10434: # If name, email and/or uid are blank (e.g., because an uploaded file
10435: # of users did not contain them), do not overwrite existing values
10436: # unless field is in $candelete array ref.  
10437: #
10438: 
10439:     my @fields = ('firstname','middlename','lastname','generation',
10440:                   'permanentemail','id');
10441:     my %newvalues;
10442:     if (ref($candelete) eq 'ARRAY') {
10443:         foreach my $field (@fields) {
10444:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10445:                 if ($field eq 'firstname') {
10446:                     $names{$field} = $first;
10447:                 } elsif ($field eq 'middlename') {
10448:                     $names{$field} = $middle;
10449:                 } elsif ($field eq 'lastname') {
10450:                     $names{$field} = $last;
10451:                 } elsif ($field eq 'generation') { 
10452:                     $names{$field} = $gene;
10453:                 } elsif ($field eq 'permanentemail') {
10454:                     $names{$field} = $email;
10455:                 } elsif ($field eq 'id') {
10456:                     $names{$field}  = $uid;
10457:                 }
10458:             }
10459:         }
10460:     }
10461:     if ($first)  { $names{'firstname'}  = $first; }
10462:     if (defined($middle)) { $names{'middlename'} = $middle; }
10463:     if ($last)   { $names{'lastname'}   = $last; }
10464:     if (defined($gene))   { $names{'generation'} = $gene; }
10465:     if ($email) {
10466:        $email=~s/[^\w\@\.\-\,]//gs;
10467:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10468:     }
10469:     if ($uid) { $names{'id'}  = $uid; }
10470:     if (defined($inststatus)) {
10471:         $names{'inststatus'} = '';
10472:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10473:         if (ref($usertypes) eq 'HASH') {
10474:             my @okstatuses; 
10475:             foreach my $item (split(/:/,$inststatus)) {
10476:                 if (defined($usertypes->{$item})) {
10477:                     push(@okstatuses,$item);  
10478:                 }
10479:             }
10480:             if (@okstatuses) {
10481:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10482:             }
10483:         }
10484:     }
10485:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10486:                  $umode.', '.$first.', '.$middle.', '.
10487:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10488:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10489:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10490:     } else {
10491:         $logmsg .= ' during self creation';
10492:     }
10493:     my $changed;
10494:     if ($newuser) {
10495:         $changed = 1;
10496:     } else {
10497:         foreach my $field (@fields) {
10498:             if ($names{$field} ne $oldnames{$field}) {
10499:                 $changed = 1;
10500:                 last;
10501:             }
10502:         }
10503:     }
10504:     unless ($changed) {
10505:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10506:         &logthis($logmsg);
10507:         return 'ok';
10508:     }
10509:     my $reply = &put('environment', \%names, $udom,$uname);
10510:     if ($reply ne 'ok') { 
10511:         return 'error: '.$reply;
10512:     }
10513:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10514:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10515:     }
10516:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10517:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10518:     $logmsg = 'Success modifying user '.$logmsg;
10519:     &logthis($logmsg);
10520:     return 'ok';
10521: }
10522: 
10523: # -------------------------------------------------------------- Modify student
10524: 
10525: sub modifystudent {
10526:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10527:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10528:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10529:     if (!$cid) {
10530: 	unless ($cid=$env{'request.course.id'}) {
10531: 	    return 'not_in_class';
10532: 	}
10533:     }
10534: # --------------------------------------------------------------- Make the user
10535:     my $reply=&modifyuser
10536: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10537:          $desiredhome,$email,$inststatus);
10538:     unless ($reply eq 'ok') { return $reply; }
10539:     # This will cause &modify_student_enrollment to get the uid from the
10540:     # student's environment
10541:     $uid = undef if (!$forceid);
10542:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10543:                                         $gene,$usec,$end,$start,$type,$locktype,
10544:                                         $cid,$selfenroll,$context,$credits,$instsec);
10545:     return $reply;
10546: }
10547: 
10548: sub modify_student_enrollment {
10549:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10550:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10551:     my ($cdom,$cnum,$chome);
10552:     if (!$cid) {
10553: 	unless ($cid=$env{'request.course.id'}) {
10554: 	    return 'not_in_class';
10555: 	}
10556: 	$cdom=$env{'course.'.$cid.'.domain'};
10557: 	$cnum=$env{'course.'.$cid.'.num'};
10558:     } else {
10559: 	($cdom,$cnum)=split(/_/,$cid);
10560:     }
10561:     $chome=$env{'course.'.$cid.'.home'};
10562:     if (!$chome) {
10563: 	$chome=&homeserver($cnum,$cdom);
10564:     }
10565:     if (!$chome) { return 'unknown_course'; }
10566:     # Make sure the user exists
10567:     my $uhome=&homeserver($uname,$udom);
10568:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10569: 	return 'error: no such user';
10570:     }
10571:     # Get student data if we were not given enough information
10572:     if (!defined($first)  || $first  eq '' || 
10573:         !defined($last)   || $last   eq '' || 
10574:         !defined($uid)    || $uid    eq '' || 
10575:         !defined($middle) || $middle eq '' || 
10576:         !defined($gene)   || $gene   eq '') {
10577:         # They did not supply us with enough data to enroll the student, so
10578:         # we need to pick up more information.
10579:         my %tmp = &get('environment',
10580:                        ['firstname','middlename','lastname', 'generation','id']
10581:                        ,$udom,$uname);
10582: 
10583:         #foreach my $key (keys(%tmp)) {
10584:         #    &logthis("key $key = ".$tmp{$key});
10585:         #}
10586:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10587:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10588:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10589:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10590:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10591:     }
10592:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10593:     my $user = "$uname:$udom";
10594:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10595:     my $reply=cput('classlist',
10596: 		   {$user => 
10597: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10598: 		   $cdom,$cnum);
10599:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10600:         &devalidate_getsection_cache($udom,$uname,$cid);
10601:     } else { 
10602: 	return 'error: '.$reply;
10603:     }
10604:     # Add student role to user
10605:     my $uurl='/'.$cid;
10606:     $uurl=~s/\_/\//g;
10607:     if ($usec) {
10608: 	$uurl.='/'.$usec;
10609:     }
10610:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10611:                              $selfenroll,$context);
10612:     if ($result ne 'ok') {
10613:         if ($old_entry{$user} ne '') {
10614:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10615:         } else {
10616:             $reply = &del('classlist',[$user],$cdom,$cnum);
10617:         }
10618:     }
10619:     return $result; 
10620: }
10621: 
10622: sub format_name {
10623:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10624:     my $name;
10625:     if ($first ne 'lastname') {
10626: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10627:     } else {
10628: 	if ($lastname=~/\S/) {
10629: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10630: 	    $name=~s/\s+,/,/;
10631: 	} else {
10632: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10633: 	}
10634:     }
10635:     $name=~s/^\s+//;
10636:     $name=~s/\s+$//;
10637:     $name=~s/\s+/ /g;
10638:     return $name;
10639: }
10640: 
10641: # ------------------------------------------------- Write to course preferences
10642: 
10643: sub writecoursepref {
10644:     my ($courseid,%prefs)=@_;
10645:     $courseid=~s/^\///;
10646:     $courseid=~s/\_/\//g;
10647:     my ($cdomain,$cnum)=split(/\//,$courseid);
10648:     my $chome=homeserver($cnum,$cdomain);
10649:     if (($chome eq '') || ($chome eq 'no_host')) { 
10650: 	return 'error: no such course';
10651:     }
10652:     my $cstring='';
10653:     foreach my $pref (keys(%prefs)) {
10654: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10655:     }
10656:     $cstring=~s/\&$//;
10657:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10658: }
10659: 
10660: # ---------------------------------------------------------- Make/modify course
10661: 
10662: sub createcourse {
10663:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10664:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10665:     $url=&declutter($url);
10666:     my $cid='';
10667:     if ($context eq 'requestcourses') {
10668:         my $can_create = 0;
10669:         my ($ownername,$ownerdom) = split(':',$course_owner);
10670:         if ($udom eq $ownerdom) {
10671:             my $reload;
10672:             if (($callercontext eq 'auto') &&
10673:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10674:                 $reload = 'reload';
10675:             }
10676:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10677:                                   $context)) {
10678:                 $can_create = 1;
10679:             }
10680:         } else {
10681:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10682:                                            $category);
10683:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10684:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10685:                 if (@curr > 0) {
10686:                     my @options = qw(approval validate autolimit);
10687:                     my $optregex = join('|',@options);
10688:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10689:                         $can_create = 1;
10690:                     }
10691:                 }
10692:             }
10693:         }
10694:         if ($can_create) {
10695:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10696:                 unless (&allowed('ccc',$udom)) {
10697:                     return 'refused'; 
10698:                 }
10699:             }
10700:         } else {
10701:             return 'refused';
10702:         }
10703:     } elsif (!&allowed('ccc',$udom)) {
10704:         return 'refused';
10705:     }
10706: # --------------------------------------------------------------- Get Unique ID
10707:     my $uname;
10708:     if ($cnum =~ /^$match_courseid$/) {
10709:         my $chome=&homeserver($cnum,$udom,'true');
10710:         if (($chome eq '') || ($chome eq 'no_host')) {
10711:             $uname = $cnum;
10712:         } else {
10713:             $uname = &generate_coursenum($udom,$crstype);
10714:         }
10715:     } else {
10716:         $uname = &generate_coursenum($udom,$crstype);
10717:     }
10718:     return $uname if ($uname =~ /^error/);
10719: # -------------------------------------------------- Check supplied server name
10720:     if (!defined($course_server)) {
10721:         if (defined(&domain($udom,'primary'))) {
10722:             $course_server = &domain($udom,'primary');
10723:         } else {
10724:             $course_server = $env{'user.home'}; 
10725:         }
10726:     }
10727:     my %host_servers =
10728:         &Apache::lonnet::get_servers($udom,'library');
10729:     unless ($host_servers{$course_server}) {
10730:         return 'error: invalid home server for course: '.$course_server;
10731:     }
10732: # ------------------------------------------------------------- Make the course
10733:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10734:                       $course_server);
10735:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10736:     my $uhome=&homeserver($uname,$udom,'true');
10737:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10738: 	return 'error: no such course';
10739:     }
10740: # ----------------------------------------------------------------- Course made
10741: # log existence
10742:     my $now = time;
10743:     my $newcourse = {
10744:                     $udom.'_'.$uname => {
10745:                                      description => $description,
10746:                                      inst_code   => $inst_code,
10747:                                      owner       => $course_owner,
10748:                                      type        => $crstype,
10749:                                      creator     => $env{'user.name'}.':'.
10750:                                                     $env{'user.domain'},
10751:                                      created     => $now,
10752:                                      context     => $context,
10753:                                                 },
10754:                     };
10755:     &courseidput($udom,$newcourse,$uhome,'notime');
10756: # set toplevel url
10757:     my $topurl=$url;
10758:     unless ($nonstandard) {
10759: # ------------------------------------------ For standard courses, make top url
10760:         my $mapurl=&clutter($url);
10761:         if ($mapurl eq '/res/') { $mapurl=''; }
10762:         $env{'form.initmap'}=(<<ENDINITMAP);
10763: <map>
10764: <resource id="1" type="start"></resource>
10765: <resource id="2" src="$mapurl"></resource>
10766: <resource id="3" type="finish"></resource>
10767: <link index="1" from="1" to="2"></link>
10768: <link index="2" from="2" to="3"></link>
10769: </map>
10770: ENDINITMAP
10771:         $topurl=&declutter(
10772:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10773:                           );
10774:     }
10775: # ----------------------------------------------------------- Write preferences
10776:     &writecoursepref($udom.'_'.$uname,
10777:                      ('description'              => $description,
10778:                       'url'                      => $topurl,
10779:                       'internal.creator'         => $env{'user.name'}.':'.
10780:                                                     $env{'user.domain'},
10781:                       'internal.created'         => $now,
10782:                       'internal.creationcontext' => $context)
10783:                     );
10784:     return '/'.$udom.'/'.$uname;
10785: }
10786: 
10787: # ------------------------------------------------------------------- Create ID
10788: sub generate_coursenum {
10789:     my ($udom,$crstype) = @_;
10790:     my $domdesc = &domain($udom);
10791:     return 'error: invalid domain' if ($domdesc eq '');
10792:     my $first;
10793:     if ($crstype eq 'Community') {
10794:         $first = '0';
10795:     } else {
10796:         $first = int(1+rand(9)); 
10797:     } 
10798:     my $uname=$first.
10799:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10800:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10801:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10802: # ----------------------------------------------- Make sure that does not exist
10803:     my $uhome=&homeserver($uname,$udom,'true');
10804:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10805:         if ($crstype eq 'Community') {
10806:             $first = '0';
10807:         } else {
10808:             $first = int(1+rand(9));
10809:         }
10810:         $uname=$first.
10811:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10812:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10813:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10814:         $uhome=&homeserver($uname,$udom,'true');
10815:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10816:             return 'error: unable to generate unique course-ID';
10817:         }
10818:     }
10819:     return $uname;
10820: }
10821: 
10822: sub is_course {
10823:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10824:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10825: 
10826:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10827:     my $uhome=&homeserver($cnum,$cdom);
10828:     my $iscourse;
10829:     if (grep { $_ eq $uhome } current_machine_ids()) {
10830:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10831:     } else {
10832:         my $hashid = $cdom.':'.$cnum;
10833:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10834:         unless (defined($cached)) {
10835:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10836:                                         $cnum,undef,undef,'.');
10837:             $iscourse = 0;
10838:             if (exists($courses{$cdom.'_'.$cnum})) {
10839:                 $iscourse = 1;
10840:             }
10841:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10842:         }
10843:     }
10844:     return unless ($iscourse);
10845:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10846: }
10847: 
10848: sub store_userdata {
10849:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10850:     my $result;
10851:     if ($datakey ne '') {
10852:         if (ref($storehash) eq 'HASH') {
10853:             if ($udom eq '' || $uname eq '') {
10854:                 $udom = $env{'user.domain'};
10855:                 $uname = $env{'user.name'};
10856:             }
10857:             my $uhome=&homeserver($uname,$udom);
10858:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10859:                 $result = 'error: no_host';
10860:             } else {
10861:                 $storehash->{'ip'} = &get_requestor_ip();
10862:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10863: 
10864:                 my $namevalue='';
10865:                 foreach my $key (keys(%{$storehash})) {
10866:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10867:                 }
10868:                 $namevalue=~s/\&$//;
10869:                 unless ($namespace eq 'courserequests') {
10870:                     $datakey = &escape($datakey);
10871:                 }
10872:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10873:                                   $namevalue,$uhome);
10874:             }
10875:         } else {
10876:             $result = 'error: data to store was not a hash reference'; 
10877:         }
10878:     } else {
10879:         $result= 'error: invalid requestkey'; 
10880:     }
10881:     return $result;
10882: }
10883: 
10884: # ---------------------------------------------------------- Assign Custom Role
10885: 
10886: sub assigncustomrole {
10887:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10888:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10889:                        $end,$start,$deleteflag,$selfenroll,$context);
10890: }
10891: 
10892: # ----------------------------------------------------------------- Revoke Role
10893: 
10894: sub revokerole {
10895:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10896:     my $now=time;
10897:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10898: }
10899: 
10900: # ---------------------------------------------------------- Revoke Custom Role
10901: 
10902: sub revokecustomrole {
10903:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10904:     my $now=time;
10905:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10906:            $deleteflag,$selfenroll,$context);
10907: }
10908: 
10909: # ------------------------------------------------------------ Disk usage
10910: sub diskusage {
10911:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10912:     $directorypath =~ s/\/$//;
10913:     my $listing=&reply('du2:'.&escape($directorypath).':'
10914:                        .&escape($getpropath).':'.&escape($uname).':'
10915:                        .&escape($udom),homeserver($uname,$udom));
10916:     if ($listing eq 'unknown_cmd') {
10917:         if ($getpropath) {
10918:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10919:         }
10920:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10921:     }
10922:     return $listing;
10923: }
10924: 
10925: sub is_locked {
10926:     my ($file_name, $domain, $user, $which) = @_;
10927:     my @check;
10928:     my $is_locked;
10929:     push (@check,$file_name);
10930:     my %locked = &get('file_permissions',\@check,
10931: 		      $env{'user.domain'},$env{'user.name'});
10932:     my ($tmp)=keys(%locked);
10933:     if ($tmp=~/^error:/) { undef(%locked); }
10934:     
10935:     if (ref($locked{$file_name}) eq 'ARRAY') {
10936:         $is_locked = 'false';
10937:         foreach my $entry (@{$locked{$file_name}}) {
10938:            if (ref($entry) eq 'ARRAY') {
10939:                $is_locked = 'true';
10940:                if (ref($which) eq 'ARRAY') {
10941:                    push(@{$which},$entry);
10942:                } else {
10943:                    last;
10944:                }
10945:            }
10946:        }
10947:     } else {
10948:         $is_locked = 'false';
10949:     }
10950:     return $is_locked;
10951: }
10952: 
10953: sub declutter_portfile {
10954:     my ($file) = @_;
10955:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10956:     return $file;
10957: }
10958: 
10959: # ------------------------------------------------------------- Mark as Read Only
10960: 
10961: sub mark_as_readonly {
10962:     my ($domain,$user,$files,$what) = @_;
10963:     my %current_permissions = &dump('file_permissions',$domain,$user);
10964:     my ($tmp)=keys(%current_permissions);
10965:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10966:     foreach my $file (@{$files}) {
10967: 	$file = &declutter_portfile($file);
10968:         push(@{$current_permissions{$file}},$what);
10969:     }
10970:     &put('file_permissions',\%current_permissions,$domain,$user);
10971:     return;
10972: }
10973: 
10974: # ------------------------------------------------------------Save Selected Files
10975: 
10976: sub save_selected_files {
10977:     my ($user, $path, @files) = @_;
10978:     my $filename = $user."savedfiles";
10979:     my @other_files = &files_not_in_path($user, $path);
10980:     open (OUT,'>',LONCAPA::tempdir().$filename);
10981:     foreach my $file (@files) {
10982:         print (OUT $env{'form.currentpath'}.$file."\n");
10983:     }
10984:     foreach my $file (@other_files) {
10985:         print (OUT $file."\n");
10986:     }
10987:     close (OUT);
10988:     return 'ok';
10989: }
10990: 
10991: sub clear_selected_files {
10992:     my ($user) = @_;
10993:     my $filename = $user."savedfiles";
10994:     open (OUT,'>',LONCAPA::tempdir().$filename);
10995:     print (OUT undef);
10996:     close (OUT);
10997:     return ("ok");    
10998: }
10999: 
11000: sub files_in_path {
11001:     my ($user, $path) = @_;
11002:     my $filename = $user."savedfiles";
11003:     my %return_files;
11004:     open (IN,'<',LONCAPA::tempdir().$filename);
11005:     while (my $line_in = <IN>) {
11006:         chomp ($line_in);
11007:         my @paths_and_file = split (m!/!, $line_in);
11008:         my $file_part = pop (@paths_and_file);
11009:         my $path_part = join ('/', @paths_and_file);
11010:         $path_part.='/';
11011:         my $path_and_file = $path_part.$file_part;
11012:         if ($path_part eq $path) {
11013:             $return_files{$file_part}= 'selected';
11014:         }
11015:     }
11016:     close (IN);
11017:     return (\%return_files);
11018: }
11019: 
11020: # called in portfolio select mode, to show files selected NOT in current directory
11021: sub files_not_in_path {
11022:     my ($user, $path) = @_;
11023:     my $filename = $user."savedfiles";
11024:     my @return_files;
11025:     my $path_part;
11026:     open(IN, '<',LONCAPA::tempdir().$filename);
11027:     while (my $line = <IN>) {
11028:         #ok, I know it's clunky, but I want it to work
11029:         my @paths_and_file = split(m|/|, $line);
11030:         my $file_part = pop(@paths_and_file);
11031:         chomp($file_part);
11032:         my $path_part = join('/', @paths_and_file);
11033:         $path_part .= '/';
11034:         my $path_and_file = $path_part.$file_part;
11035:         if ($path_part ne $path) {
11036:             push(@return_files, ($path_and_file));
11037:         }
11038:     }
11039:     close(OUT);
11040:     return (@return_files);
11041: }
11042: 
11043: #------------------------------Submitted/Handedback Portfolio Files Versioning
11044:  
11045: sub portfiles_versioning {
11046:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11047:     my $portfolio_root = '/userfiles/portfolio';
11048:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11049:     foreach my $file (@{$portfiles}) {
11050:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11051:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11052:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11053:         my $getpropath = 1;
11054:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11055:                                              $stu_name,$getpropath);
11056:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11057:         my $new_answer = 
11058:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11059:         if ($new_answer ne 'problem getting file') {
11060:             push(@{$versioned_portfiles}, $directory.$new_answer);
11061:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11062:                               [$symb,$env{'request.course.id'},'graded']);
11063:         }
11064:     }
11065: }
11066: 
11067: sub get_next_version {
11068:     my ($answer_name, $answer_ext, $dir_list) = @_;
11069:     my $version;
11070:     if (ref($dir_list) eq 'ARRAY') {
11071:         foreach my $row (@{$dir_list}) {
11072:             my ($file) = split(/\&/,$row,2);
11073:             my ($file_name,$file_version,$file_ext) =
11074:                 &file_name_version_ext($file);
11075:             if (($file_name eq $answer_name) &&
11076:                 ($file_ext eq $answer_ext)) {
11077:                      # gets here if filename and extension match,
11078:                      # regardless of version
11079:                 if ($file_version ne '') {
11080:                     # a versioned file is found  so save it for later
11081:                     if ($file_version > $version) {
11082:                         $version = $file_version;
11083:                     }
11084:                 }
11085:             }
11086:         }
11087:     }
11088:     $version ++;
11089:     return($version);
11090: }
11091: 
11092: sub version_selected_portfile {
11093:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11094:     my ($answer_name,$answer_ver,$answer_ext) =
11095:         &file_name_version_ext($file_name);
11096:     my $new_answer;
11097:     $env{'form.copy'} =
11098:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11099:     if($env{'form.copy'} eq '-1') {
11100:         $new_answer = 'problem getting file';
11101:     } else {
11102:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11103:         my $copy_result = 
11104:             &finishuserfileupload($stu_name,$domain,'copy',
11105:                                   '/portfolio'.$directory.$new_answer);
11106:     }
11107:     undef($env{'form.copy'});
11108:     return ($new_answer);
11109: }
11110: 
11111: sub file_name_version_ext {
11112:     my ($file)=@_;
11113:     my @file_parts = split(/\./, $file);
11114:     my ($name,$version,$ext);
11115:     if (@file_parts > 1) {
11116:         $ext=pop(@file_parts);
11117:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11118:             $version=pop(@file_parts);
11119:         }
11120:         $name=join('.',@file_parts);
11121:     } else {
11122:         $name=join('.',@file_parts);
11123:     }
11124:     return($name,$version,$ext);
11125: }
11126: 
11127: #----------------------------------------------Get portfolio file permissions
11128: 
11129: sub get_portfile_permissions {
11130:     my ($domain,$user) = @_;
11131:     my %current_permissions = &dump('file_permissions',$domain,$user);
11132:     my ($tmp)=keys(%current_permissions);
11133:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11134:     return \%current_permissions;
11135: }
11136: 
11137: #---------------------------------------------Get portfolio file access controls
11138: 
11139: sub get_access_controls {
11140:     my ($current_permissions,$group,$file) = @_;
11141:     my %access;
11142:     my $real_file = $file;
11143:     $file =~ s/\.meta$//;
11144:     if (defined($file)) {
11145:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11146:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11147:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11148:             }
11149:         }
11150:     } else {
11151:         foreach my $key (keys(%{$current_permissions})) {
11152:             if ($key =~ /\0accesscontrol$/) {
11153:                 if (defined($group)) {
11154:                     if ($key !~ m-^\Q$group\E/-) {
11155:                         next;
11156:                     }
11157:                 }
11158:                 my ($fullpath) = split(/\0/,$key);
11159:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11160:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11161:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11162:                     }
11163:                 }
11164:             }
11165:         }
11166:     }
11167:     return %access;
11168: }
11169: 
11170: sub modify_access_controls {
11171:     my ($file_name,$changes,$domain,$user)=@_;
11172:     my ($outcome,$deloutcome);
11173:     my %store_permissions;
11174:     my %new_values;
11175:     my %new_control;
11176:     my %translation;
11177:     my @deletions = ();
11178:     my $now = time;
11179:     if (exists($$changes{'activate'})) {
11180:         if (ref($$changes{'activate'}) eq 'HASH') {
11181:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11182:             my $numnew = scalar(@newitems);
11183:             for (my $i=0; $i<$numnew; $i++) {
11184:                 my $newkey = $newitems[$i];
11185:                 my $newid = &Apache::loncommon::get_cgi_id();
11186:                 if ($newkey =~ /^\d+:/) { 
11187:                     $newkey =~ s/^(\d+)/$newid/;
11188:                     $translation{$1} = $newid;
11189:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11190:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11191:                     $translation{$1} = $newid;
11192:                 }
11193:                 $new_values{$file_name."\0".$newkey} = 
11194:                                           $$changes{'activate'}{$newitems[$i]};
11195:                 $new_control{$newkey} = $now;
11196:             }
11197:         }
11198:     }
11199:     my %todelete;
11200:     my %changed_items;
11201:     foreach my $action ('delete','update') {
11202:         if (exists($$changes{$action})) {
11203:             if (ref($$changes{$action}) eq 'HASH') {
11204:                 foreach my $key (keys(%{$$changes{$action}})) {
11205:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11206:                     if ($action eq 'delete') { 
11207:                         $todelete{$itemnum} = 1;
11208:                     } else {
11209:                         $changed_items{$itemnum} = $key;
11210:                     }
11211:                 }
11212:             }
11213:         }
11214:     }
11215:     # get lock on access controls for file.
11216:     my $lockhash = {
11217:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11218:                                                        ':'.$env{'user.domain'},
11219:                    }; 
11220:     my $tries = 0;
11221:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11222:    
11223:     while (($gotlock ne 'ok') && $tries < 10) {
11224:         $tries ++;
11225:         sleep(0.1);
11226:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11227:     }
11228:     if ($gotlock eq 'ok') {
11229:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11230:         my ($tmp)=keys(%curr_permissions);
11231:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11232:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11233:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11234:             if (ref($curr_controls) eq 'HASH') {
11235:                 foreach my $control_item (keys(%{$curr_controls})) {
11236:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11237:                     if (defined($todelete{$itemnum})) {
11238:                         push(@deletions,$file_name."\0".$control_item);
11239:                     } else {
11240:                         if (defined($changed_items{$itemnum})) {
11241:                             $new_control{$changed_items{$itemnum}} = $now;
11242:                             push(@deletions,$file_name."\0".$control_item);
11243:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11244:                         } else {
11245:                             $new_control{$control_item} = $$curr_controls{$control_item};
11246:                         }
11247:                     }
11248:                 }
11249:             }
11250:         }
11251:         my ($group);
11252:         if (&is_course($domain,$user)) {
11253:             ($group,my $file) = split(/\//,$file_name,2);
11254:         }
11255:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11256:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11257:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11258:         #  remove lock
11259:         my @del_lock = ($file_name."\0".'locked_access_records');
11260:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11261:         my $sqlresult =
11262:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11263:                                     $group);
11264:     } else {
11265:         $outcome = "error: could not obtain lockfile\n";  
11266:     }
11267:     return ($outcome,$deloutcome,\%new_values,\%translation);
11268: }
11269: 
11270: sub make_public_indefinitely {
11271:     my (@requrl) = @_;
11272:     return &automated_portfile_access('public',\@requrl);
11273: }
11274: 
11275: sub automated_portfile_access {
11276:     my ($accesstype,$addsref,$delsref,$info) = @_;
11277:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11278:         return 'invalid';
11279:     }
11280:     my %urls;
11281:     if (ref($addsref) eq 'ARRAY') {
11282:         foreach my $requrl (@{$addsref}) {
11283:             if (&is_portfolio_url($requrl)) {
11284:                 unless (exists($urls{$requrl})) {
11285:                     $urls{$requrl} = 'add';
11286:                 }
11287:             }
11288:         }
11289:     }
11290:     if (ref($delsref) eq 'ARRAY') {
11291:         foreach my $requrl (@{$delsref}) { 
11292:             if (&is_portfolio_url($requrl)) {
11293:                 unless (exists($urls{$requrl})) {
11294:                     $urls{$requrl} = 'delete'; 
11295:                 }
11296:             }
11297:         }
11298:     }
11299:     unless (keys(%urls)) {
11300:         return 'invalid';
11301:     }
11302:     my $ip;
11303:     if ($accesstype eq 'ip') {
11304:         if (ref($info) eq 'HASH') {
11305:             if ($info->{'ip'} ne '') {
11306:                 $ip = $info->{'ip'};
11307:             }
11308:         }
11309:         if ($ip eq '') {
11310:             return 'invalid';
11311:         }
11312:     }
11313:     my $errors;
11314:     my $now = time;
11315:     my %current_perms;
11316:     foreach my $requrl (sort(keys(%urls))) {
11317:         my $action;
11318:         if ($urls{$requrl} eq 'add') {
11319:             $action = 'activate';
11320:         } else {
11321:             $action = 'none';
11322:         }
11323:         my $aclnum = 0;
11324:         my (undef,$udom,$unum,$file_name,$group) =
11325:             &parse_portfolio_url($requrl);
11326:         unless (exists($current_perms{$unum.':'.$udom})) {
11327:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11328:         }
11329:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11330:                                                    $group,$file_name);
11331:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11332:             my ($num,$scope,$end,$start) = 
11333:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11334:             if ($scope eq $accesstype) {
11335:                 if (($start <= $now) && ($end == 0)) {
11336:                     if ($accesstype eq 'ip') {
11337:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11338:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11339:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11340:                                     if ($urls{$requrl} eq 'add') {
11341:                                         $action = 'none';
11342:                                         last;
11343:                                     } else {
11344:                                         $action = 'delete';
11345:                                         $aclnum = $num;
11346:                                         last;
11347:                                     }
11348:                                 }
11349:                             }
11350:                         }
11351:                     } elsif ($accesstype eq 'public') {
11352:                         if ($urls{$requrl} eq 'add') {
11353:                             $action = 'none';
11354:                             last;
11355:                         } else {
11356:                             $action = 'delete';
11357:                             $aclnum = $num;
11358:                             last;
11359:                         }
11360:                     }
11361:                 } elsif ($accesstype eq 'public') {
11362:                     $action = 'update';
11363:                     $aclnum = $num;
11364:                     last;
11365:                 }
11366:             }
11367:         }
11368:         if ($action eq 'none') {
11369:             next;
11370:         } else {
11371:             my %changes;
11372:             my $newend = 0;
11373:             my $newstart = $now;
11374:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11375:             $changes{$action}{$newkey} = {
11376:                 type => $accesstype,
11377:                 time => {
11378:                     start => $newstart,
11379:                     end   => $newend,
11380:                 },
11381:             };
11382:             if ($accesstype eq 'ip') {
11383:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11384:             }
11385:             my ($outcome,$deloutcome,$new_values,$translation) =
11386:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11387:             unless ($outcome eq 'ok') {
11388:                 $errors .= $outcome.' ';
11389:             }
11390:         }
11391:     }
11392:     if ($errors) {
11393:         $errors =~ s/\s$//;
11394:         return $errors;
11395:     } else {
11396:         return 'ok';
11397:     }
11398: }
11399: 
11400: #------------------------------------------------------Get Marked as Read Only
11401: 
11402: sub get_marked_as_readonly {
11403:     my ($domain,$user,$what,$group) = @_;
11404:     my $current_permissions = &get_portfile_permissions($domain,$user);
11405:     my @readonly_files;
11406:     my $cmp1=$what;
11407:     if (ref($what)) { $cmp1=join('',@{$what}) };
11408:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11409:         if (defined($group)) {
11410:             if ($file_name !~ m-^\Q$group\E/-) {
11411:                 next;
11412:             }
11413:         }
11414:         if (ref($value) eq "ARRAY"){
11415:             foreach my $stored_what (@{$value}) {
11416:                 my $cmp2=$stored_what;
11417:                 if (ref($stored_what) eq 'ARRAY') {
11418:                     $cmp2=join('',@{$stored_what});
11419:                 }
11420:                 if ($cmp1 eq $cmp2) {
11421:                     push(@readonly_files, $file_name);
11422:                     last;
11423:                 } elsif (!defined($what)) {
11424:                     push(@readonly_files, $file_name);
11425:                     last;
11426:                 }
11427:             }
11428:         }
11429:     }
11430:     return @readonly_files;
11431: }
11432: #-----------------------------------------------------------Get Marked as Read Only Hash
11433: 
11434: sub get_marked_as_readonly_hash {
11435:     my ($current_permissions,$group,$what) = @_;
11436:     my %readonly_files;
11437:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11438:         if (defined($group)) {
11439:             if ($file_name !~ m-^\Q$group\E/-) {
11440:                 next;
11441:             }
11442:         }
11443:         if (ref($value) eq "ARRAY"){
11444:             foreach my $stored_what (@{$value}) {
11445:                 if (ref($stored_what) eq 'ARRAY') {
11446:                     foreach my $lock_descriptor(@{$stored_what}) {
11447:                         if ($lock_descriptor eq 'graded') {
11448:                             $readonly_files{$file_name} = 'graded';
11449:                         } elsif ($lock_descriptor eq 'handback') {
11450:                             $readonly_files{$file_name} = 'handback';
11451:                         } else {
11452:                             if (!exists($readonly_files{$file_name})) {
11453:                                 $readonly_files{$file_name} = 'locked';
11454:                             }
11455:                         }
11456:                     }
11457:                 } 
11458:             }
11459:         } 
11460:     }
11461:     return %readonly_files;
11462: }
11463: # ------------------------------------------------------------ Unmark as Read Only
11464: 
11465: sub unmark_as_readonly {
11466:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11467:     # for portfolio submissions, $what contains [$symb,$crsid] 
11468:     my ($domain,$user,$what,$file_name,$group) = @_;
11469:     $file_name = &declutter_portfile($file_name);
11470:     my $symb_crs = $what;
11471:     if (ref($what)) { $symb_crs=join('',@$what); }
11472:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11473:     my ($tmp)=keys(%current_permissions);
11474:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11475:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11476:     foreach my $file (@readonly_files) {
11477: 	my $clean_file = &declutter_portfile($file);
11478: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11479: 	my $current_locks = $current_permissions{$file};
11480:         my @new_locks;
11481:         my @del_keys;
11482:         if (ref($current_locks) eq "ARRAY"){
11483:             foreach my $locker (@{$current_locks}) {
11484:                 my $compare=$locker;
11485:                 if (ref($locker) eq 'ARRAY') {
11486:                     $compare=join('',@{$locker});
11487:                     if ($compare ne $symb_crs) {
11488:                         push(@new_locks, $locker);
11489:                     }
11490:                 }
11491:             }
11492:             if (scalar(@new_locks) > 0) {
11493:                 $current_permissions{$file} = \@new_locks;
11494:             } else {
11495:                 push(@del_keys, $file);
11496:                 &del('file_permissions',\@del_keys, $domain, $user);
11497:                 delete($current_permissions{$file});
11498:             }
11499:         }
11500:     }
11501:     &put('file_permissions',\%current_permissions,$domain,$user);
11502:     return;
11503: }
11504: 
11505: # ------------------------------------------------------------ Directory lister
11506: 
11507: sub dirlist {
11508:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11509:     $uri=~s/^\///;
11510:     $uri=~s/\/$//;
11511:     my ($udom, $uname);
11512:     if ($getuserdir) {
11513:         $udom = $userdomain;
11514:         $uname = $username;
11515:     } else {
11516:         (undef,$udom,$uname)=split(/\//,$uri);
11517:         if(defined($userdomain)) {
11518:             $udom = $userdomain;
11519:         }
11520:         if(defined($username)) {
11521:             $uname = $username;
11522:         }
11523:     }
11524:     my ($dirRoot,$listing,@listing_results);
11525: 
11526:     $dirRoot = $perlvar{'lonDocRoot'};
11527:     if (defined($getpropath)) {
11528:         $dirRoot = &propath($udom,$uname);
11529:         $dirRoot =~ s/\/$//;
11530:     } elsif (defined($getuserdir)) {
11531:         my $subdir=$uname.'__';
11532:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11533:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11534:                    ."/$udom/$subdir/$uname";
11535:     } elsif (defined($alternateRoot)) {
11536:         $dirRoot = $alternateRoot;
11537:     }
11538: 
11539:     if($udom) {
11540:         if($uname) {
11541:             my $uhome = &homeserver($uname,$udom);
11542:             if ($uhome eq 'no_host') {
11543:                 return ([],'no_host');
11544:             }
11545:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11546:                               .$getuserdir.':'.&escape($dirRoot)
11547:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11548:             if ($listing eq 'unknown_cmd') {
11549:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11550:             } else {
11551:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11552:             }
11553:             if ($listing eq 'unknown_cmd') {
11554:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11555:                 @listing_results = split(/:/,$listing);
11556:             } else {
11557:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11558:             }
11559:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11560:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11561:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11562:                 return ([],$listing);
11563:             } else {
11564:                 return (\@listing_results);
11565:             }
11566:         } elsif(!$alternateRoot) {
11567:             my (%allusers,%listerror);
11568: 	    my %servers = &get_servers($udom,'library');
11569:  	    foreach my $tryserver (keys(%servers)) {
11570:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11571:                                   &escape($udom),$tryserver);
11572:                 if ($listing eq 'unknown_cmd') {
11573: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11574: 				      $udom, $tryserver);
11575:                 } else {
11576:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11577:                 }
11578: 		if ($listing eq 'unknown_cmd') {
11579: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11580: 				      $udom, $tryserver);
11581: 		    @listing_results = split(/:/,$listing);
11582: 		} else {
11583: 		    @listing_results =
11584: 			map { &unescape($_); } split(/:/,$listing);
11585: 		}
11586:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11587:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11588:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11589:                     $listerror{$tryserver} = $listing;
11590:                 } else {
11591: 		    foreach my $line (@listing_results) {
11592: 			my ($entry) = split(/&/,$line,2);
11593: 			$allusers{$entry} = 1;
11594: 		    }
11595: 		}
11596:             }
11597:             my @alluserslist=();
11598:             foreach my $user (sort(keys(%allusers))) {
11599:                 push(@alluserslist,$user.'&user');
11600:             }
11601: 
11602:             if (!%listerror) {
11603:                 # no errors
11604:                 return (\@alluserslist);
11605:             } elsif (scalar(keys(%servers)) == 1) {
11606:                 # one library server, one error 
11607:                 my ($key) = keys(%listerror);
11608:                 return (\@alluserslist, $listerror{$key});
11609:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11610:                 # con_lost indicates that we might miss data from at least one
11611:                 # library server
11612:                 return (\@alluserslist, 'con_lost');
11613:             } else {
11614:                 # multiple library servers and no con_lost -> data should be
11615:                 # complete. 
11616:                 return (\@alluserslist);
11617:             }
11618: 
11619:         } else {
11620:             return ([],'missing username');
11621:         }
11622:     } elsif(!defined($getpropath)) {
11623:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11624:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11625:         return (\@all_domains);
11626:     } else {
11627:         return ([],'missing domain');
11628:     }
11629: }
11630: 
11631: # --------------------------------------------- GetFileTimestamp
11632: # This function utilizes dirlist and returns the date stamp for
11633: # when it was last modified.  It will also return an error of -1
11634: # if an error occurs
11635: 
11636: sub GetFileTimestamp {
11637:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11638:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11639:     $studentName   = &LONCAPA::clean_username($studentName);
11640:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11641:                                     undef,$getuserdir);
11642:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11643:         return -1;
11644:     }
11645:     if (ref($fileref) eq 'ARRAY') {
11646:         my @stats = split('&',$fileref->[0]);
11647:         # @stats contains first the filename, then the stat output
11648:         return $stats[10]; # so this is 10 instead of 9.
11649:     } else {
11650:         return -1;
11651:     }
11652: }
11653: 
11654: sub stat_file {
11655:     my ($uri) = @_;
11656:     $uri = &clutter_with_no_wrapper($uri);
11657: 
11658:     my ($udom,$uname,$file);
11659:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11660: 	($udom,$uname,$file) =
11661: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11662: 	$file = 'userfiles/'.$file;
11663:     }
11664:     if ($uri =~ m-^/res/-) {
11665: 	($udom,$uname) = 
11666: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11667: 	$file = $uri;
11668:     }
11669: 
11670:     if (!$udom || !$uname || !$file) {
11671: 	# unable to handle the uri
11672: 	return ();
11673:     }
11674:     my $getpropath;
11675:     if ($file =~ /^userfiles\//) {
11676:         $getpropath = 1;
11677:     }
11678:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11679:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11680:         return ();
11681:     } else {
11682:         if (ref($listref) eq 'ARRAY') {
11683:             my @stats = split('&',$listref->[0]);
11684: 	    shift(@stats); #filename is first
11685: 	    return @stats;
11686:         }
11687:     }
11688:     return ();
11689: }
11690: 
11691: # --------------------------------------------------------- recursedirs
11692: # Recursive function to traverse either a specific user's Authoring Space
11693: # or corresponding Published Resource Space, and populate the hash ref:
11694: # $dirhashref with URLs of all directories, and if $filehashref hash
11695: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11696: # or .rights files in resource space, and .meta, .save, .log, and .bak
11697: # files in Authoring Space.
11698: #
11699: # Inputs:
11700: #
11701: # $is_home - true if current server is home server for user's space
11702: # $context - either: priv, or res respectively for Authoring or Resource Space.
11703: # $docroot - Document root (i.e., /home/httpd/html
11704: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11705: # $relpath - Current path (relative to top level).
11706: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11707: # $filehashref - reference to hash to populate with URLs of files (Optional)
11708: #
11709: # Returns: nothing
11710: #
11711: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11712: #
11713: # Currently used by interface/londocs.pm to create linked select boxes for
11714: # directory and filename to import a Course "Author" resource into a course, and
11715: # also to create linked select boxes for Authoring Space and Directory to choose
11716: # save location for creation of a new "standard" problem from the Course Editor.
11717: #
11718: 
11719: sub recursedirs {
11720:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11721:     return unless (ref($dirhashref) eq 'HASH');
11722:     my $currpath = $docroot.$toppath;
11723:     if ($relpath) {
11724:         $currpath .= "/$relpath";
11725:     }
11726:     my $savefile;
11727:     if (ref($filehashref)) {
11728:         $savefile = 1;
11729:     }
11730:     if ($is_home) {
11731:         if (opendir(my $dirh,$currpath)) {
11732:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11733:                 next if ($item eq '');
11734:                 if (-d "$currpath/$item") {
11735:                     my $newpath;
11736:                     if ($relpath) {
11737:                         $newpath = "$relpath/$item";
11738:                     } else {
11739:                         $newpath = $item;
11740:                     }
11741:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11742:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11743:                 } elsif ($savefile) {
11744:                     if ($context eq 'priv') {
11745:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11746:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11747:                         }
11748:                     } else {
11749:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11750:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11751:                         }
11752:                     }
11753:                 }
11754:             }
11755:             closedir($dirh);
11756:         }
11757:     } else {
11758:         my ($dirlistref,$listerror) =
11759:             &dirlist($toppath.$relpath);
11760:         my @dir_lines;
11761:         my $dirptr=16384;
11762:         if (ref($dirlistref) eq 'ARRAY') {
11763:             foreach my $dir_line (sort
11764:                               {
11765:                                   my ($afile)=split('&',$a,2);
11766:                                   my ($bfile)=split('&',$b,2);
11767:                                   return (lc($afile) cmp lc($bfile));
11768:                               } (@{$dirlistref})) {
11769:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11770:                     split(/\&/,$dir_line,16);
11771:                 $item =~ s/\s+$//;
11772:                 next if (($item =~ /^\.\.?$/) || ($obs));
11773:                 if ($dirptr&$testdir) {
11774:                     my $newpath;
11775:                     if ($relpath) {
11776:                         $newpath = "$relpath/$item";
11777:                     } else {
11778:                         $relpath = '/';
11779:                         $newpath = $item;
11780:                     }
11781:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11782:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11783:                 } elsif ($savefile) {
11784:                     if ($context eq 'priv') {
11785:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11786:                             $filehashref->{$relpath}{$item} = 1;
11787:                         }
11788:                     } else {
11789:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11790:                             $filehashref->{$relpath}{$item} = 1;
11791:                         }
11792:                     }
11793:                 }
11794:             }
11795:         }
11796:     }
11797:     return;
11798: }
11799: 
11800: # -------------------------------------------------------- Value of a Condition
11801: 
11802: # gets the value of a specific preevaluated condition
11803: #    stored in the string  $env{user.state.<cid>}
11804: # or looks up a condition reference in the bighash and if if hasn't
11805: # already been evaluated recurses into docondval to get the value of
11806: # the condition, then memoizing it to 
11807: #   $env{user.state.<cid>.<condition>}
11808: sub directcondval {
11809:     my $number=shift;
11810:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11811: 	&Apache::lonuserstate::evalstate();
11812:     }
11813:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11814: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11815:     } elsif ($number =~ /^_/) {
11816: 	my $sub_condition;
11817: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11818: 		&GDBM_READER(),0640)) {
11819: 	    $sub_condition=$bighash{'conditions'.$number};
11820: 	    untie(%bighash);
11821: 	}
11822: 	my $value = &docondval($sub_condition);
11823: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11824: 	return $value;
11825:     }
11826:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11827:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11828:     } else {
11829:        return 2;
11830:     }
11831: }
11832: 
11833: # get the collection of conditions for this resource
11834: sub condval {
11835:     my $condidx=shift;
11836:     my $allpathcond='';
11837:     foreach my $cond (split(/\|/,$condidx)) {
11838: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11839: 	    $allpathcond.=
11840: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11841: 	}
11842:     }
11843:     $allpathcond=~s/\|$//;
11844:     return &docondval($allpathcond);
11845: }
11846: 
11847: #evaluates an expression of conditions
11848: sub docondval {
11849:     my ($allpathcond) = @_;
11850:     my $result=0;
11851:     if ($env{'request.course.id'}
11852: 	&& defined($allpathcond)) {
11853: 	my $operand='|';
11854: 	my @stack;
11855: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11856: 	    if ($chunk eq '(') {
11857: 		push @stack,($operand,$result);
11858: 	    } elsif ($chunk eq ')') {
11859: 		my $before=pop @stack;
11860: 		if (pop @stack eq '&') {
11861: 		    $result=$result>$before?$before:$result;
11862: 		} else {
11863: 		    $result=$result>$before?$result:$before;
11864: 		}
11865: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11866: 		$operand=$chunk;
11867: 	    } else {
11868: 		my $new=directcondval($chunk);
11869: 		if ($operand eq '&') {
11870: 		    $result=$result>$new?$new:$result;
11871: 		} else {
11872: 		    $result=$result>$new?$result:$new;
11873: 		}
11874: 	    }
11875: 	}
11876:     }
11877:     return $result;
11878: }
11879: 
11880: # ---------------------------------------------------- Devalidate courseresdata
11881: 
11882: sub devalidatecourseresdata {
11883:     my ($coursenum,$coursedomain)=@_;
11884:     my $hashid=$coursenum.':'.$coursedomain;
11885:     &devalidate_cache_new('courseres',$hashid);
11886: }
11887: 
11888: 
11889: # --------------------------------------------------- Course Resourcedata Query
11890: #
11891: #  Parameters:
11892: #      $coursenum    - Number of the course.
11893: #      $coursedomain - Domain at which the course was created.
11894: #  Returns:
11895: #     A hash of the course parameters along (I think) with timestamps
11896: #     and version info.
11897: 
11898: sub get_courseresdata {
11899:     my ($coursenum,$coursedomain)=@_;
11900:     my $coursehom=&homeserver($coursenum,$coursedomain);
11901:     my $hashid=$coursenum.':'.$coursedomain;
11902:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11903:     my %dumpreply;
11904:     unless (defined($cached)) {
11905: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11906: 	$result=\%dumpreply;
11907: 	my ($tmp) = keys(%dumpreply);
11908: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11909: 	    &do_cache_new('courseres',$hashid,$result,600);
11910: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11911: 	    return $tmp;
11912: 	} elsif ($tmp =~ /^(error)/) {
11913: 	    $result=undef;
11914: 	    &do_cache_new('courseres',$hashid,$result,600);
11915: 	}
11916:     }
11917:     return $result;
11918: }
11919: 
11920: sub devalidateuserresdata {
11921:     my ($uname,$udom)=@_;
11922:     my $hashid="$udom:$uname";
11923:     &devalidate_cache_new('userres',$hashid);
11924: }
11925: 
11926: sub get_userresdata {
11927:     my ($uname,$udom)=@_;
11928:     #most student don\'t have any data set, check if there is some data
11929:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11930: 
11931:     my $hashid="$udom:$uname";
11932:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11933:     if (!defined($cached)) {
11934: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11935: 	$result=\%resourcedata;
11936: 	&do_cache_new('userres',$hashid,$result,600);
11937:     }
11938:     my ($tmp)=keys(%$result);
11939:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11940: 	return $result;
11941:     }
11942:     #error 2 occurs when the .db doesn't exist
11943:     if ($tmp!~/error: 2 /) {
11944:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11945: 	    &logthis("<font color=\"blue\">WARNING:".
11946: 		     " Trying to get resource data for ".
11947: 		     $uname." at ".$udom.": ".
11948: 		     $tmp."</font>");
11949:         }
11950:     } elsif ($tmp=~/error: 2 /) {
11951: 	#&EXT_cache_set($udom,$uname);
11952: 	&do_cache_new('userres',$hashid,undef,600);
11953: 	undef($tmp); # not really an error so don't send it back
11954:     }
11955:     return $tmp;
11956: }
11957: #----------------------------------------------- resdata - return resource data
11958: #  Purpose:
11959: #    Return resource data for either users or for a course.
11960: #  Parameters:
11961: #     $name      - Course/user name.
11962: #     $domain    - Name of the domain the user/course is registered on.
11963: #     $type      - Type of thing $name is (must be 'course' or 'user')
11964: #     $mapp      - decluttered URL of enclosing map  
11965: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11966: #     $recurseup - Ref to array of map URLs, starting with map containing
11967: #                  $mapp up through hierarchy of nested maps to top level map.  
11968: #     $courseid  - CourseID (first part of param identifier).
11969: #     $modifier  - Middle part of param identifier.
11970: #     $what      - Last part of param identifier.
11971: #     @which     - Array of names of resources desired.
11972: #  Returns:
11973: #     The value of the first reasource in @which that is found in the
11974: #     resource hash.
11975: #  Exceptional Conditions:
11976: #     If the $type passed in is not valid (not the string 'course' or 
11977: #     'user', an undefined  reference is returned.
11978: #     If none of the resources are found, an undef is returned
11979: sub resdata {
11980:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11981:         $modifier,$what,@which)=@_;
11982:     my $result;
11983:     if ($type eq 'course') {
11984: 	$result=&get_courseresdata($name,$domain);
11985:     } elsif ($type eq 'user') {
11986: 	$result=&get_userresdata($name,$domain);
11987:     }
11988:     if (!ref($result)) { return $result; }    
11989:     foreach my $item (@which) {
11990:         if ($item->[1] eq 'course') {
11991:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11992:                 unless ($$recursed) {
11993:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11994:                     $$recursed = 1;
11995:                 }
11996:                 foreach my $item (@${recurseup}) {
11997:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11998:                     last if (defined($result->{$norecursechk}));
11999:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12000:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12001:                 }
12002:             }
12003:         }
12004:         if (defined($result->{$item->[0]})) {
12005: 	    return [$result->{$item->[0]},$item->[1]];
12006: 	}
12007:     }
12008:     return undef;
12009: }
12010: 
12011: sub get_domain_lti {
12012:     my ($cdom,$context) = @_;
12013:     my ($name,%lti);
12014:     if ($context eq 'consumer') {
12015:         $name = 'ltitools';
12016:     } elsif ($context eq 'provider') {
12017:         $name = 'lti';
12018:     } else {
12019:         return %lti;
12020:     }
12021:     my ($result,$cached)=&is_cached_new($name,$cdom);
12022:     if (defined($cached)) {
12023:         if (ref($result) eq 'HASH') {
12024:             %lti = %{$result};
12025:         }
12026:     } else {
12027:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12028:         if (ref($domconfig{$name}) eq 'HASH') {
12029:             %lti = %{$domconfig{$name}};
12030:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
12031:             if (ref($encdomconfig{$name}) eq 'HASH') {
12032:                 foreach my $id (keys(%lti)) {
12033:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12034:                         foreach my $item ('key','secret') {
12035:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12036:                         }
12037:                     }
12038:                 }
12039:             }
12040:         }
12041:         my $cachetime = 24*60*60;
12042:         &do_cache_new($name,$cdom,\%lti,$cachetime);
12043:     }
12044:     return %lti;
12045: }
12046: 
12047: sub get_numsuppfiles {
12048:     my ($cnum,$cdom,$ignorecache)=@_;
12049:     my $hashid=$cnum.':'.$cdom;
12050:     my ($suppcount,$cached);
12051:     unless ($ignorecache) {
12052:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12053:     }
12054:     unless (defined($cached)) {
12055:         my $chome=&homeserver($cnum,$cdom);
12056:         unless ($chome eq 'no_host') {
12057:             ($suppcount,my $supptools,my $errors) = (0,0,0);
12058:             my $suppmap = 'supplemental.sequence';
12059:             ($suppcount,$supptools,$errors) =
12060:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12061:                                                          $supptools,$errors);
12062:         }
12063:         &do_cache_new('suppcount',$hashid,$suppcount,600);
12064:     }
12065:     return $suppcount;
12066: }
12067: 
12068: #
12069: # EXT resource caching routines
12070: #
12071: 
12072: {
12073: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12074: #
12075: # The course for which we cache
12076: my $cachedmapkey='';
12077: # The cached recursive maps for this course
12078: my %cachedmaps=();
12079: # When this was last done
12080: my $cachedmaptime='';
12081: 
12082: sub clear_EXT_cache_status {
12083:     &delenv('cache.EXT.');
12084: }
12085: 
12086: sub EXT_cache_status {
12087:     my ($target_domain,$target_user) = @_;
12088:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12089:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12090:         # We know already the user has no data
12091:         return 1;
12092:     } else {
12093:         return 0;
12094:     }
12095: }
12096: 
12097: sub EXT_cache_set {
12098:     my ($target_domain,$target_user) = @_;
12099:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12100:     #&appenv({$cachename => time});
12101: }
12102: 
12103: # --------------------------------------------------------- Value of a Variable
12104: sub EXT {
12105: 
12106:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
12107:     unless ($varname) { return ''; }
12108:     #get real user name/domain, courseid and symb
12109:     my $courseid;
12110:     my $publicuser;
12111:     if ($symbparm) {
12112: 	$symbparm=&get_symb_from_alias($symbparm);
12113:     }
12114:     if (!($uname && $udom)) {
12115:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12116:       if (!$symbparm) {	$symbparm=$cursymb; }
12117:     } else {
12118: 	$courseid=$env{'request.course.id'};
12119:     }
12120:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12121:     my $rest;
12122:     if (defined($therest[0])) {
12123:        $rest=join('.',@therest);
12124:     } else {
12125:        $rest='';
12126:     }
12127: 
12128:     my $qualifierrest=$qualifier;
12129:     if ($rest) { $qualifierrest.='.'.$rest; }
12130:     my $spacequalifierrest=$space;
12131:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12132:     if ($realm eq 'user') {
12133: # --------------------------------------------------------------- user.resource
12134: 	if ($space eq 'resource') {
12135: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12136: 		  || defined($Apache::lonhomework::parsing_a_task))
12137: 		 &&
12138: 		 ($symbparm eq &symbread()) ) {	
12139: 		# if we are in the middle of processing the resource the
12140: 		# get the value we are planning on committing
12141:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12142:                     return $Apache::lonhomework::results{$qualifierrest};
12143:                 } else {
12144:                     return $Apache::lonhomework::history{$qualifierrest};
12145:                 }
12146: 	    } else {
12147: 		my %restored;
12148: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12149: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12150: 		} else {
12151: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12152: 		}
12153: 		return $restored{$qualifierrest};
12154: 	    }
12155: # ----------------------------------------------------------------- user.access
12156:         } elsif ($space eq 'access') {
12157: 	    # FIXME - not supporting calls for a specific user
12158:             return &allowed($qualifier,$rest);
12159: # ------------------------------------------ user.preferences, user.environment
12160:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12161: 	    if (($uname eq $env{'user.name'}) &&
12162: 		($udom eq $env{'user.domain'})) {
12163: 		return $env{join('.',('environment',$qualifierrest))};
12164: 	    } else {
12165: 		my %returnhash;
12166: 		if (!$publicuser) {
12167: 		    %returnhash=&userenvironment($udom,$uname,
12168: 						 $qualifierrest);
12169: 		}
12170: 		return $returnhash{$qualifierrest};
12171: 	    }
12172: # ----------------------------------------------------------------- user.course
12173:         } elsif ($space eq 'course') {
12174: 	    # FIXME - not supporting calls for a specific user
12175:             return $env{join('.',('request.course',$qualifier))};
12176: # ------------------------------------------------------------------- user.role
12177:         } elsif ($space eq 'role') {
12178: 	    # FIXME - not supporting calls for a specific user
12179:             my ($role,$where)=split(/\./,$env{'request.role'});
12180:             if ($qualifier eq 'value') {
12181: 		return $role;
12182:             } elsif ($qualifier eq 'extent') {
12183:                 return $where;
12184:             }
12185: # ----------------------------------------------------------------- user.domain
12186:         } elsif ($space eq 'domain') {
12187:             return $udom;
12188: # ------------------------------------------------------------------- user.name
12189:         } elsif ($space eq 'name') {
12190:             return $uname;
12191: # ---------------------------------------------------- Any other user namespace
12192:         } else {
12193: 	    my %reply;
12194: 	    if (!$publicuser) {
12195: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12196: 	    }
12197: 	    return $reply{$qualifierrest};
12198:         }
12199:     } elsif ($realm eq 'query') {
12200: # ---------------------------------------------- pull stuff out of query string
12201:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12202: 						[$spacequalifierrest]);
12203: 	return $env{'form.'.$spacequalifierrest}; 
12204:    } elsif ($realm eq 'request') {
12205: # ------------------------------------------------------------- request.browser
12206:         if ($space eq 'browser') {
12207:             return $env{'browser.'.$qualifier};
12208: # ------------------------------------------------------------ request.filename
12209:         } else {
12210:             return $env{'request.'.$spacequalifierrest};
12211:         }
12212:     } elsif ($realm eq 'course') {
12213: # ---------------------------------------------------------- course.description
12214:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12215:     } elsif ($realm eq 'resource') {
12216: 
12217: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12218: 	    if (!$symbparm) { $symbparm=&symbread(); }
12219: 	}
12220: 
12221:         if ($qualifier eq '') {
12222: 	    if ($space eq 'title') {
12223: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12224: 	        return &gettitle($symbparm);
12225: 	    }
12226: 	
12227: 	    if ($space eq 'map') {
12228: 	        my ($map) = &decode_symb($symbparm);
12229: 	        return &symbread($map);
12230: 	    }
12231:             if ($space eq 'maptitle') {
12232:                 my ($map) = &decode_symb($symbparm);
12233:                 return &gettitle($map);
12234:             }
12235: 	    if ($space eq 'filename') {
12236: 	        if ($symbparm) {
12237: 		    return &clutter((&decode_symb($symbparm))[2]);
12238: 	        }
12239: 	        return &hreflocation('',$env{'request.filename'});
12240: 	    }
12241: 
12242:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12243:                 if ($space eq 'visibleparts') {
12244:                     my $navmap = Apache::lonnavmaps::navmap->new();
12245:                     my $item;
12246:                     if (ref($navmap)) {
12247:                         my $res = $navmap->getBySymb($symbparm);
12248:                         my $parts = $res->parts();
12249:                         if (ref($parts) eq 'ARRAY') {
12250:                             $item = join(',',@{$parts});
12251:                         }
12252:                         undef($navmap);
12253:                     }
12254:                     return $item;
12255:                 }
12256:             }
12257:         }
12258: 
12259: 	my ($section, $group, @groups, @recurseup, $recursed);
12260: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12261:         if (($courseid eq '') && ($cid)) {
12262:             $courseid = $cid;
12263:         }
12264: 	if (($symbparm && $courseid) && 
12265: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12266: 
12267: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12268: 
12269: # ----------------------------------------------------- Cascading lookup scheme
12270: 	    my $symbp=$symbparm;
12271: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12272: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12273:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12274: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12275: 	    if (($env{'user.name'} eq $uname) &&
12276: 		($env{'user.domain'} eq $udom)) {
12277: 		$section=$env{'request.course.sec'};
12278:                 @groups = split(/:/,$env{'request.course.groups'});  
12279:                 @groups=&sort_course_groups($courseid,@groups); 
12280: 	    } else {
12281: 		if (! defined($usection)) {
12282: 		    $section=&getsection($udom,$uname,$courseid);
12283: 		} else {
12284: 		    $section = $usection;
12285: 		}
12286:                 @groups = &get_users_groups($udom,$uname,$courseid);
12287: 	    }
12288: 
12289: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12290: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12291:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12292: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12293: 
12294: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12295: 	    my $courselevelr=$courseid.'.'.$symbparm;
12296:             $courseleveli=$courseid.'.'.$recurseparm;
12297: 	    $courselevelm=$courseid.'.'.$mapparm;
12298: 
12299: # ----------------------------------------------------------- first, check user
12300: 
12301: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12302:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12303: 				       ([$courselevelr,'resource'],
12304: 					[$courselevelm,'map'     ],
12305:                                         [$courseleveli,'map'     ],
12306: 					[$courselevel, 'course'  ]));
12307: 	    if (defined($userreply)) { return &get_reply($userreply); }
12308: 
12309: # ------------------------------------------------ second, check some of course
12310:             my $coursereply;
12311:             if (@groups > 0) {
12312:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12313:                                        $recurseparm,$mapparm,$spacequalifierrest,
12314:                                        $mapp,\$recursed,\@recurseup);
12315:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12316:             }
12317: 
12318: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12319: 				  $env{'course.'.$courseid.'.domain'},
12320: 				  'course',$mapp,\$recursed,\@recurseup,
12321:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12322: 				  ([$seclevelr,   'resource'],
12323: 				   [$seclevelm,   'map'     ],
12324:                                    [$secleveli,   'map'     ],
12325: 				   [$seclevel,    'course'  ],
12326: 				   [$courselevelr,'resource']));
12327: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12328: 
12329: # ------------------------------------------------------ third, check map parms
12330: 	    my %parmhash=();
12331: 	    my $thisparm='';
12332: 	    if (tie(%parmhash,'GDBM_File',
12333: 		    $env{'request.course.fn'}.'_parms.db',
12334: 		    &GDBM_READER(),0640)) {
12335: 		$thisparm=$parmhash{$symbparm};
12336: 		untie(%parmhash);
12337: 	    }
12338: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12339: 	}
12340: # ------------------------------------------ fourth, look in resource metadata
12341:  
12342:         my $what = $spacequalifierrest;
12343: 	$what=~s/\./\_/;
12344: 	my $filename;
12345: 	if (!$symbparm) { $symbparm=&symbread(); }
12346: 	if ($symbparm) {
12347: 	    $filename=(&decode_symb($symbparm))[2];
12348: 	} else {
12349: 	    $filename=$env{'request.filename'};
12350: 	}
12351:         my $toolsymb;
12352:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12353:             $toolsymb = $symbparm;
12354:         }
12355: 	my $metadata=&metadata($filename,$what,$toolsymb);
12356: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12357: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12358: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12359: 
12360: # ----------------------------------------------- fifth, look in rest of course
12361: 	if ($symbparm && defined($courseid) && 
12362: 	    $courseid eq $env{'request.course.id'}) {
12363: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12364: 				     $env{'course.'.$courseid.'.domain'},
12365: 				     'course',$mapp,\$recursed,\@recurseup,
12366:                                      $courseid,'.',$spacequalifierrest,
12367: 				     ([$courselevelm,'map'   ],
12368:                                       [$courseleveli,'map'   ],
12369: 				      [$courselevel, 'course']));
12370: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12371: 	}
12372: # ------------------------------------------------------------------ Cascade up
12373: 	unless ($space eq '0') {
12374: 	    my @parts=split(/_/,$space);
12375: 	    my $id=pop(@parts);
12376: 	    my $part=join('_',@parts);
12377: 	    if ($part eq '') { $part='0'; }
12378: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12379: 				 $symbparm,$udom,$uname,$section,1);
12380: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12381: 	}
12382: 	if ($recurse) { return undef; }
12383: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12384: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12385: # ---------------------------------------------------- Any other user namespace
12386:     } elsif ($realm eq 'environment') {
12387: # ----------------------------------------------------------------- environment
12388: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12389: 	    return $env{'environment.'.$spacequalifierrest};
12390: 	} else {
12391: 	    if ($uname eq 'anonymous' && $udom eq '') {
12392: 		return '';
12393: 	    }
12394: 	    my %returnhash=&userenvironment($udom,$uname,
12395: 					    $spacequalifierrest);
12396: 	    return $returnhash{$spacequalifierrest};
12397: 	}
12398:     } elsif ($realm eq 'system') {
12399: # ----------------------------------------------------------------- system.time
12400: 	if ($space eq 'time') {
12401: 	    return time;
12402:         }
12403:     } elsif ($realm eq 'server') {
12404: # ----------------------------------------------------------------- system.time
12405: 	if ($space eq 'name') {
12406: 	    return $ENV{'SERVER_NAME'};
12407:         }
12408:     } elsif ($realm eq 'client') {
12409:         if ($space eq 'remote_addr') {
12410:             return $ENV{'REMOTE_ADDR'};
12411:         }
12412:     }
12413:     return '';
12414: }
12415: 
12416: sub get_reply {
12417:     my ($reply_value) = @_;
12418:     if (ref($reply_value) eq 'ARRAY') {
12419:         if (wantarray) {
12420: 	    return @$reply_value;
12421:         }
12422:         return $reply_value->[0];
12423:     } else {
12424:         return $reply_value;
12425:     }
12426: }
12427: 
12428: sub check_group_parms {
12429:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12430:         $recursed,$recurseupref) = @_;
12431:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12432:                   [$what,'course']);
12433:     my $coursereply;
12434:     foreach my $group (@{$groups}) {
12435:         my @groupitems = ();
12436:         foreach my $level (@levels) {
12437:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12438:              push(@groupitems,[$item,$level->[1]]);
12439:         }
12440:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12441:                                    $env{'course.'.$courseid.'.domain'},
12442:                                    'course',$mapp,$recursed,$recurseupref,
12443:                                    $courseid,'.['.$group.'].',$what,
12444:                                    @groupitems);
12445:         last if (defined($coursereply));
12446:     }
12447:     return $coursereply;
12448: }
12449: 
12450: sub get_map_hierarchy {
12451:     my ($mapname,$courseid) = @_;
12452:     my @recurseup = ();
12453:     if ($mapname) {
12454:         if (($cachedmapkey eq $courseid) &&
12455:             (abs($cachedmaptime-time)<5)) {
12456:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12457:                 return @{$cachedmaps{$mapname}};
12458:             }
12459:         }
12460:         my $navmap = Apache::lonnavmaps::navmap->new();
12461:         if (ref($navmap)) {
12462:             @recurseup = $navmap->recurseup_maps($mapname);
12463:             undef($navmap);
12464:             $cachedmaps{$mapname} = \@recurseup;
12465:             $cachedmaptime=time;
12466:             $cachedmapkey=$courseid;
12467:         }
12468:     }
12469:     return @recurseup;
12470: }
12471: 
12472: }
12473: 
12474: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12475:     my ($courseid,@groups) = @_;
12476:     @groups = sort(@groups);
12477:     return @groups;
12478: }
12479: 
12480: sub packages_tab_default {
12481:     my ($uri,$varname,$toolsymb)=@_;
12482:     my (undef,$part,$name)=split(/\./,$varname);
12483: 
12484:     my (@extension,@specifics,$do_default);
12485:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12486: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12487: 	if ($pack_type eq 'default') {
12488: 	    $do_default=1;
12489: 	} elsif ($pack_type eq 'extension') {
12490: 	    push(@extension,[$package,$pack_type,$pack_part]);
12491: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12492: 	    # only look at packages defaults for packages that this id is
12493: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12494: 	}
12495:     }
12496:     # first look for a package that matches the requested part id
12497:     foreach my $package (@specifics) {
12498: 	my (undef,$pack_type,$pack_part)=@{$package};
12499: 	next if ($pack_part ne $part);
12500: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12501: 	    return $packagetab{"$pack_type&$name&default"};
12502: 	}
12503:     }
12504:     # look for any possible matching non extension_ package
12505:     foreach my $package (@specifics) {
12506: 	my (undef,$pack_type,$pack_part)=@{$package};
12507: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12508: 	    return $packagetab{"$pack_type&$name&default"};
12509: 	}
12510: 	if ($pack_type eq 'part') { $pack_part='0'; }
12511: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12512: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12513: 	}
12514:     }
12515:     # look for any posible extension_ match
12516:     foreach my $package (@extension) {
12517: 	my ($package,$pack_type)=@{$package};
12518: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12519: 	    return $packagetab{"$pack_type&$name&default"};
12520: 	}
12521: 	if (defined($packagetab{$package."&$name&default"})) {
12522: 	    return $packagetab{$package."&$name&default"};
12523: 	}
12524:     }
12525:     # look for a global default setting
12526:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12527: 	return $packagetab{"default&$name&default"};
12528:     }
12529:     return undef;
12530: }
12531: 
12532: sub add_prefix_and_part {
12533:     my ($prefix,$part)=@_;
12534:     my $keyroot;
12535:     if (defined($prefix) && $prefix !~ /^__/) {
12536: 	# prefix that has a part already
12537: 	$keyroot=$prefix;
12538:     } elsif (defined($prefix)) {
12539: 	# prefix that is missing a part
12540: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12541:     } else {
12542: 	# no prefix at all
12543: 	if (defined($part)) { $keyroot='_'.$part; }
12544:     }
12545:     return $keyroot;
12546: }
12547: 
12548: # ---------------------------------------------------------------- Get metadata
12549: 
12550: my %metaentry;
12551: my %importedpartids;
12552: my %importedrespids;
12553: sub metadata {
12554:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12555:     $uri=&declutter($uri);
12556:     # if it is a non metadata possible uri return quickly
12557:     if (($uri eq '') || 
12558: 	(($uri =~ m|^/*adm/|) && 
12559: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12560:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12561: 	return undef;
12562:     }
12563:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12564: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12565: 	return undef;
12566:     }
12567:     my $filename=$uri;
12568:     $uri=~s/\.meta$//;
12569: #
12570: # Is the metadata already cached?
12571: # Look at timestamp of caching
12572: # Everything is cached by the main uri, libraries are never directly cached
12573: #
12574:     if (!defined($liburi)) {
12575: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12576: 	if (defined($cached)) { return $result->{':'.$what}; }
12577:     }
12578: 
12579: #
12580: # If the uri is for an external tool the file from
12581: # which metadata should be retrieved depends on whether
12582: # the tool had been configured to be gradable (set in the Course
12583: # Editor or Resource Editor).
12584: #
12585: # If a valid symb has been included as the third arg in the call
12586: # to &metadata() that can be used to retrieve the value of
12587: # parameter_0_gradable set for the resource, and included in the
12588: # uploaded map containing the tool. The value is retrieved via
12589: # &EXT(), if a valid symb is available.  Otherwise the value of
12590: # gradable in the exttool_$marker.db file for the tool instance
12591: # is retrieved via &get().
12592: #
12593: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12594: # hiddenresource and encrypturl (during course initialization)
12595: # the map-level parameter for resource.0.gradable included in the 
12596: # uploaded map containing the tool will not yet have been stored
12597: # in the user_course_parms.db file for the user's session, so in 
12598: # this case fall back to retrieving gradable status from the
12599: # exttool_$marker.db file.
12600: #
12601: # In order to avoid an infinite loop, &metadata() will return
12602: # before a call to &EXT(), if the uri is for an external tool
12603: # and the $what for which metadata is being requested is
12604: # parameter_0_gradable or 0_gradable.
12605: #
12606: 
12607:     if ($uri =~ /ext\.tool$/) {
12608:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12609:             return;
12610:         } else {
12611:             my ($checked,$use_passback);
12612:             if ($toolsymb ne '') {
12613:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12614:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12615:                     $checked = 1;
12616:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12617:                         $use_passback = 1;
12618:                     }
12619:                 }
12620:             }
12621:             unless ($checked) {
12622:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12623:                 $marker=~s/\D//g;
12624:                 if ($marker) {
12625:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12626:                     $use_passback = $toolsettings{'gradable'};
12627:                 }
12628:             }
12629:             if ($use_passback) {
12630:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12631:             } else {
12632:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12633:             }
12634:         }
12635:     }
12636: 
12637:     {
12638: # Imported parts would go here
12639:         my @origfiletagids=();
12640:         my $importedparts=0;
12641: 
12642: # Imported responseids would go here
12643:         my $importedresponses=0;
12644: #
12645: # Is this a recursive call for a library?
12646: #
12647: #	if (! exists($metacache{$uri})) {
12648: #	    $metacache{$uri}={};
12649: #	}
12650: 	my $cachetime = 60*60;
12651:         if ($liburi) {
12652: 	    $liburi=&declutter($liburi);
12653:             $filename=$liburi;
12654:         } else {
12655: 	    &devalidate_cache_new('meta',$uri);
12656: 	    undef(%metaentry);
12657: 	}
12658:         my %metathesekeys=();
12659:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12660: 	my $metastring;
12661: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12662: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12663: 	    $metastring = 
12664: 		&Apache::lonnet::ssi_body($which,
12665: 					  ('grade_target' => 'meta'));
12666: 	    $cachetime = 1; # only want this cached in the child not long term
12667: 	} elsif (($uri !~ m -^(editupload)/-) && 
12668:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12669: 	    my $file=&filelocation('',&clutter($filename));
12670: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12671: 	    $metastring=&getfile($file);
12672: 	}
12673:         my $parser=HTML::LCParser->new(\$metastring);
12674:         my $token;
12675:         undef %metathesekeys;
12676:         while ($token=$parser->get_token) {
12677: 	    if ($token->[0] eq 'S') {
12678: 		if (defined($token->[2]->{'package'})) {
12679: #
12680: # This is a package - get package info
12681: #
12682: 		    my $package=$token->[2]->{'package'};
12683: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12684: 		    if (defined($token->[2]->{'id'})) { 
12685: 			$keyroot.='_'.$token->[2]->{'id'}; 
12686: 		    }
12687: 		    if ($metaentry{':packages'}) {
12688: 			$metaentry{':packages'}.=','.$package.$keyroot;
12689: 		    } else {
12690: 			$metaentry{':packages'}=$package.$keyroot;
12691: 		    }
12692: 		    foreach my $pack_entry (keys(%packagetab)) {
12693: 			my $part=$keyroot;
12694: 			$part=~s/^\_//;
12695: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12696: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12697: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12698: 			    # ignore package.tab specified default values
12699:                             # here &package_tab_default() will fetch those
12700: 			    if ($subp eq 'default') { next; }
12701: 			    my $value=$packagetab{$pack_entry};
12702: 			    my $unikey;
12703: 			    if ($pack =~ /_0$/) {
12704: 				$unikey='parameter_0_'.$name;
12705: 				$part=0;
12706: 			    } else {
12707: 				$unikey='parameter'.$keyroot.'_'.$name;
12708: 			    }
12709: 			    if ($subp eq 'display') {
12710: 				$value.=' [Part: '.$part.']';
12711: 			    }
12712: 			    $metaentry{':'.$unikey.'.part'}=$part;
12713: 			    $metathesekeys{$unikey}=1;
12714: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12715: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12716: 			    }
12717: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12718: 				$metaentry{':'.$unikey}=
12719: 				    $metaentry{':'.$unikey.'.default'};
12720: 			    }
12721: 			}
12722: 		    }
12723: 		} else {
12724: #
12725: # This is not a package - some other kind of start tag
12726: #
12727: 		    my $entry=$token->[1];
12728: 		    my $unikey='';
12729: 
12730: 		    if ($entry eq 'import') {
12731: #
12732: # Importing a library here
12733: #
12734:                         my $location=$parser->get_text('/import');
12735:                         my $dir=$filename;
12736:                         $dir=~s|[^/]*$||;
12737:                         $location=&filelocation($dir,$location);
12738: 
12739:                         my $importid=$token->[2]->{'id'};
12740:                         my $importmode=$token->[2]->{'importmode'};
12741: #
12742: # Check metadata for imported file to
12743: # see if it contained response items
12744: #
12745:                         my ($origfile,@libfilekeys);
12746:                         my %currmetaentry = %metaentry;
12747:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12748:                                                            $depthcount+1));
12749:                         if (grep(/^responseorder$/,@libfilekeys)) {
12750:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12751:                                                              undef,$depthcount+1);
12752:                             if ($libresponseorder ne '') {
12753:                                 if ($#origfiletagids<0) {
12754:                                     undef(%importedrespids);
12755:                                     undef(%importedpartids);
12756:                                 }
12757:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12758:                                 if (@respids) {
12759:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12760:                                 }
12761:                                 if ($importedrespids{$importid} ne '') {
12762:                                     $importedresponses = 1;
12763: # We need to get the original file and the imported file to get the response order correct
12764: # Load and inspect original file
12765:                                     if ($#origfiletagids<0) {
12766:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12767:                                         $origfile=&getfile($origfilelocation);
12768:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12769:                                     }
12770:                                 }
12771:                             }
12772:                         }
12773: # Do not overwrite contents of %metaentry hash for resource itself with 
12774: # hash populated for imported library file
12775:                         %metaentry = %currmetaentry;
12776:                         undef(%currmetaentry);
12777:                         if ($importmode eq 'part') {
12778: # Import as part(s)
12779:                            $importedparts=1;
12780: # We need to get the original file and the imported file to get the part order correct
12781: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12782: # Load and inspect original file if we didn't do that already
12783:                            if ($#origfiletagids<0) {
12784:                                undef(%importedrespids);
12785:                                undef(%importedpartids);
12786:                                if ($origfile eq '') {
12787:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12788:                                    $origfile=&getfile($origfilelocation);
12789:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12790:                                }
12791:                            }
12792:                            my @impfilepartids;
12793: # If <partorder> tag is included in metadata for the imported file
12794: # get the parts in the imported file from that.
12795:                            if (grep(/^partorder$/,@libfilekeys)) {
12796:                                %currmetaentry = %metaentry;
12797:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12798:                                                             $depthcount+1);
12799:                                %metaentry = %currmetaentry;
12800:                                undef(%currmetaentry);
12801:                                if ($libpartorder ne '') {
12802:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12803:                                }
12804:                            } else {
12805: # If no <partorder> tag available, load and inspect imported file
12806:                                my $impfile=&getfile($location);
12807:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12808:                            }
12809:                            if ($#impfilepartids>=0) {
12810: # This problem had parts
12811:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12812:                            } else {
12813: # Importing by turning a single problem into a problem part
12814: # It gets the import-tags ID as part-ID
12815:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12816:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12817:                            }
12818:                         } else {
12819: # Import as problem or as normal import
12820:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12821:                             unless ($importmode eq 'problem') {
12822: # Normal import
12823:                                 if (defined($token->[2]->{'id'})) {
12824:                                     $unikey.='_'.$token->[2]->{'id'};
12825:                                 }
12826:                             }
12827: # Check metadata for imported file to
12828: # see if it contained parts
12829:                             if (grep(/^partorder$/,@libfilekeys)) {
12830:                                 %currmetaentry = %metaentry;
12831:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12832:                                                              $depthcount+1);
12833:                                 %metaentry = %currmetaentry;
12834:                                 undef(%currmetaentry);
12835:                                 if ($libpartorder ne '') {
12836:                                     $importedparts = 1;
12837:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12838:                                 }
12839:                             }
12840:                         }
12841: 			if ($depthcount<20) {
12842: 			    my $metadata = 
12843: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12844: 					  $depthcount+1);
12845: 			    foreach my $meta (split(',',$metadata)) {
12846: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12847: 				$metathesekeys{$meta}=1;
12848: 			    }
12849:                         }
12850: 		    } else {
12851: #
12852: # Not importing, some other kind of non-package, non-library start tag
12853: # 
12854:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12855:                         if (defined($token->[2]->{'id'})) {
12856:                             $unikey.='_'.$token->[2]->{'id'};
12857:                         }
12858: 			if (defined($token->[2]->{'name'})) { 
12859: 			    $unikey.='_'.$token->[2]->{'name'}; 
12860: 			}
12861: 			$metathesekeys{$unikey}=1;
12862: 			foreach my $param (@{$token->[3]}) {
12863: 			    $metaentry{':'.$unikey.'.'.$param} =
12864: 				$token->[2]->{$param};
12865: 			}
12866: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12867: 			my $default=$metaentry{':'.$unikey.'.default'};
12868: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12869: 		 # only ws inside the tag, and not in default, so use default
12870: 		 # as value
12871: 			    $metaentry{':'.$unikey}=$default;
12872: 			} elsif ( $internaltext =~ /\S/ ) {
12873: 		  # something interesting inside the tag
12874: 			    $metaentry{':'.$unikey}=$internaltext;
12875: 			} else {
12876: 		  # no interesting values, don't set a default
12877: 			}
12878: # end of not-a-package not-a-library import
12879: 		    }
12880: # end of not-a-package start tag
12881: 		}
12882: # the next is the end of "start tag"
12883: 	    }
12884: 	}
12885: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12886: 	$extension = lc($extension);
12887: 	if ($extension eq 'htm') { $extension='html'; }
12888: 
12889: 	foreach my $key (keys(%packagetab)) {
12890: 	    #no specific packages #how's our extension
12891: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12892: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12893: 					 \%metathesekeys);
12894: 	}
12895: 
12896: 	if (!exists($metaentry{':packages'})
12897: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12898: 	    foreach my $key (keys(%packagetab)) {
12899: 		#no specific packages well let's get default then
12900: 		if ($key!~/^default&/) { next; }
12901: 		&metadata_create_package_def($uri,$key,'default',
12902: 					     \%metathesekeys);
12903: 	    }
12904: 	}
12905: # are there custom rights to evaluate
12906: 	if ($metaentry{':copyright'} eq 'custom') {
12907: 
12908:     #
12909:     # Importing a rights file here
12910:     #
12911: 	    unless ($depthcount) {
12912: 		my $location=$metaentry{':customdistributionfile'};
12913: 		my $dir=$filename;
12914: 		$dir=~s|[^/]*$||;
12915: 		$location=&filelocation($dir,$location);
12916: 		my $rights_metadata =
12917: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12918: 			      $depthcount+1);
12919: 		foreach my $rights (split(',',$rights_metadata)) {
12920: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12921: 		    $metathesekeys{$rights}=1;
12922: 		}
12923: 	    }
12924: 	}
12925: 	# uniqifiy package listing
12926: 	my %seen;
12927: 	my @uniq_packages =
12928: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12929: 	$metaentry{':packages'} = join(',',@uniq_packages);
12930: 
12931:         if (($importedresponses) || ($importedparts)) {
12932:             if ($importedparts) {
12933: # We had imported parts and need to rebuild partorder
12934:                 $metaentry{':partorder'}='';
12935:                 $metathesekeys{'partorder'}=1;
12936:             }
12937:             if ($importedresponses) {
12938: # We had imported responses and need to rebuil responseorder
12939:                 $metaentry{':responseorder'}='';
12940:                 $metathesekeys{'responseorder'}=1;
12941:             }
12942:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12943:                 my $origid = $origfiletagids[$index+1];
12944:                 if ($origfiletagids[$index] eq 'part') {
12945: # Original part, part of the problem
12946:                     if ($importedparts) {
12947:                         $metaentry{':partorder'}.=','.$origid;
12948:                     }
12949:                 } elsif ($origfiletagids[$index] eq 'import') {
12950:                     if ($importedparts) {
12951: # We have imported parts at this position
12952:                         if ($importedpartids{$origid} ne '') {
12953:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12954:                         }
12955:                     }
12956:                     if ($importedresponses) {
12957: # We have imported responses at this position
12958:                         if ($importedrespids{$origid} ne '') {
12959:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12960:                         }
12961:                     }
12962:                 } else {
12963: # Original response item, part of the problem
12964:                     if ($importedresponses) {
12965:                         $metaentry{':responseorder'}.=','.$origid;
12966:                     }
12967:                 }
12968:             }
12969:             if ($importedparts) {
12970:                 $metaentry{':partorder'}=~s/^\,//;
12971:             }
12972:             if ($importedresponses) {
12973:                 $metaentry{':responseorder'}=~s/^\,//;
12974:             }
12975:         }
12976: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12977: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12978: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12979:         unless ($liburi) {
12980: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12981:         }
12982: # this is the end of "was not already recently cached
12983:     }
12984:     return $metaentry{':'.$what};
12985: }
12986: 
12987: sub metadata_create_package_def {
12988:     my ($uri,$key,$package,$metathesekeys)=@_;
12989:     my ($pack,$name,$subp)=split(/\&/,$key);
12990:     if ($subp eq 'default') { next; }
12991:     
12992:     if (defined($metaentry{':packages'})) {
12993: 	$metaentry{':packages'}.=','.$package;
12994:     } else {
12995: 	$metaentry{':packages'}=$package;
12996:     }
12997:     my $value=$packagetab{$key};
12998:     my $unikey;
12999:     $unikey='parameter_0_'.$name;
13000:     $metaentry{':'.$unikey.'.part'}=0;
13001:     $$metathesekeys{$unikey}=1;
13002:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13003: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13004:     }
13005:     if (defined($metaentry{':'.$unikey.'.default'})) {
13006: 	$metaentry{':'.$unikey}=
13007: 	    $metaentry{':'.$unikey.'.default'};
13008:     }
13009: }
13010: 
13011: sub metadata_generate_part0 {
13012:     my ($metadata,$metacache,$uri) = @_;
13013:     my %allnames;
13014:     foreach my $metakey (keys(%$metadata)) {
13015: 	if ($metakey=~/^parameter\_(.*)/) {
13016: 	  my $part=$$metacache{':'.$metakey.'.part'};
13017: 	  my $name=$$metacache{':'.$metakey.'.name'};
13018: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13019: 	    $allnames{$name}=$part;
13020: 	  }
13021: 	}
13022:     }
13023:     foreach my $name (keys(%allnames)) {
13024:       $$metadata{"parameter_0_$name"}=1;
13025:       my $key=":parameter_0_$name";
13026:       $$metacache{"$key.part"}='0';
13027:       $$metacache{"$key.name"}=$name;
13028:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13029: 					   $allnames{$name}.'_'.$name.
13030: 					   '.type'};
13031:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13032: 			     '.display'};
13033:       my $expr='[Part: '.$allnames{$name}.']';
13034:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13035:       $$metacache{"$key.display"}=$olddis;
13036:     }
13037: }
13038: 
13039: # ------------------------------------------------------ Devalidate title cache
13040: 
13041: sub devalidate_title_cache {
13042:     my ($url)=@_;
13043:     if (!$env{'request.course.id'}) { return; }
13044:     my $symb=&symbread($url);
13045:     if (!$symb) { return; }
13046:     my $key=$env{'request.course.id'}."\0".$symb;
13047:     &devalidate_cache_new('title',$key);
13048: }
13049: 
13050: # ------------------------------------------------- Get the title of a course
13051: 
13052: sub current_course_title {
13053:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13054: }
13055: # ------------------------------------------------- Get the title of a resource
13056: 
13057: sub gettitle {
13058:     my $urlsymb=shift;
13059:     my $symb=&symbread($urlsymb);
13060:     if ($symb) {
13061: 	my $key=$env{'request.course.id'}."\0".$symb;
13062: 	my ($result,$cached)=&is_cached_new('title',$key);
13063: 	if (defined($cached)) { 
13064: 	    return $result;
13065: 	}
13066: 	my ($map,$resid,$url)=&decode_symb($symb);
13067: 	my $title='';
13068: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13069: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13070: 	} else {
13071: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13072: 		    &GDBM_READER(),0640)) {
13073: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13074: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13075: 		untie(%bighash);
13076: 	    }
13077: 	}
13078: 	$title=~s/\&colon\;/\:/gs;
13079: 	if ($title) {
13080: # Remember both $symb and $title for dynamic metadata
13081:             $accesshash{$symb.'___crstitle'}=$title;
13082:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13083: # Cache this title and then return it
13084: 	    return &do_cache_new('title',$key,$title,600);
13085: 	}
13086: 	$urlsymb=$url;
13087:     }
13088:     my $title=&metadata($urlsymb,'title');
13089:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13090:     return $title;
13091: }
13092: 
13093: sub get_slot {
13094:     my ($which,$cnum,$cdom)=@_;
13095:     if (!$cnum || !$cdom) {
13096: 	(undef,my $courseid)=&whichuser();
13097: 	$cdom=$env{'course.'.$courseid.'.domain'};
13098: 	$cnum=$env{'course.'.$courseid.'.num'};
13099:     }
13100:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13101:     my %slotinfo;
13102:     if (exists($remembered{$key})) {
13103: 	$slotinfo{$which} = $remembered{$key};
13104:     } else {
13105: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13106: 	&Apache::lonhomework::showhash(%slotinfo);
13107: 	my ($tmp)=keys(%slotinfo);
13108: 	if ($tmp=~/^error:/) { return (); }
13109: 	$remembered{$key} = $slotinfo{$which};
13110:     }
13111:     if (ref($slotinfo{$which}) eq 'HASH') {
13112: 	return %{$slotinfo{$which}};
13113:     }
13114:     return $slotinfo{$which};
13115: }
13116: 
13117: sub get_reservable_slots {
13118:     my ($cnum,$cdom,$uname,$udom) = @_;
13119:     my $now = time;
13120:     my $reservable_info;
13121:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13122:     if (exists($remembered{$key})) {
13123:         $reservable_info = $remembered{$key};
13124:     } else {
13125:         my %resv;
13126:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13127:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13128:         $reservable_info = \%resv;
13129:         $remembered{$key} = $reservable_info;
13130:     }
13131:     return $reservable_info;
13132: }
13133: 
13134: sub get_course_slots {
13135:     my ($cnum,$cdom) = @_;
13136:     my $hashid=$cnum.':'.$cdom;
13137:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13138:     if (defined($cached)) {
13139:         if (ref($result) eq 'HASH') {
13140:             return %{$result};
13141:         }
13142:     } else {
13143:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13144:         my ($tmp) = keys(%slots);
13145:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13146:             &do_cache_new('allslots',$hashid,\%slots,600);
13147:             return %slots;
13148:         }
13149:     }
13150:     return;
13151: }
13152: 
13153: sub devalidate_slots_cache {
13154:     my ($cnum,$cdom)=@_;
13155:     my $hashid=$cnum.':'.$cdom;
13156:     &devalidate_cache_new('allslots',$hashid);
13157: }
13158: 
13159: sub get_coursechange {
13160:     my ($cdom,$cnum) = @_;
13161:     if ($cdom eq '' || $cnum eq '') {
13162:         return unless ($env{'request.course.id'});
13163:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13164:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13165:     }
13166:     my $hashid=$cdom.'_'.$cnum;
13167:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13168:     if ((defined($cached)) && ($change ne '')) {
13169:         return $change;
13170:     } else {
13171:         my %crshash;
13172:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13173:         if ($crshash{'internal.contentchange'} eq '') {
13174:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13175:             if ($change eq '') {
13176:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13177:                 $change = $crshash{'internal.created'};
13178:             }
13179:         } else {
13180:             $change = $crshash{'internal.contentchange'};
13181:         }
13182:         my $cachetime = 600;
13183:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13184:     }
13185:     return $change;
13186: }
13187: 
13188: sub devalidate_coursechange_cache {
13189:     my ($cnum,$cdom)=@_;
13190:     my $hashid=$cnum.':'.$cdom;
13191:     &devalidate_cache_new('crschange',$hashid);
13192: }
13193: 
13194: # ------------------------------------------------- Update symbolic store links
13195: 
13196: sub symblist {
13197:     my ($mapname,%newhash)=@_;
13198:     $mapname=&deversion(&declutter($mapname));
13199:     my %hash;
13200:     if (($env{'request.course.fn'}) && (%newhash)) {
13201:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13202:                       &GDBM_WRCREAT(),0640)) {
13203: 	    foreach my $url (keys(%newhash)) {
13204: 		next if ($url eq 'last_known'
13205: 			 && $env{'form.no_update_last_known'});
13206: 		$hash{declutter($url)}=&encode_symb($mapname,
13207: 						    $newhash{$url}->[1],
13208: 						    $newhash{$url}->[0]);
13209:             }
13210:             if (untie(%hash)) {
13211: 		return 'ok';
13212:             }
13213:         }
13214:     }
13215:     return 'error';
13216: }
13217: 
13218: # --------------------------------------------------------------- Verify a symb
13219: 
13220: sub symbverify {
13221:     my ($symb,$thisurl,$encstate)=@_;
13222:     my $thisfn=$thisurl;
13223:     $thisfn=&declutter($thisfn);
13224: # direct jump to resource in page or to a sequence - will construct own symbs
13225:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13226: # check URL part
13227:     my ($map,$resid,$url)=&decode_symb($symb);
13228: 
13229:     unless ($url eq $thisfn) { return 0; }
13230: 
13231:     $symb=&symbclean($symb);
13232:     $thisurl=&deversion($thisurl);
13233:     $thisfn=&deversion($thisfn);
13234: 
13235:     my %bighash;
13236:     my $okay=0;
13237: 
13238:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13239:                             &GDBM_READER(),0640)) {
13240:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13241:             $thisurl =~ s/\?.+$//;
13242:             if ($map =~ m{^uploaded/.+\.page$}) {
13243:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13244:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13245:             }
13246:         }
13247:         my $ids;
13248:         if ($map =~ m{^uploaded/.+\.page$}) {
13249:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13250:         } else {
13251:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13252:         }
13253:         unless ($ids) {
13254:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13255:             $ids=$bighash{$idkey};
13256:         }
13257:         if ($ids) {
13258: # ------------------------------------------------------------------- Has ID(s)
13259:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13260:                 $symb =~ s/\?.+$//;
13261:             }
13262: 	    foreach my $id (split(/\,/,$ids)) {
13263: 	       my ($mapid,$resid)=split(/\./,$id);
13264:                if (
13265:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13266:    eq $symb) {
13267:                    if (ref($encstate)) {
13268:                        $$encstate = $bighash{'encrypted_'.$id};
13269:                    }
13270: 		   if (($env{'request.role.adv'}) ||
13271: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13272:                        ($thisurl eq '/adm/navmaps')) {
13273: 		       $okay=1;
13274:                        last;
13275: 		   }
13276: 	       }
13277: 	   }
13278:         }
13279: 	untie(%bighash);
13280:     }
13281:     return $okay;
13282: }
13283: 
13284: # --------------------------------------------------------------- Clean-up symb
13285: 
13286: sub symbclean {
13287:     my $symb=shift;
13288:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13289: # remove version from map
13290:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13291: 
13292: # remove version from URL
13293:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13294: 
13295: # remove wrapper
13296: 
13297:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13298:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13299:     return $symb;
13300: }
13301: 
13302: # ---------------------------------------------- Split symb to find map and url
13303: 
13304: sub encode_symb {
13305:     my ($map,$resid,$url)=@_;
13306:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13307: }
13308: 
13309: sub decode_symb {
13310:     my $symb=shift;
13311:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13312:     my ($map,$resid,$url)=split(/___/,$symb);
13313:     return (&fixversion($map),$resid,&fixversion($url));
13314: }
13315: 
13316: sub fixversion {
13317:     my $fn=shift;
13318:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13319:     my %bighash;
13320:     my $uri=&clutter($fn);
13321:     my $key=$env{'request.course.id'}.'_'.$uri;
13322: # is this cached?
13323:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13324:     if (defined($cached)) { return $result; }
13325: # unfortunately not cached, or expired
13326:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13327: 	    &GDBM_READER(),0640)) {
13328:  	if ($bighash{'version_'.$uri}) {
13329:  	    my $version=$bighash{'version_'.$uri};
13330:  	    unless (($version eq 'mostrecent') || 
13331: 		    ($version==&getversion($uri))) {
13332:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13333:  	    }
13334:  	}
13335:  	untie %bighash;
13336:     }
13337:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13338: }
13339: 
13340: sub deversion {
13341:     my $url=shift;
13342:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13343:     return $url;
13344: }
13345: 
13346: # ------------------------------------------------------ Return symb list entry
13347: 
13348: sub symbread {
13349:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13350:         $ignoresymbdb,$noenccheck)=@_;
13351:     my $cache_str='request.symbread.cached.'.$thisfn;
13352:     if (defined($env{$cache_str})) {
13353:         unless (ref($possibles) eq 'HASH') {
13354:             if ($ignorecachednull) {
13355:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
13356:             } else {
13357:                 return $env{$cache_str};
13358:             }
13359:         }
13360:     }
13361: # no filename provided? try from environment
13362:     unless ($thisfn) {
13363:         if ($env{'request.symb'}) {
13364:             return $env{$cache_str}=&symbclean($env{'request.symb'});
13365: 	}
13366: 	$thisfn=$env{'request.filename'};
13367:     }
13368:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13369: # is that filename actually a symb? Verify, clean, and return
13370:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13371: 	if (&symbverify($thisfn,$1)) {
13372: 	    return $env{$cache_str}=&symbclean($thisfn);
13373: 	}
13374:     }
13375:     $thisfn=declutter($thisfn);
13376:     my %hash;
13377:     my %bighash;
13378:     my $syval='';
13379:     if (($env{'request.course.fn'}) && ($thisfn)) {
13380:         my $targetfn = $thisfn;
13381:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13382:             $targetfn = 'adm/wrapper/'.$thisfn;
13383:         }
13384: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13385: 	    $targetfn=$1;
13386: 	}
13387:         unless ($ignoresymbdb) {
13388:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13389:                           &GDBM_READER(),0640)) {
13390: 	        $syval=$hash{$targetfn};
13391:                 untie(%hash);
13392:             }
13393:             if ($syval && $checkforblock) {
13394:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13395:                 if (@blockers) {
13396:                     $syval='';
13397:                 }
13398:             }
13399:         }
13400: # ---------------------------------------------------------- There was an entry
13401:         if ($syval) {
13402: 	    #unless ($syval=~/\_\d+$/) {
13403: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13404: 		    #&appenv({'request.ambiguous' => $thisfn});
13405: 		    #return $env{$cache_str}='';
13406: 		#}    
13407: 		#$syval.=$1;
13408: 	    #}
13409:         } else {
13410: # ------------------------------------------------------- Was not in symb table
13411:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13412:                             &GDBM_READER(),0640)) {
13413: # ---------------------------------------------- Get ID(s) for current resource
13414:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13415:               unless ($ids) { 
13416:                  $ids=$bighash{'ids_/'.$thisfn};
13417:               }
13418:               unless ($ids) {
13419: # alias?
13420: 		  $ids=$bighash{'mapalias_'.$thisfn};
13421:               }
13422:               if ($ids) {
13423: # ------------------------------------------------------------------- Has ID(s)
13424:                  my @possibilities=split(/\,/,$ids);
13425:                  if ($#possibilities==0) {
13426: # ----------------------------------------------- There is only one possibility
13427: 		     my ($mapid,$resid)=split(/\./,$ids);
13428: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13429: 						    $resid,$thisfn);
13430:                      if (ref($possibles) eq 'HASH') {
13431:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13432:                              $possibles->{$syval} = 1;
13433:                          }
13434:                      }
13435:                      if ($checkforblock) {
13436:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13437:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13438:                              if (@blockers) {
13439:                                  $syval = '';
13440:                                  untie(%bighash);
13441:                                  return $env{$cache_str}='';
13442:                              }
13443:                          }
13444:                      }
13445:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13446: # ------------------------------------------ There is more than one possibility
13447:                      my $realpossible=0;
13448:                      foreach my $id (@possibilities) {
13449: 			 my $file=$bighash{'src_'.$id};
13450:                          my $canaccess;
13451:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13452:                              $canaccess = 1;
13453:                          } else { 
13454:                              $canaccess = &allowed('bre',$file);
13455:                          }
13456:                          if ($canaccess) {
13457:          		     my ($mapid,$resid)=split(/\./,$id);
13458:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13459:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13460: 						             $resid,$thisfn);
13461:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13462:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13463:                                  if ($checkforblock) {
13464:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13465:                                      if (@blockers > 0) {
13466:                                          $syval = '';
13467:                                      } else {
13468:                                          $syval = $poss_syval;
13469:                                          $realpossible++;
13470:                                      }
13471:                                  } else {
13472:                                      $syval = $poss_syval;
13473:                                      $realpossible++;
13474:                                  }
13475:                                  if ($syval) {
13476:                                      if (ref($possibles) eq 'HASH') {
13477:                                          $possibles->{$syval} = 1;
13478:                                      }
13479:                                  }
13480:                              }
13481: 			 }
13482:                      }
13483: 		     if ($realpossible!=1) { $syval=''; }
13484:                  } else {
13485:                      $syval='';
13486:                  }
13487: 	      }
13488:               untie(%bighash);
13489:            }
13490:         }
13491:         if ($syval) {
13492: 	    return $env{$cache_str}=$syval;
13493:         }
13494:     }
13495:     &appenv({'request.ambiguous' => $thisfn});
13496:     return $env{$cache_str}='';
13497: }
13498: 
13499: # ---------------------------------------------------------- Return random seed
13500: 
13501: sub numval {
13502:     my $txt=shift;
13503:     $txt=~tr/A-J/0-9/;
13504:     $txt=~tr/a-j/0-9/;
13505:     $txt=~tr/K-T/0-9/;
13506:     $txt=~tr/k-t/0-9/;
13507:     $txt=~tr/U-Z/0-5/;
13508:     $txt=~tr/u-z/0-5/;
13509:     $txt=~s/\D//g;
13510:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13511:     return int($txt);
13512: }
13513: 
13514: sub numval2 {
13515:     my $txt=shift;
13516:     $txt=~tr/A-J/0-9/;
13517:     $txt=~tr/a-j/0-9/;
13518:     $txt=~tr/K-T/0-9/;
13519:     $txt=~tr/k-t/0-9/;
13520:     $txt=~tr/U-Z/0-5/;
13521:     $txt=~tr/u-z/0-5/;
13522:     $txt=~s/\D//g;
13523:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13524:     my $total;
13525:     foreach my $val (@txts) { $total+=$val; }
13526:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13527:     return int($total);
13528: }
13529: 
13530: sub numval3 {
13531:     use integer;
13532:     my $txt=shift;
13533:     $txt=~tr/A-J/0-9/;
13534:     $txt=~tr/a-j/0-9/;
13535:     $txt=~tr/K-T/0-9/;
13536:     $txt=~tr/k-t/0-9/;
13537:     $txt=~tr/U-Z/0-5/;
13538:     $txt=~tr/u-z/0-5/;
13539:     $txt=~s/\D//g;
13540:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13541:     my $total;
13542:     foreach my $val (@txts) { $total+=$val; }
13543:     if ($_64bit) { $total=(($total<<32)>>32); }
13544:     return $total;
13545: }
13546: 
13547: sub digest {
13548:     my ($data)=@_;
13549:     my $digest=&Digest::MD5::md5($data);
13550:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13551:     my ($e,$f);
13552:     {
13553:         use integer;
13554:         $e=($a+$b);
13555:         $f=($c+$d);
13556:         if ($_64bit) {
13557:             $e=(($e<<32)>>32);
13558:             $f=(($f<<32)>>32);
13559:         }
13560:     }
13561:     if (wantarray) {
13562: 	return ($e,$f);
13563:     } else {
13564: 	my $g;
13565: 	{
13566: 	    use integer;
13567: 	    $g=($e+$f);
13568: 	    if ($_64bit) {
13569: 		$g=(($g<<32)>>32);
13570: 	    }
13571: 	}
13572: 	return $g;
13573:     }
13574: }
13575: 
13576: sub latest_rnd_algorithm_id {
13577:     return '64bit5';
13578: }
13579: 
13580: sub get_rand_alg {
13581:     my ($courseid)=@_;
13582:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13583:     if ($courseid) {
13584: 	return $env{"course.$courseid.rndseed"};
13585:     }
13586:     return &latest_rnd_algorithm_id();
13587: }
13588: 
13589: sub validCODE {
13590:     my ($CODE)=@_;
13591:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13592:     return 0;
13593: }
13594: 
13595: sub getCODE {
13596:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13597:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13598: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13599: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13600: 	return $Apache::lonhomework::history{'resource.CODE'};
13601:     }
13602:     return undef;
13603: }
13604: #
13605: #  Determines the random seed for a specific context:
13606: #
13607: # parameters:
13608: #   symb      - in course context the symb for the seed.
13609: #   course_id - The course id of the form domain_coursenum.
13610: #   domain    - Domain for the user.
13611: #   course    - Course for the user.
13612: #   cenv      - environment of the course.
13613: #
13614: # NOTE:
13615: #   All parameters are picked out of the environment if missing
13616: #   or not defined.
13617: #   If a symb cannot be determined the current time is used instead.
13618: #
13619: #  For a given well defined symb, courside, domain, username,
13620: #  and course environment, the seed is reproducible.
13621: #
13622: sub rndseed {
13623:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13624:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13625:     if (!defined($symb)) {
13626: 	unless ($symb=$wsymb) { return time; }
13627:     }
13628:     if (!defined $courseid) { 
13629: 	$courseid=$wcourseid; 
13630:     }
13631:     if (!defined $domain) { $domain=$wdomain; }
13632:     if (!defined $username) { $username=$wusername }
13633: 
13634:     my $which;
13635:     if (defined($cenv->{'rndseed'})) {
13636: 	$which = $cenv->{'rndseed'};
13637:     } else {
13638: 	$which =&get_rand_alg($courseid);
13639:     }
13640:     if (defined(&getCODE())) {
13641: 
13642: 	if ($which eq '64bit5') {
13643: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13644: 	} elsif ($which eq '64bit4') {
13645: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13646: 	} else {
13647: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13648: 	}
13649:     } elsif ($which eq '64bit5') {
13650: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13651:     } elsif ($which eq '64bit4') {
13652: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13653:     } elsif ($which eq '64bit3') {
13654: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13655:     } elsif ($which eq '64bit2') {
13656: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13657:     } elsif ($which eq '64bit') {
13658: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13659:     }
13660:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13661: }
13662: 
13663: sub rndseed_32bit {
13664:     my ($symb,$courseid,$domain,$username)=@_;
13665:     {
13666: 	use integer;
13667: 	my $symbchck=unpack("%32C*",$symb) << 27;
13668: 	my $symbseed=numval($symb) << 22;
13669: 	my $namechck=unpack("%32C*",$username) << 17;
13670: 	my $nameseed=numval($username) << 12;
13671: 	my $domainseed=unpack("%32C*",$domain) << 7;
13672: 	my $courseseed=unpack("%32C*",$courseid);
13673: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13674: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13675: 	#&logthis("rndseed :$num:$symb");
13676: 	if ($_64bit) { $num=(($num<<32)>>32); }
13677: 	return $num;
13678:     }
13679: }
13680: 
13681: sub rndseed_64bit {
13682:     my ($symb,$courseid,$domain,$username)=@_;
13683:     {
13684: 	use integer;
13685: 	my $symbchck=unpack("%32S*",$symb) << 21;
13686: 	my $symbseed=numval($symb) << 10;
13687: 	my $namechck=unpack("%32S*",$username);
13688: 	
13689: 	my $nameseed=numval($username) << 21;
13690: 	my $domainseed=unpack("%32S*",$domain) << 10;
13691: 	my $courseseed=unpack("%32S*",$courseid);
13692: 	
13693: 	my $num1=$symbchck+$symbseed+$namechck;
13694: 	my $num2=$nameseed+$domainseed+$courseseed;
13695: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13696: 	#&logthis("rndseed :$num:$symb");
13697: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13698: 	return "$num1,$num2";
13699:     }
13700: }
13701: 
13702: sub rndseed_64bit2 {
13703:     my ($symb,$courseid,$domain,$username)=@_;
13704:     {
13705: 	use integer;
13706: 	# strings need to be an even # of cahracters long, it it is odd the
13707:         # last characters gets thrown away
13708: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13709: 	my $symbseed=numval($symb) << 10;
13710: 	my $namechck=unpack("%32S*",$username.' ');
13711: 	
13712: 	my $nameseed=numval($username) << 21;
13713: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13714: 	my $courseseed=unpack("%32S*",$courseid.' ');
13715: 	
13716: 	my $num1=$symbchck+$symbseed+$namechck;
13717: 	my $num2=$nameseed+$domainseed+$courseseed;
13718: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13719: 	#&logthis("rndseed :$num:$symb");
13720: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13721: 	return "$num1,$num2";
13722:     }
13723: }
13724: 
13725: sub rndseed_64bit3 {
13726:     my ($symb,$courseid,$domain,$username)=@_;
13727:     {
13728: 	use integer;
13729: 	# strings need to be an even # of cahracters long, it it is odd the
13730:         # last characters gets thrown away
13731: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13732: 	my $symbseed=numval2($symb) << 10;
13733: 	my $namechck=unpack("%32S*",$username.' ');
13734: 	
13735: 	my $nameseed=numval2($username) << 21;
13736: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13737: 	my $courseseed=unpack("%32S*",$courseid.' ');
13738: 	
13739: 	my $num1=$symbchck+$symbseed+$namechck;
13740: 	my $num2=$nameseed+$domainseed+$courseseed;
13741: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13742: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13743: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13744: 	
13745: 	return "$num1:$num2";
13746:     }
13747: }
13748: 
13749: sub rndseed_64bit4 {
13750:     my ($symb,$courseid,$domain,$username)=@_;
13751:     {
13752: 	use integer;
13753: 	# strings need to be an even # of cahracters long, it it is odd the
13754:         # last characters gets thrown away
13755: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13756: 	my $symbseed=numval3($symb) << 10;
13757: 	my $namechck=unpack("%32S*",$username.' ');
13758: 	
13759: 	my $nameseed=numval3($username) << 21;
13760: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13761: 	my $courseseed=unpack("%32S*",$courseid.' ');
13762: 	
13763: 	my $num1=$symbchck+$symbseed+$namechck;
13764: 	my $num2=$nameseed+$domainseed+$courseseed;
13765: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13766: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13767: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13768: 	
13769: 	return "$num1:$num2";
13770:     }
13771: }
13772: 
13773: sub rndseed_64bit5 {
13774:     my ($symb,$courseid,$domain,$username)=@_;
13775:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13776:     return "$num1:$num2";
13777: }
13778: 
13779: sub rndseed_CODE_64bit {
13780:     my ($symb,$courseid,$domain,$username)=@_;
13781:     {
13782: 	use integer;
13783: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13784: 	my $symbseed=numval2($symb);
13785: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13786: 	my $CODEseed=numval(&getCODE());
13787: 	my $courseseed=unpack("%32S*",$courseid.' ');
13788: 	my $num1=$symbseed+$CODEchck;
13789: 	my $num2=$CODEseed+$courseseed+$symbchck;
13790: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13791: 	#&logthis("rndseed :$num1:$num2:$symb");
13792: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13793: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13794: 	return "$num1:$num2";
13795:     }
13796: }
13797: 
13798: sub rndseed_CODE_64bit4 {
13799:     my ($symb,$courseid,$domain,$username)=@_;
13800:     {
13801: 	use integer;
13802: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13803: 	my $symbseed=numval3($symb);
13804: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13805: 	my $CODEseed=numval3(&getCODE());
13806: 	my $courseseed=unpack("%32S*",$courseid.' ');
13807: 	my $num1=$symbseed+$CODEchck;
13808: 	my $num2=$CODEseed+$courseseed+$symbchck;
13809: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13810: 	#&logthis("rndseed :$num1:$num2:$symb");
13811: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13812: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13813: 	return "$num1:$num2";
13814:     }
13815: }
13816: 
13817: sub rndseed_CODE_64bit5 {
13818:     my ($symb,$courseid,$domain,$username)=@_;
13819:     my $code = &getCODE();
13820:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13821:     return "$num1:$num2";
13822: }
13823: 
13824: sub setup_random_from_rndseed {
13825:     my ($rndseed)=@_;
13826:     if ($rndseed =~/([,:])/) {
13827:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13828:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13829:             &Math::Random::random_set_seed_from_phrase($rndseed);
13830:         } else {
13831:             &Math::Random::random_set_seed($num1,$num2);
13832:         }
13833:     } else {
13834: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13835:     }
13836: }
13837: 
13838: sub latest_receipt_algorithm_id {
13839:     return 'receipt3';
13840: }
13841: 
13842: sub recunique {
13843:     my $fucourseid=shift;
13844:     my $unique;
13845:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13846: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13847: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13848:     } else {
13849: 	$unique=$perlvar{'lonReceipt'};
13850:     }
13851:     return unpack("%32C*",$unique);
13852: }
13853: 
13854: sub recprefix {
13855:     my $fucourseid=shift;
13856:     my $prefix;
13857:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13858: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13859: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13860:     } else {
13861: 	$prefix=$perlvar{'lonHostID'};
13862:     }
13863:     return unpack("%32C*",$prefix);
13864: }
13865: 
13866: sub ireceipt {
13867:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13868: 
13869:     my $return =&recprefix($fucourseid).'-';
13870: 
13871:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13872: 	$env{'request.state'} eq 'construct') {
13873: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13874: 	return $return;
13875:     }
13876: 
13877:     my $cuname=unpack("%32C*",$funame);
13878:     my $cudom=unpack("%32C*",$fudom);
13879:     my $cucourseid=unpack("%32C*",$fucourseid);
13880:     my $cusymb=unpack("%32C*",$fusymb);
13881:     my $cunique=&recunique($fucourseid);
13882:     my $cpart=unpack("%32S*",$part);
13883:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13884: 
13885: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13886: 			       
13887: 	$return.= ($cunique%$cuname+
13888: 		   $cunique%$cudom+
13889: 		   $cusymb%$cuname+
13890: 		   $cusymb%$cudom+
13891: 		   $cucourseid%$cuname+
13892: 		   $cucourseid%$cudom+
13893: 		   $cpart%$cuname+
13894: 		   $cpart%$cudom);
13895:     } else {
13896: 	$return.= ($cunique%$cuname+
13897: 		   $cunique%$cudom+
13898: 		   $cusymb%$cuname+
13899: 		   $cusymb%$cudom+
13900: 		   $cucourseid%$cuname+
13901: 		   $cucourseid%$cudom);
13902:     }
13903:     return $return;
13904: }
13905: 
13906: sub receipt {
13907:     my ($part)=@_;
13908:     my ($symb,$courseid,$domain,$name) = &whichuser();
13909:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13910: }
13911: 
13912: sub whichuser {
13913:     my ($passedsymb)=@_;
13914:     my ($symb,$courseid,$domain,$name,$publicuser);
13915:     if (defined($env{'form.grade_symb'})) {
13916: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13917: 	my $allowed=&allowed('vgr',$tmp_courseid);
13918: 	if (!$allowed &&
13919: 	    exists($env{'request.course.sec'}) &&
13920: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13921: 	    $allowed=&allowed('vgr',$tmp_courseid.
13922: 			      '/'.$env{'request.course.sec'});
13923: 	}
13924: 	if ($allowed) {
13925: 	    ($symb)=&get_env_multiple('form.grade_symb');
13926: 	    $courseid=$tmp_courseid;
13927: 	    ($domain)=&get_env_multiple('form.grade_domain');
13928: 	    ($name)=&get_env_multiple('form.grade_username');
13929: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13930: 	}
13931:     }
13932:     if (!$passedsymb) {
13933: 	$symb=&symbread();
13934:     } else {
13935: 	$symb=$passedsymb;
13936:     }
13937:     $courseid=$env{'request.course.id'};
13938:     $domain=$env{'user.domain'};
13939:     $name=$env{'user.name'};
13940:     if ($name eq 'public' && $domain eq 'public') {
13941: 	if (!defined($env{'form.username'})) {
13942: 	    $env{'form.username'}.=time.rand(10000000);
13943: 	}
13944: 	$name.=$env{'form.username'};
13945:     }
13946:     return ($symb,$courseid,$domain,$name,$publicuser);
13947: 
13948: }
13949: 
13950: # ------------------------------------------------------------ Serves up a file
13951: # returns either the contents of the file or 
13952: # -1 if the file doesn't exist
13953: #
13954: # if the target is a file that was uploaded via DOCS, 
13955: # a check will be made to see if a current copy exists on the local server,
13956: # if it does this will be served, otherwise a copy will be retrieved from
13957: # the home server for the course and stored in /home/httpd/html/userfiles on
13958: # the local server.   
13959: 
13960: sub getfile {
13961:     my ($file) = @_;
13962:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13963:     &repcopy($file);
13964:     return &readfile($file);
13965: }
13966: 
13967: sub repcopy_userfile {
13968:     my ($file)=@_;
13969:     my $londocroot = $perlvar{'lonDocRoot'};
13970:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13971:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13972:     my ($cdom,$cnum,$filename) = 
13973: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13974:     my $uri="/uploaded/$cdom/$cnum/$filename";
13975:     if (-e "$file") {
13976: # we already have a local copy, check it out
13977: 	my @fileinfo = stat($file);
13978: 	my $rtncode;
13979: 	my $info;
13980: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13981: 	if ($lwpresp ne 'ok') {
13982: # there is no such file anymore, even though we had a local copy
13983: 	    if ($rtncode eq '404') {
13984: 		unlink($file);
13985: 	    }
13986: 	    return -1;
13987: 	}
13988: 	if ($info < $fileinfo[9]) {
13989: # nice, the file we have is up-to-date, just say okay
13990: 	    return 'ok';
13991: 	} else {
13992: # the file is outdated, get rid of it
13993: 	    unlink($file);
13994: 	}
13995:     }
13996: # one way or the other, at this point, we don't have the file
13997: # construct the correct path for the file
13998:     my @parts = ($cdom,$cnum); 
13999:     if ($filename =~ m|^(.+)/[^/]+$|) {
14000: 	push @parts, split(/\//,$1);
14001:     }
14002:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14003:     foreach my $part (@parts) {
14004: 	$path .= '/'.$part;
14005: 	if (!-e $path) {
14006: 	    mkdir($path,0770);
14007: 	}
14008:     }
14009: # now the path exists for sure
14010: # get a user agent
14011:     my $transferfile=$file.'.in.transfer';
14012: # FIXME: this should flock
14013:     if (-e $transferfile) { return 'ok'; }
14014:     my $request;
14015:     $uri=~s/^\///;
14016:     my $homeserver = &homeserver($cnum,$cdom);
14017:     my $hostname = &hostname($homeserver);
14018:     my $protocol = $protocol{$homeserver};
14019:     $protocol = 'http' if ($protocol ne 'https');
14020:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14021:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14022: # did it work?
14023:     if ($response->is_error()) {
14024: 	unlink($transferfile);
14025: 	&logthis("Userfile repcopy failed for $uri");
14026: 	return -1;
14027:     }
14028: # worked, rename the transfer file
14029:     rename($transferfile,$file);
14030:     return 'ok';
14031: }
14032: 
14033: sub tokenwrapper {
14034:     my $uri=shift;
14035:     $uri=~s|^https?\://([^/]+)||;
14036:     $uri=~s|^/||;
14037:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14038:     my $token=$1;
14039:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14040:     if ($udom && $uname && $file) {
14041: 	$file=~s|(\?\.*)*$||;
14042:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14043:         my $homeserver = &homeserver($uname,$udom);
14044:         my $hostname = &hostname($homeserver);
14045:         my $protocol = $protocol{$homeserver};
14046:         $protocol = 'http' if ($protocol ne 'https');
14047:         return $protocol.'://'.$hostname.'/'.$uri.
14048:                (($uri=~/\?/)?'&':'?').'token='.$token.
14049:                                '&tokenissued='.$perlvar{'lonHostID'};
14050:     } else {
14051:         return '/adm/notfound.html';
14052:     }
14053: }
14054: 
14055: # call with reqtype HEAD: get last modification time
14056: # call with reqtype GET: get the file contents
14057: # Do not call this with reqtype GET for large files! It loads everything into memory
14058: #
14059: sub getuploaded {
14060:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14061:     $uri=~s/^\///;
14062:     my $homeserver = &homeserver($cnum,$cdom);
14063:     my $hostname = &hostname($homeserver);
14064:     my $protocol = $protocol{$homeserver};
14065:     $protocol = 'http' if ($protocol ne 'https');
14066:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14067:     my $request=new HTTP::Request($reqtype,$uri);
14068:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14069:     $$rtncode = $response->code;
14070:     if (! $response->is_success()) {
14071: 	return 'failed';
14072:     }      
14073:     if ($reqtype eq 'HEAD') {
14074: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14075:     } elsif ($reqtype eq 'GET') {
14076: 	$$info = $response->content;
14077:     }
14078:     return 'ok';
14079: }
14080: 
14081: sub readfile {
14082:     my $file = shift;
14083:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14084:     my $fh;
14085:     open($fh,"<",$file);
14086:     my $a='';
14087:     while (my $line = <$fh>) { $a .= $line; }
14088:     return $a;
14089: }
14090: 
14091: sub filelocation {
14092:     my ($dir,$file) = @_;
14093:     my $location;
14094:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14095: 
14096:     if ($file =~ m-^/adm/-) {
14097: 	$file=~s-^/adm/wrapper/-/-;
14098: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14099:     }
14100: 
14101:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14102:         $location = $file;
14103:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14104:         my ($udom,$uname,$filename)=
14105:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14106:         my $home=&homeserver($uname,$udom);
14107:         my $is_me=0;
14108:         my @ids=&current_machine_ids();
14109:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14110:         if ($is_me) {
14111:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14112:         } else {
14113:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14114:   	      $udom.'/'.$uname.'/'.$filename;
14115:         }
14116:     } elsif ($file =~ m-^/adm/-) {
14117: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14118:     } else {
14119:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14120:         $file=~s:^/(res|priv)/:/:;
14121:         my $space=$1;
14122:         if ( !( $file =~ m:^/:) ) {
14123:             $location = $dir. '/'.$file;
14124:         } else {
14125:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14126:         }
14127:     }
14128:     $location=~s://+:/:g; # remove duplicate /
14129:     while ($location=~m{/\.\./}) {
14130: 	if ($location =~ m{/[^/]+/\.\./}) {
14131: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14132: 	} else {
14133: 	    $location=~ s{/\.\./}{/}g;
14134: 	}
14135:     } #remove dir/..
14136:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14137:     return $location;
14138: }
14139: 
14140: sub hreflocation {
14141:     my ($dir,$file)=@_;
14142:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14143: 	$file=filelocation($dir,$file);
14144:     } elsif ($file=~m-^/adm/-) {
14145: 	$file=~s-^/adm/wrapper/-/-;
14146: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14147:     }
14148:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14149: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14150:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14151: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14152: 	        {/uploaded/$1/$2/}x;
14153:     }
14154:     if ($file=~ m{^/userfiles/}) {
14155: 	$file =~ s{^/userfiles/}{/uploaded/};
14156:     }
14157:     return $file;
14158: }
14159: 
14160: 
14161: 
14162: 
14163: 
14164: sub current_machine_domains {
14165:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14166: }
14167: 
14168: sub machine_domains {
14169:     my ($hostname) = @_;
14170:     my @domains;
14171:     my %hostname = &all_hostnames();
14172:     while( my($id, $name) = each(%hostname)) {
14173: #	&logthis("-$id-$name-$hostname-");
14174: 	if ($hostname eq $name) {
14175: 	    push(@domains,&host_domain($id));
14176: 	}
14177:     }
14178:     return @domains;
14179: }
14180: 
14181: sub current_machine_ids {
14182:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14183: }
14184: 
14185: sub machine_ids {
14186:     my ($hostname) = @_;
14187:     $hostname ||= &hostname($perlvar{'lonHostID'});
14188:     my @ids;
14189:     my %name_to_host = &all_names();
14190:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14191: 	return @{ $name_to_host{$hostname} };
14192:     }
14193:     return;
14194: }
14195: 
14196: sub additional_machine_domains {
14197:     my @domains;
14198:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
14199:     while( my $line = <$fh>) {
14200:         $line =~ s/\s//g;
14201:         push(@domains,$line);
14202:     }
14203:     return @domains;
14204: }
14205: 
14206: sub default_login_domain {
14207:     my $domain = $perlvar{'lonDefDomain'};
14208:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14209:     foreach my $posdom (&current_machine_domains(),
14210:                         &additional_machine_domains()) {
14211:         if (lc($posdom) eq lc($testdomain)) {
14212:             $domain=$posdom;
14213:             last;
14214:         }
14215:     }
14216:     return $domain;
14217: }
14218: 
14219: sub shared_institution {
14220:     my ($dom) = @_;
14221:     my $same_intdom;
14222:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
14223:     if ($hostintdom ne '') {
14224:         my %iphost = &get_iphost();
14225:         my $primary_id = &domain($dom,'primary');
14226:         my $primary_ip = &get_host_ip($primary_id);
14227:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14228:             foreach my $id (@{$iphost{$primary_ip}}) {
14229:                 my $intdom = &internet_dom($id);
14230:                 if ($intdom eq $hostintdom) {
14231:                     $same_intdom = 1;
14232:                     last;
14233:                 }
14234:             }
14235:         }
14236:     }
14237:     return $same_intdom;
14238: }
14239: 
14240: sub uses_sts {
14241:     my ($ignore_cache) = @_;
14242:     my $lonhost = $perlvar{'lonHostID'};
14243:     my $hostname = &hostname($lonhost);
14244:     my $sts_on;
14245:     if ($protocol{$lonhost} eq 'https') {
14246:         my $cachetime = 12*3600;
14247:         if (!$ignore_cache) {
14248:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14249:             if (defined($cached)) {
14250:                 return $sts_on;
14251:             }
14252:         }
14253:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14254:         my $request=new HTTP::Request('HEAD',$url);
14255:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14256:         if ($response->is_success) {
14257:             my $has_sts = $response->header('Strict-Transport-Security');
14258:             if ($has_sts eq '') {
14259:                 $sts_on = 0;
14260:             } else {
14261:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14262:                     my $maxage = $1;
14263:                     if ($maxage) {
14264:                         $sts_on = 1;
14265:                     } else {
14266:                         $sts_on = 0;
14267:                     }
14268:                 } else {
14269:                     $sts_on = 0;
14270:                 }
14271:             }
14272:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14273:         }
14274:     }
14275:     return;
14276: }
14277: 
14278: sub get_requestor_ip {
14279:     my ($r,$nolookup,$noproxy) = @_;
14280:     my $from_ip;
14281:     if (ref($r)) {
14282:         $from_ip = $r->get_remote_host($nolookup);
14283:     } else {
14284:         $from_ip = $ENV{'REMOTE_ADDR'};
14285:     }
14286:     return $from_ip if ($noproxy); 
14287:     # Who controls proxy settings for server
14288:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14289:     my $proxyinfo = &get_proxy_settings($dom_in_use);
14290:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14291:         if ($proxyinfo->{'exempt'}) {
14292:             if (&ip_match($from_ip,$proxyinfo->{'exempt'})) {
14293:                 return $from_ip;
14294:             }
14295:         }
14296:         if ($proxyinfo->{'trusted'}) {
14297:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14298:                 my $ipheader = $proxyinfo->{'ipheader'};
14299:                 my ($ip,$xfor);
14300:                 if (ref($r)) {
14301:                     if ($ipheader) {
14302:                         $ip = $r->headers_in->{$ipheader};
14303:                     }
14304:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
14305:                 } else {
14306:                     if ($ipheader) {
14307:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
14308:                     }
14309:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14310:                 }
14311:                 if (($ip eq '') && ($xfor ne '')) {
14312:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14313:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14314:                             $ip = $poss_ip;
14315:                             last;
14316:                         }
14317:                     }
14318:                 }
14319:                 if ($ip ne '') {
14320:                     return $ip;
14321:                 }
14322:             }
14323:         }
14324:     }
14325:     return $from_ip;
14326: }
14327: 
14328: sub get_proxy_settings {
14329:     my ($dom_in_use) = @_;
14330:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14331:     my $proxyinfo = {
14332:                        ipheader => $domdefaults{'waf_ipheader'},
14333:                        trusted  => $domdefaults{'waf_trusted'},
14334:                        exempt   => $domdefaults{'waf_exempt'},
14335:                     };
14336:     return $proxyinfo;
14337: }
14338: 
14339: sub ip_match {
14340:     my ($ip,$pattern_str) = @_;
14341:     $ip=Net::CIDR::cidrvalidate($ip);
14342:     if ($ip) {
14343:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14344:     }
14345:     return;
14346: }
14347: 
14348: sub get_proxy_alias {
14349:     my $lonhost = $perlvar{'lonHostID'};
14350:     if ($lonhost ne '') {
14351:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonhost);
14352:         if ($cached) {
14353:             return $alias;
14354:         }
14355:         my $dom = &Apache::lonnet::host_domain($lonhost);
14356:         if ($dom ne '') {
14357:             my $cachetime = 60*60*24;
14358:             my %domconfig =
14359:                 &Apache::lonnet::get_dom('configuration',['proxy'],$dom);
14360:             my $alias;
14361:             if (ref($domconfig{'proxy'}) eq 'HASH') {
14362:                 if (ref($domconfig{'proxy'}{'alias'}) eq 'HASH') {
14363:                     $alias = $domconfig{'proxy'}{'alias'}{$lonhost};
14364:                 }
14365:             }
14366:             return &do_cache_new('proxyalias',$lonhost,$alias,$cachetime);
14367:         }
14368:     }
14369:     return;
14370: }
14371: 
14372: # ------------------------------------------------------------- Declutters URLs
14373: 
14374: sub declutter {
14375:     my $thisfn=shift;
14376:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14377:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14378:         $thisfn=~s{^/home/httpd/html}{};
14379:     }
14380:     $thisfn=~s/^\///;
14381:     $thisfn=~s|^adm/wrapper/||;
14382:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14383:     $thisfn=~s/^res\///;
14384:     $thisfn=~s/^priv\///;
14385:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14386:         $thisfn=~s/\?.+$//;
14387:     }
14388:     return $thisfn;
14389: }
14390: 
14391: # ------------------------------------------------------------- Clutter up URLs
14392: 
14393: sub clutter {
14394:     my $thisfn='/'.&declutter(shift);
14395:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14396: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14397:        $thisfn='/res'.$thisfn; 
14398:     }
14399:     if ($thisfn !~m|^/adm|) {
14400: 	if ($thisfn =~ m|^/ext/|) {
14401: 	    $thisfn='/adm/wrapper'.$thisfn;
14402: 	} else {
14403: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14404: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14405: 	    if ($embstyle eq 'ssi'
14406: 		|| ($embstyle eq 'hdn')
14407: 		|| ($embstyle eq 'rat')
14408: 		|| ($embstyle eq 'prv')
14409: 		|| ($embstyle eq 'ign')) {
14410: 		#do nothing with these
14411: 	    } elsif (($embstyle eq 'img') 
14412: 		|| ($embstyle eq 'emb')
14413: 		|| ($embstyle eq 'wrp')) {
14414: 		$thisfn='/adm/wrapper'.$thisfn;
14415: 	    } elsif ($embstyle eq 'unk'
14416: 		     && $thisfn!~/\.(sequence|page)$/) {
14417: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14418: 	    } else {
14419: #		&logthis("Got a blank emb style");
14420: 	    }
14421: 	}
14422:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14423:         $thisfn='/adm/wrapper'.$thisfn;
14424:     }
14425:     return $thisfn;
14426: }
14427: 
14428: sub clutter_with_no_wrapper {
14429:     my $uri = &clutter(shift);
14430:     if ($uri =~ m-^/adm/-) {
14431: 	$uri =~ s-^/adm/wrapper/-/-;
14432: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14433:     }
14434:     return $uri;
14435: }
14436: 
14437: sub freeze_escape {
14438:     my ($value)=@_;
14439:     if (ref($value)) {
14440: 	$value=&nfreeze($value);
14441: 	return '__FROZEN__'.&escape($value);
14442:     }
14443:     return &escape($value);
14444: }
14445: 
14446: 
14447: sub thaw_unescape {
14448:     my ($value)=@_;
14449:     if ($value =~ /^__FROZEN__/) {
14450: 	substr($value,0,10,undef);
14451: 	$value=&unescape($value);
14452: 	return &thaw($value);
14453:     }
14454:     return &unescape($value);
14455: }
14456: 
14457: sub correct_line_ends {
14458:     my ($result)=@_;
14459:     $$result =~s/\r\n/\n/mg;
14460:     $$result =~s/\r/\n/mg;
14461: }
14462: # ================================================================ Main Program
14463: 
14464: sub goodbye {
14465:    &logthis("Starting Shut down");
14466: #not converted to using infrastruture and probably shouldn't be
14467:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14468: #converted
14469: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14470:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14471: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14472: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14473: #1.1 only
14474: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14475: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14476: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14477: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14478:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14479:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14480:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14481:    &flushcourselogs();
14482:    &logthis("Shutting down");
14483: }
14484: 
14485: sub get_dns {
14486:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14487:     if (!$ignore_cache) {
14488: 	my ($content,$cached)=
14489: 	    &Apache::lonnet::is_cached_new('dns',$url);
14490: 	if ($cached) {
14491: 	    &$func($content,$hashref);
14492: 	    return;
14493: 	}
14494:     }
14495: 
14496:     my %alldns;
14497:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14498:         foreach my $dns (<$config>) {
14499: 	    next if ($dns !~ /^\^(\S*)/x);
14500:             my $line = $1;
14501:             my ($host,$protocol) = split(/:/,$line);
14502:             if ($protocol ne 'https') {
14503:                 $protocol = 'http';
14504:             }
14505: 	    $alldns{$host} = $protocol;
14506:         }
14507:         close($config);
14508:     }
14509:     while (%alldns) {
14510: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14511: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14512:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14513:         delete($alldns{$dns});
14514: 	next if ($response->is_error());
14515:         if ($url eq '/adm/dns/loncapaCRL') {
14516:             return &$func($response);
14517:         } else {
14518: 	    my @content = split("\n",$response->content);
14519: 	    unless ($nocache) {
14520: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14521: 	    }
14522: 	    &$func(\@content,$hashref);
14523:             return;
14524:         }
14525:     }
14526:     my $which = (split('/',$url,4))[3];
14527:     if ($which eq 'loncapaCRL') {
14528:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14529:         if (-e $diskfile) {
14530:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14531:         } else {
14532:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14533:         }
14534:     } else {
14535:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14536:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14537:             my @content = <$config>;
14538:             close($config);
14539:             &$func(\@content,$hashref);
14540:         }
14541:     }
14542:     return;
14543: }
14544: 
14545: # ------------------------------------------------------Get DNS checksums file
14546: sub parse_dns_checksums_tab {
14547:     my ($lines,$hashref) = @_;
14548:     my $lonhost = $perlvar{'lonHostID'};
14549:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14550:     my $loncaparev = &get_server_loncaparev($machine_dom);
14551:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14552:     my $webconfdir = '/etc/httpd/conf';
14553:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14554:         $webconfdir = '/etc/apache2';
14555:     } elsif ($distro =~ /^sles(\d+)$/) {
14556:         if ($1 >= 10) {
14557:             $webconfdir = '/etc/apache2';
14558:         }
14559:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14560:         if ($1 >= 10.0) {
14561:             $webconfdir = '/etc/apache2';
14562:         }
14563:     }
14564:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14565:     my (%chksum,%revnum);
14566:     if (ref($lines) eq 'ARRAY') {
14567:         chomp(@{$lines});
14568:         my $version = shift(@{$lines});
14569:         if ($version eq $release) {  
14570:             foreach my $line (@{$lines}) {
14571:                 my ($file,$version,$shasum) = split(/,/,$line);
14572:                 if ($file =~ m{^/etc/httpd/conf}) {
14573:                     if ($webconfdir eq '/etc/apache2') {
14574:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14575:                     }
14576:                 }
14577:                 $chksum{$file} = $shasum;
14578:                 $revnum{$file} = $version;
14579:             }
14580:             if (ref($hashref) eq 'HASH') {
14581:                 %{$hashref} = (
14582:                                 sums     => \%chksum,
14583:                                 versions => \%revnum,
14584:                               );
14585:             }
14586:         }
14587:     }
14588:     return;
14589: }
14590: 
14591: sub fetch_dns_checksums {
14592:     my %checksums;
14593:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14594:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14595:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14596:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14597:              \%checksums);
14598:     return \%checksums;
14599: }
14600: 
14601: sub fetch_crl_pemfile {
14602:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14603: }
14604: 
14605: sub save_crl_pem {
14606:     my ($response) = @_;
14607:     my ($msg,$hadchanges);
14608:     if (ref($response)) {
14609:         my $now = time;
14610:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14611:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14612:         if (open(my $fh,'>',"$tmpcrl")) {
14613:             print $fh $response->content;
14614:             close($fh);
14615:             if (-e $lonca) {
14616:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14617:                     my $check = <PIPE>;
14618:                     close(PIPE);
14619:                     chomp($check);
14620:                     if ($check eq 'verify OK') {
14621:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14622:                         my $backup;
14623:                         if (-e $dest) {
14624:                             if (&File::Copy::move($dest,"$dest.bak")) {
14625:                                 $backup = 'ok';
14626:                             }
14627:                         }
14628:                         if (&File::Copy::move($tmpcrl,$dest)) {
14629:                             $msg = 'ok';
14630:                             if ($backup) {
14631:                                 my (%oldnums,%newnums);
14632:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14633:                                     while (<PIPE>) {
14634:                                         $oldnums{(split(/:/))[1]} = 1;
14635:                                     }
14636:                                     close(PIPE);
14637:                                 }
14638:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14639:                                     while(<PIPE>) {
14640:                                         $newnums{(split(/:/))[1]} = 1;
14641:                                     }
14642:                                     close(PIPE);
14643:                                 }
14644:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14645:                                     unless (exists($oldnums{$key})) {
14646:                                         $hadchanges = 1;
14647:                                         last;
14648:                                     }
14649:                                 }
14650:                                 unless ($hadchanges) {
14651:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14652:                                         unless (exists($newnums{$key})) {
14653:                                             $hadchanges = 1;
14654:                                             last;
14655:                                         }
14656:                                     }
14657:                                 }
14658:                             }
14659:                         }
14660:                     } else {
14661:                         unlink($tmpcrl);
14662:                     }
14663:                 } else {
14664:                     unlink($tmpcrl);
14665:                 }
14666:             } else {
14667:                 unlink($tmpcrl);
14668:             }
14669:         }
14670:     }
14671:     return ($msg,$hadchanges);
14672: }
14673: 
14674: # ------------------------------------------------------------ Read domain file
14675: {
14676:     my $loaded;
14677:     my %domain;
14678: 
14679:     sub parse_domain_tab {
14680: 	my ($lines) = @_;
14681: 	foreach my $line (@$lines) {
14682: 	    next if ($line =~ /^(\#|\s*$ )/x);
14683: 
14684: 	    chomp($line);
14685: 	    my ($name,@elements) = split(/:/,$line,9);
14686: 	    my %this_domain;
14687: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14688: 			       'lang_def', 'city', 'longi', 'lati',
14689: 			       'primary') {
14690: 		$this_domain{$field} = shift(@elements);
14691: 	    }
14692: 	    $domain{$name} = \%this_domain;
14693: 	}
14694:     }
14695: 
14696:     sub reset_domain_info {
14697: 	undef($loaded);
14698: 	undef(%domain);
14699:     }
14700: 
14701:     sub load_domain_tab {
14702: 	my ($ignore_cache,$nocache) = @_;
14703: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14704: 	my $fh;
14705: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14706: 	    my @lines = <$fh>;
14707: 	    &parse_domain_tab(\@lines);
14708: 	}
14709: 	close($fh);
14710: 	$loaded = 1;
14711:     }
14712: 
14713:     sub domain {
14714: 	&load_domain_tab() if (!$loaded);
14715: 
14716: 	my ($name,$what) = @_;
14717: 	return if ( !exists($domain{$name}) );
14718: 
14719: 	if (!$what) {
14720: 	    return $domain{$name}{'description'};
14721: 	}
14722: 	return $domain{$name}{$what};
14723:     }
14724: 
14725:     sub domain_info {
14726:         &load_domain_tab() if (!$loaded);
14727:         return %domain;
14728:     }
14729: 
14730: }
14731: 
14732: 
14733: # ------------------------------------------------------------- Read hosts file
14734: {
14735:     my %hostname;
14736:     my %hostdom;
14737:     my %libserv;
14738:     my $loaded;
14739:     my %name_to_host;
14740:     my %internetdom;
14741:     my %LC_dns_serv;
14742: 
14743:     sub parse_hosts_tab {
14744: 	my ($file) = @_;
14745: 	foreach my $configline (@$file) {
14746: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14747:             chomp($configline);
14748: 	    if ($configline =~ /^\^/) {
14749:                 if ($configline =~ /^\^([\w.\-]+)/) {
14750:                     $LC_dns_serv{$1} = 1;
14751:                 }
14752:                 next;
14753:             }
14754: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14755: 	    $name=~s/\s//g;
14756: 	    if ($id && $domain && $role && $name) {
14757:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14758:                     my $curr = $hostname{$id};
14759:                     my $skip;
14760:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14761:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14762:                             $skip = 1;
14763:                         } else {
14764:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14765:                         }
14766:                     }
14767:                     unless ($skip) {
14768:                         push(@{$name_to_host{$name}},$id);
14769:                     }
14770:                 } else {
14771:                     push(@{$name_to_host{$name}},$id);
14772:                 }
14773: 		$hostname{$id}=$name;
14774: 		$hostdom{$id}=$domain;
14775: 		if ($role eq 'library') { $libserv{$id}=$name; }
14776:                 if (defined($protocol)) {
14777:                     if ($protocol eq 'https') {
14778:                         $protocol{$id} = $protocol;
14779:                     } else {
14780:                         $protocol{$id} = 'http'; 
14781:                     }
14782:                 } else {
14783:                     $protocol{$id} = 'http';
14784:                 }
14785:                 if (defined($intdom)) {
14786:                     $internetdom{$id} = $intdom;
14787:                 }
14788: 	    }
14789: 	}
14790:     }
14791:     
14792:     sub reset_hosts_info {
14793: 	&purge_remembered();
14794: 	&reset_domain_info();
14795: 	&reset_hosts_ip_info();
14796:         undef(%internetdom);
14797: 	undef(%name_to_host);
14798: 	undef(%hostname);
14799: 	undef(%hostdom);
14800: 	undef(%libserv);
14801: 	undef($loaded);
14802:     }
14803: 
14804:     sub load_hosts_tab {
14805: 	my ($ignore_cache,$nocache) = @_;
14806: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14807: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14808: 	my @config = <$config>;
14809: 	&parse_hosts_tab(\@config);
14810: 	close($config);
14811: 	$loaded=1;
14812:     }
14813: 
14814:     sub hostname {
14815: 	&load_hosts_tab() if (!$loaded);
14816: 
14817: 	my ($lonid) = @_;
14818: 	return $hostname{$lonid};
14819:     }
14820: 
14821:     sub all_hostnames {
14822: 	&load_hosts_tab() if (!$loaded);
14823: 
14824: 	return %hostname;
14825:     }
14826: 
14827:     sub all_names {
14828:         my ($ignore_cache,$nocache) = @_;
14829: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14830: 
14831: 	return %name_to_host;
14832:     }
14833: 
14834:     sub all_host_domain {
14835:         &load_hosts_tab() if (!$loaded);
14836:         return %hostdom;
14837:     }
14838: 
14839:     sub all_host_intdom {
14840:         &load_hosts_tab() if (!$loaded);
14841:         return %internetdom;
14842:     }
14843: 
14844:     sub is_library {
14845: 	&load_hosts_tab() if (!$loaded);
14846: 
14847: 	return exists($libserv{$_[0]});
14848:     }
14849: 
14850:     sub all_library {
14851: 	&load_hosts_tab() if (!$loaded);
14852: 
14853: 	return %libserv;
14854:     }
14855: 
14856:     sub unique_library {
14857: 	#2x reverse removes all hostnames that appear more than once
14858:         my %unique = reverse &all_library();
14859:         return reverse %unique;
14860:     }
14861: 
14862:     sub get_servers {
14863: 	&load_hosts_tab() if (!$loaded);
14864: 
14865: 	my ($domain,$type) = @_;
14866: 	my %possible_hosts = ($type eq 'library') ? %libserv
14867: 	                                          : %hostname;
14868: 	my %result;
14869: 	if (ref($domain) eq 'ARRAY') {
14870: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14871: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14872: 		    $result{$host} = $hostname;
14873: 		}
14874: 	    }
14875: 	} else {
14876: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14877: 		if ($hostdom{$host} eq $domain) {
14878: 		    $result{$host} = $hostname;
14879: 		}
14880: 	    }
14881: 	}
14882: 	return %result;
14883:     }
14884: 
14885:     sub get_unique_servers {
14886:         my %unique = reverse &get_servers(@_);
14887: 	return reverse %unique;
14888:     }
14889: 
14890:     sub host_domain {
14891: 	&load_hosts_tab() if (!$loaded);
14892: 
14893: 	my ($lonid) = @_;
14894: 	return $hostdom{$lonid};
14895:     }
14896: 
14897:     sub all_domains {
14898: 	&load_hosts_tab() if (!$loaded);
14899: 
14900: 	my %seen;
14901: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14902: 	return @uniq;
14903:     }
14904: 
14905:     sub internet_dom {
14906:         &load_hosts_tab() if (!$loaded);
14907: 
14908:         my ($lonid) = @_;
14909:         return $internetdom{$lonid};
14910:     }
14911: 
14912:     sub is_LC_dns {
14913:         &load_hosts_tab() if (!$loaded);
14914: 
14915:         my ($hostname) = @_;
14916:         return exists($LC_dns_serv{$hostname});
14917:     }
14918: 
14919: }
14920: 
14921: { 
14922:     my %iphost;
14923:     my %name_to_ip;
14924:     my %lonid_to_ip;
14925: 
14926:     sub get_hosts_from_ip {
14927: 	my ($ip) = @_;
14928: 	my %iphosts = &get_iphost();
14929: 	if (ref($iphosts{$ip})) {
14930: 	    return @{$iphosts{$ip}};
14931: 	}
14932: 	return;
14933:     }
14934:     
14935:     sub reset_hosts_ip_info {
14936: 	undef(%iphost);
14937: 	undef(%name_to_ip);
14938: 	undef(%lonid_to_ip);
14939:     }
14940: 
14941:     sub get_host_ip {
14942: 	my ($lonid) = @_;
14943: 	if (exists($lonid_to_ip{$lonid})) {
14944: 	    return $lonid_to_ip{$lonid};
14945: 	}
14946: 	my $name=&hostname($lonid);
14947:    	my $ip = gethostbyname($name);
14948: 	return if (!$ip || length($ip) ne 4);
14949: 	$ip=inet_ntoa($ip);
14950: 	$name_to_ip{$name}   = $ip;
14951: 	$lonid_to_ip{$lonid} = $ip;
14952: 	return $ip;
14953:     }
14954:     
14955:     sub get_iphost {
14956: 	my ($ignore_cache,$nocache) = @_;
14957: 
14958: 	if (!$ignore_cache) {
14959: 	    if (%iphost) {
14960: 		return %iphost;
14961: 	    }
14962: 	    my ($ip_info,$cached)=
14963: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14964: 	    if ($cached) {
14965: 		%iphost      = %{$ip_info->[0]};
14966: 		%name_to_ip  = %{$ip_info->[1]};
14967: 		%lonid_to_ip = %{$ip_info->[2]};
14968: 		return %iphost;
14969: 	    }
14970: 	}
14971: 
14972: 	# get yesterday's info for fallback
14973: 	my %old_name_to_ip;
14974: 	my ($ip_info,$cached)=
14975: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14976: 	if ($cached) {
14977: 	    %old_name_to_ip = %{$ip_info->[1]};
14978: 	}
14979: 
14980: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14981: 	foreach my $name (keys(%name_to_host)) {
14982: 	    my $ip;
14983: 	    if (!exists($name_to_ip{$name})) {
14984: 		$ip = gethostbyname($name);
14985: 		if (!$ip || length($ip) ne 4) {
14986: 		    if (defined($old_name_to_ip{$name})) {
14987: 			$ip = $old_name_to_ip{$name};
14988: 			&logthis("Can't find $name defaulting to old $ip");
14989: 		    } else {
14990: 			&logthis("Name $name no IP found");
14991: 			next;
14992: 		    }
14993: 		} else {
14994: 		    $ip=inet_ntoa($ip);
14995: 		}
14996: 		$name_to_ip{$name} = $ip;
14997: 	    } else {
14998: 		$ip = $name_to_ip{$name};
14999: 	    }
15000: 	    foreach my $id (@{ $name_to_host{$name} }) {
15001: 		$lonid_to_ip{$id} = $ip;
15002: 	    }
15003: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
15004: 	}
15005:         unless ($nocache) {
15006: 	    &do_cache_new('iphost','iphost',
15007: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
15008: 		          48*60*60);
15009:         }
15010: 
15011: 	return %iphost;
15012:     }
15013: 
15014:     #
15015:     #  Given a DNS returns the loncapa host name for that DNS 
15016:     # 
15017:     sub host_from_dns {
15018:         my ($dns) = @_;
15019:         my @hosts;
15020:         my $ip;
15021: 
15022:         if (exists($name_to_ip{$dns})) {
15023:             $ip = $name_to_ip{$dns};
15024:         }
15025:         if (!$ip) {
15026:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15027:             if (length($ip) == 4) { 
15028: 	        $ip   = &IO::Socket::inet_ntoa($ip);
15029:             }
15030:         }
15031:         if ($ip) {
15032: 	    @hosts = get_hosts_from_ip($ip);
15033: 	    return $hosts[0];
15034:         }
15035:         return undef;
15036:     }
15037: 
15038:     sub get_internet_names {
15039:         my ($lonid) = @_;
15040:         return if ($lonid eq '');
15041:         my ($idnref,$cached)=
15042:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
15043:         if ($cached) {
15044:             return $idnref;
15045:         }
15046:         my $ip = &get_host_ip($lonid);
15047:         my @hosts = &get_hosts_from_ip($ip);
15048:         my %iphost = &get_iphost();
15049:         my (@idns,%seen);
15050:         foreach my $id (@hosts) {
15051:             my $dom = &host_domain($id);
15052:             my $prim_id = &domain($dom,'primary');
15053:             my $prim_ip = &get_host_ip($prim_id);
15054:             next if ($seen{$prim_ip});
15055:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15056:                 foreach my $id (@{$iphost{$prim_ip}}) {
15057:                     my $intdom = &internet_dom($id);
15058:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
15059:                         push(@idns,$intdom);
15060:                     }
15061:                 }
15062:             }
15063:             $seen{$prim_ip} = 1;
15064:         }
15065:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15066:     }
15067: 
15068: }
15069: 
15070: sub all_loncaparevs {
15071:     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);
15072: }
15073: 
15074: # ---------------------------------------------------------- Read loncaparev table
15075: {
15076:     sub load_loncaparevs { 
15077:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15078:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15079:                 while (my $configline=<$config>) {
15080:                     chomp($configline);
15081:                     my ($hostid,$loncaparev)=split(/:/,$configline);
15082:                     $loncaparevs{$hostid}=$loncaparev;
15083:                 }
15084:                 close($config);
15085:             }
15086:         }
15087:     }
15088: }
15089: 
15090: # ---------------------------------------------------------- Read serverhostID table
15091: {
15092:     sub load_serverhomeIDs {
15093:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15094:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15095:                 while (my $configline=<$config>) {
15096:                     chomp($configline);
15097:                     my ($name,$id)=split(/:/,$configline);
15098:                     $serverhomeIDs{$name}=$id;
15099:                 }
15100:                 close($config);
15101:             }
15102:         }
15103:     }
15104: }
15105: 
15106: 
15107: BEGIN {
15108: 
15109: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15110:     unless ($readit) {
15111: {
15112:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15113:     %perlvar = (%perlvar,%{$configvars});
15114: }
15115: 
15116: 
15117: # ------------------------------------------------------ Read spare server file
15118: {
15119:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15120: 
15121:     while (my $configline=<$config>) {
15122:        chomp($configline);
15123:        if ($configline) {
15124: 	   my ($host,$type) = split(':',$configline,2);
15125: 	   if (!defined($type) || $type eq '') { $type = 'default' };
15126: 	   push(@{ $spareid{$type} }, $host);
15127:        }
15128:     }
15129:     close($config);
15130: }
15131: # ------------------------------------------------------------ Read permissions
15132: {
15133:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15134: 
15135:     while (my $configline=<$config>) {
15136: 	chomp($configline);
15137: 	if ($configline) {
15138: 	    my ($role,$perm)=split(/ /,$configline);
15139: 	    if ($perm ne '') { $pr{$role}=$perm; }
15140: 	}
15141:     }
15142:     close($config);
15143: }
15144: 
15145: # -------------------------------------------- Read plain texts for permissions
15146: {
15147:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15148: 
15149:     while (my $configline=<$config>) {
15150: 	chomp($configline);
15151: 	if ($configline) {
15152: 	    my ($short,@plain)=split(/:/,$configline);
15153:             %{$prp{$short}} = ();
15154: 	    if (@plain > 0) {
15155:                 $prp{$short}{'std'} = $plain[0];
15156:                 for (my $i=1; $i<@plain; $i++) {
15157:                     $prp{$short}{'alt'.$i} = $plain[$i];  
15158:                 }
15159:             }
15160: 	}
15161:     }
15162:     close($config);
15163: }
15164: 
15165: # ---------------------------------------------------------- Read package table
15166: {
15167:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15168: 
15169:     while (my $configline=<$config>) {
15170: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15171: 	chomp($configline);
15172: 	my ($short,$plain)=split(/:/,$configline);
15173: 	my ($pack,$name)=split(/\&/,$short);
15174: 	if ($plain ne '') {
15175: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
15176: 	    $packagetab{$short}=$plain; 
15177: 	}
15178:     }
15179:     close($config);
15180: }
15181: 
15182: # ---------------------------------------------------------- Read loncaparev table
15183: 
15184: &load_loncaparevs();
15185: 
15186: # ---------------------------------------------------------- Read serverhostID table
15187: 
15188: &load_serverhomeIDs();
15189: 
15190: # ---------------------------------------------------------- Read releaseslist XML
15191: {
15192:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15193:     if (-e $file) {
15194:         my $parser = HTML::LCParser->new($file);
15195:         while (my $token = $parser->get_token()) {
15196:             if ($token->[0] eq 'S') {
15197:                 my $item = $token->[1];
15198:                 my $name = $token->[2]{'name'};
15199:                 my $value = $token->[2]{'value'};
15200:                 my $valuematch = $token->[2]{'valuematch'};
15201:                 my $namematch = $token->[2]{'namematch'};
15202:                 if ($item eq 'parameter') {
15203:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15204:                         my $release = $parser->get_text();
15205:                         $release =~ s/(^\s*|\s*$ )//gx;
15206:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15207:                     }
15208:                 } elsif ($item ne '' && $name ne '') {
15209:                     my $release = $parser->get_text();
15210:                     $release =~ s/(^\s*|\s*$ )//gx;
15211:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
15212:                 }
15213:             }
15214:         }
15215:     }
15216: }
15217: 
15218: # ---------------------------------------------------------- Read managers table
15219: {
15220:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15221:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15222:             while (my $configline=<$config>) {
15223:                 chomp($configline);
15224:                 next if ($configline =~ /^\#/);
15225:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15226:                     $managerstab{$configline} = 1;
15227:                 }
15228:             }
15229:             close($config);
15230:         }
15231:     }
15232: }
15233: 
15234: # ------------- set up temporary directory
15235: {
15236:     $tmpdir = LONCAPA::tempdir();
15237: 
15238: }
15239: 
15240: # ------------- set default texengine (domain default overrides this)
15241: {
15242:     $deftex = LONCAPA::texengine();
15243: }
15244: 
15245: # ------------- set default minimum length for passwords for internal auth users
15246: {
15247:     $passwdmin = LONCAPA::passwd_min();
15248: }
15249: 
15250: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
15251: 				'compress_threshold'=> 20_000,
15252:  			        });
15253: 
15254: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15255: $dumpcount=0;
15256: $locknum=0;
15257: 
15258: &logtouch();
15259: &logthis('<font color="yellow">INFO: Read configuration</font>');
15260: $readit=1;
15261:     {
15262: 	use integer;
15263: 	my $test=(2**32)+1;
15264: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15265: 	&logthis(" Detected 64bit platform ($_64bit)");
15266:     }
15267: }
15268: }
15269: 
15270: 1;
15271: __END__
15272: 
15273: =pod
15274: 
15275: =head1 NAME
15276: 
15277: Apache::lonnet - Subroutines to ask questions about things in the network.
15278: 
15279: =head1 SYNOPSIS
15280: 
15281: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15282: 
15283:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15284: 
15285: Common parameters:
15286: 
15287: =over 4
15288: 
15289: =item *
15290: 
15291: $uname : an internal username (if $cname expecting a course Id specifically)
15292: 
15293: =item *
15294: 
15295: $udom : a domain (if $cdom expecting a course's domain specifically)
15296: 
15297: =item *
15298: 
15299: $symb : a resource instance identifier
15300: 
15301: =item *
15302: 
15303: $namespace : the name of a .db file that contains the data needed or
15304: being set.
15305: 
15306: =back
15307: 
15308: =head1 OVERVIEW
15309: 
15310: lonnet provides subroutines which interact with the
15311: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15312: about classes, users, and resources.
15313: 
15314: For many of these objects you can also use this to store data about
15315: them or modify them in various ways.
15316: 
15317: =head2 Symbs
15318: 
15319: To identify a specific instance of a resource, LON-CAPA uses symbols
15320: or "symbs"X<symb>. These identifiers are built from the URL of the
15321: map, the resource number of the resource in the map, and the URL of
15322: the resource itself. The latter is somewhat redundant, but might help
15323: if maps change.
15324: 
15325: An example is
15326: 
15327:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15328: 
15329: The respective map entry is
15330: 
15331:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15332:   title="Problem 2">
15333:  </resource>
15334: 
15335: Symbs are used by the random number generator, as well as to store and
15336: restore data specific to a certain instance of for example a problem.
15337: 
15338: =head2 Storing And Retrieving Data
15339: 
15340: X<store()>X<cstore()>X<restore()>Three of the most important functions
15341: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15342: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15343: is is the non-critical message twin of cstore. These functions are for
15344: handlers to store a perl hash to a user's permanent data space in an
15345: easy manner, and to retrieve it again on another call. It is expected
15346: that a handler would use this once at the beginning to retrieve data,
15347: and then again once at the end to send only the new data back.
15348: 
15349: The data is stored in the user's data directory on the user's
15350: homeserver under the ID of the course.
15351: 
15352: The hash that is returned by restore will have all of the previous
15353: value for all of the elements of the hash.
15354: 
15355: Example:
15356: 
15357:  #creating a hash
15358:  my %hash;
15359:  $hash{'foo'}='bar';
15360: 
15361:  #storing it
15362:  &Apache::lonnet::cstore(\%hash);
15363: 
15364:  #changing a value
15365:  $hash{'foo'}='notbar';
15366: 
15367:  #adding a new value
15368:  $hash{'bar'}='foo';
15369:  &Apache::lonnet::cstore(\%hash);
15370: 
15371:  #retrieving the hash
15372:  my %history=&Apache::lonnet::restore();
15373: 
15374:  #print the hash
15375:  foreach my $key (sort(keys(%history))) {
15376:    print("\%history{$key} = $history{$key}");
15377:  }
15378: 
15379: Will print out:
15380: 
15381:  %history{1:foo} = bar
15382:  %history{1:keys} = foo:timestamp
15383:  %history{1:timestamp} = 990455579
15384:  %history{2:bar} = foo
15385:  %history{2:foo} = notbar
15386:  %history{2:keys} = foo:bar:timestamp
15387:  %history{2:timestamp} = 990455580
15388:  %history{bar} = foo
15389:  %history{foo} = notbar
15390:  %history{timestamp} = 990455580
15391:  %history{version} = 2
15392: 
15393: Note that the special hash entries C<keys>, C<version> and
15394: C<timestamp> were added to the hash. C<version> will be equal to the
15395: total number of versions of the data that have been stored. The
15396: C<timestamp> attribute will be the UNIX time the hash was
15397: stored. C<keys> is available in every historical section to list which
15398: keys were added or changed at a specific historical revision of a
15399: hash.
15400: 
15401: B<Warning>: do not store the hash that restore returns directly. This
15402: will cause a mess since it will restore the historical keys as if the
15403: were new keys. I.E. 1:foo will become 1:1:foo etc.
15404: 
15405: Calling convention:
15406: 
15407:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15408:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15409: 
15410: For more detailed information, see lonnet specific documentation.
15411: 
15412: =head1 RETURN MESSAGES
15413: 
15414: =over 4
15415: 
15416: =item * B<con_lost>: unable to contact remote host
15417: 
15418: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15419: when the connection is brought back up
15420: 
15421: =item * B<con_failed>: unable to contact remote host and unable to save message
15422: for later delivery
15423: 
15424: =item * B<error:>: an error a occurred, a description of the error follows the :
15425: 
15426: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15427: that was requested
15428: 
15429: =back
15430: 
15431: =head1 PUBLIC SUBROUTINES
15432: 
15433: =head2 Session Environment Functions
15434: 
15435: =over 4
15436: 
15437: =item * 
15438: X<appenv()>
15439: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15440: the user envirnoment file, and will be restored for each access this
15441: user makes during this session, also modifies the %env for the current
15442: process. Optional rolesarrayref - if defined contains a reference to an array
15443: of roles which are exempt from the restriction on modifying user.role entries 
15444: in the user's environment.db and in %env.    
15445: 
15446: =item *
15447: X<delenv()>
15448: B<delenv($delthis,$regexp)>: removes all items from the session
15449: environment file that begin with $delthis. If the 
15450: optional second arg - $regexp - is true, $delthis is treated as a 
15451: regular expression, otherwise \Q$delthis\E is used. 
15452: The values are also deleted from the current processes %env.
15453: 
15454: =item * get_env_multiple($name) 
15455: 
15456: gets $name from the %env hash, it seemlessly handles the cases where multiple
15457: values may be defined and end up as an array ref.
15458: 
15459: returns an array of values
15460: 
15461: =back
15462: 
15463: =head2 User Information
15464: 
15465: =over 4
15466: 
15467: =item *
15468: X<queryauthenticate()>
15469: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15470: authentication scheme
15471: 
15472: =item *
15473: X<authenticate()>
15474: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15475: authenticate user from domain's lib servers (first use the current
15476: one). C<$upass> should be the users password.
15477: $checkdefauth is optional (value is 1 if a check should be made to
15478:    authenticate user using default authentication method, and allow
15479:    account creation if username does not have account in the domain).
15480: $clientcancheckhost is optional (value is 1 if checking whether the
15481:    server can host will occur on the client side in lonauth.pm).   
15482: 
15483: =item *
15484: X<homeserver()>
15485: B<homeserver($uname,$udom)>: find the server which has
15486: the user's directory and files (there must be only one), this caches
15487: the answer, and also caches if there is a borken connection.
15488: 
15489: =item *
15490: X<idget()>
15491: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15492: a list of student/employee IDs or clicker IDs
15493: (student/employee IDs are a unique resource in a domain, there must be 
15494: only 1 ID per username, and only 1 username per ID in a specific domain).
15495: clickerIDs are not necessarily unique, as students might share clickers.
15496: (returns hash: id=>name,id=>name)
15497: 
15498: =item *
15499: X<idrget()>
15500: B<idrget($udom,@unames)>: find the IDs behind a list of
15501: usernames (returns hash: name=>id,name=>id)
15502: 
15503: =item *
15504: X<idput()>
15505: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15506: names and associated student/employee IDs or clicker IDs.
15507: 
15508: =item *
15509: X<iddel()>
15510: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15511: student/employee ID or clicker ID username look-ups from domain.
15512: The homeserver ($uhome) and namespace ($namespace) are optional.
15513: If no $uhome is provided, it will be determined usig &homeserver()
15514: for each user.  If no $namespace is provided, the default is ids.
15515: 
15516: =item *
15517: X<updateclickers()>
15518: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15519: clicker ID-to-username look-ups in clickers.db on library server.
15520: Permitted actions are add or del (i.e., add or delete). The 
15521: clickers.db contains clickerID as keys (escaped), and each corresponding
15522: value is an escaped comma-separated list of usernames (for whom the
15523: library server is the homeserver), who registered that particular ID.
15524: If $critical is true, the update will be sent via &critical, otherwise
15525: &reply() will be used.
15526: 
15527: =item *
15528: X<rolesinit()>
15529: B<rolesinit($udom,$username)>: get user privileges.
15530: returns user role, first access and timer interval hashes
15531: 
15532: =item *
15533: X<privileged()>
15534: B<privileged($username,$domain)>: returns a true if user has a
15535: privileged and active role (i.e. su or dc), false otherwise.
15536: 
15537: =item *
15538: X<getsection()>
15539: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15540: course $cname, return section name/number or '' for "not in course"
15541: and '-1' for "no section"
15542: 
15543: =item *
15544: X<userenvironment()>
15545: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15546: passed in @what from the requested user's environment, returns a hash
15547: 
15548: =item * 
15549: X<userlog_query()>
15550: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15551: activity.log file. %filters defines filters applied when parsing the
15552: log file. These can be start or end timestamps, or the type of action
15553: - log to look for Login or Logout events, check for Checkin or
15554: Checkout, role for role selection. The response is in the form
15555: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15556: escaped strings of the action recorded in the activity.log file.
15557: 
15558: =back
15559: 
15560: =head2 User Roles
15561: 
15562: =over 4
15563: 
15564: =item *
15565: 
15566: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15567: returns codes for allowed actions.
15568: 
15569: The first argument is required, all others are optional.
15570: 
15571: $priv is the privilege being checked.
15572: $uri contains additional information about what is being checked for access (e.g.,
15573: URL, course ID etc.). 
15574: $symb is the unique resource instance identifier in a course; if needed,
15575: but not provided, it will be retrieved via a call to &symbread(). 
15576: $role is the role for which a priv is being checked (only used if priv is evb). 
15577: $clientip is the user's IP address (only used when checking for access to portfolio 
15578: files).
15579: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15580: prevents recursive calls to &allowed.
15581: 
15582:  F: full access
15583:  U,I,K: authentication modes (cxx only)
15584:  '': forbidden
15585:  1: user needs to choose course
15586:  2: browse allowed
15587:  A: passphrase authentication needed
15588:  B: access temporarily blocked because of a blocking event in a course.
15589:  D: access blocked because access is required via session initiated via deep-link 
15590: 
15591: =item *
15592: 
15593: constructaccess($url,$setpriv) : check for access to construction space URL
15594: 
15595: See if the owner domain and name in the URL match those in the
15596: expected environment.  If so, return three element list
15597: ($ownername,$ownerdomain,$ownerhome).
15598: 
15599: Otherwise return the null string.
15600: 
15601: If second argument 'setpriv' is true, it assigns the privileges,
15602: and returns the same three element list, unless the owner has
15603: blocked "ad hoc" Domain Coordinator access to the Author Space,
15604: in which case the null string is returned.
15605: 
15606: =item *
15607: 
15608: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15609: define a custom role rolename set privileges in format of lonTabs/roles.tab
15610: for system, domain, and course level. $uname and $udom are optional (current
15611: user's username and domain will be used when either of $uname or $udom are absent.
15612: 
15613: =item *
15614: 
15615: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15616: (rolesplain.tab); plain text explanation of a user role term.
15617: $type is Course (default) or Community.
15618: If $forcedefault evaluates to true, text returned will be default 
15619: text for $type. Otherwise, if this is a course, the text returned 
15620: will be a custom name for the role (if defined in the course's 
15621: environment).  If no custom name is defined the default is returned.
15622:    
15623: =item *
15624: 
15625: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15626: All arguments are optional. Returns a hash of a roles, either for
15627: co-author/assistant author roles for a user's Construction Space
15628: (default), or if $context is 'userroles', roles for the user himself,
15629: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15630: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15631: For each key, value is set to colon-separated start and end times for
15632: the role.  If no username and domain are specified, will default to
15633: current user/domain. Types, roles, and roledoms are references to arrays
15634: of role statuses (active, future or previous), roles 
15635: (e.g., cc,in, st etc.) and domains of the roles which can be used
15636: to restrict the list of roles reported. If no array ref is 
15637: provided for types, will default to return only active roles.
15638: 
15639: =item *
15640: 
15641: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15642: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15643: 
15644: Additional optional arguments are: $type (if role checking is to be restricted 
15645: to certain user status types -- previous (expired roles), active (currently
15646: available roles) or future (roles available in the future), and
15647: $hideprivileged -- if true will not report course roles for users who
15648: have active Domain Coordinator role in course's domain or in additional
15649: domains (specified in 'Domains to check for privileged users' in course
15650: environment -- set via:  Course Settings -> Classlists and staff listing).
15651: 
15652: =item *
15653: 
15654: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15655: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15656: $possdomains and $possroles are optional array refs -- to domains to check and
15657: roles to check.  If $possdomains is not specified, a dump will be done of the
15658: users' roles.db to check for a dc or su role in any domain. This can be
15659: time consuming if &privileged is called repeatedly (e.g., when displaying a
15660: classlist), so in such cases, supplying a $possdomains array is preferred, as
15661: this then allows &privileged_by_domain() to be used, which caches the identity
15662: of privileged users, eliminating the need for repeated calls to &dump().
15663: 
15664: =item *
15665: 
15666: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15667: where the outer hash keys are domains specified in the $possdomains array ref,
15668: next inner hash keys are privileged roles specified in the $roles array ref,
15669: and the innermost hash contains key = value pairs for username:domain = end:start
15670: for active or future "privileged" users with that role in that domain. To avoid
15671: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15672: innerhash are cached using priv_$role and $dom as the identifiers.
15673: 
15674: =back
15675: 
15676: =head2 User Modification
15677: 
15678: =over 4
15679: 
15680: =item *
15681: 
15682: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15683: user for the level given by URL.  Optional start and end dates (leave empty
15684: string or zero for "no date")
15685: 
15686: =item *
15687: 
15688: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15689: change a users, password, possible return values are: ok,
15690: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15691: refused
15692: 
15693: =item *
15694: 
15695: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15696: 
15697: =item *
15698: 
15699: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15700:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15701: 
15702: will update user information (firstname,middlename,lastname,generation,
15703: permanentemail), and if forceid is true, student/employee ID also.
15704: A user's institutional affiliation(s) can also be updated.
15705: User information fields will not be overwritten with empty entries 
15706: unless the field is included in the $candelete array reference.
15707: This array is included when a single user is modified via "Manage Users",
15708: or when Autoupdate.pl is run by cron in a domain.
15709: 
15710: =item *
15711: 
15712: modifystudent
15713: 
15714: modify a student's enrollment and identification information.
15715: The course id is resolved based on the current user's environment.  
15716: This means the invoking user must be a course coordinator or otherwise
15717: associated with a course.
15718: 
15719: This call is essentially a wrapper for lonnet::modifyuser and
15720: lonnet::modify_student_enrollment
15721: 
15722: Inputs: 
15723: 
15724: =over 4
15725: 
15726: =item B<$udom> Student's loncapa domain
15727: 
15728: =item B<$uname> Student's loncapa login name
15729: 
15730: =item B<$uid> Student/Employee ID
15731: 
15732: =item B<$umode> Student's authentication mode
15733: 
15734: =item B<$upass> Student's password
15735: 
15736: =item B<$first> Student's first name
15737: 
15738: =item B<$middle> Student's middle name
15739: 
15740: =item B<$last> Student's last name
15741: 
15742: =item B<$gene> Student's generation
15743: 
15744: =item B<$usec> Student's section in course
15745: 
15746: =item B<$end> Unix time of the roles expiration
15747: 
15748: =item B<$start> Unix time of the roles start date
15749: 
15750: =item B<$forceid> If defined, allow $uid to be changed
15751: 
15752: =item B<$desiredhome> server to use as home server for student
15753: 
15754: =item B<$email> Student's permanent e-mail address
15755: 
15756: =item B<$type> Type of enrollment (auto or manual)
15757: 
15758: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15759: 
15760: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15761: 
15762: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15763: 
15764: =item B<$context> role change context (shown in User Management Logs display in a course)
15765: 
15766: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15767: 
15768: =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.
15769: 
15770: =back
15771: 
15772: =item *
15773: 
15774: modify_student_enrollment
15775: 
15776: Change a student's enrollment status in a class.  The environment variable
15777: 'role.request.course' must be defined for this function to proceed.
15778: 
15779: Inputs:
15780: 
15781: =over 4
15782: 
15783: =item $udom, student's domain
15784: 
15785: =item $uname, student's name
15786: 
15787: =item $uid, student's user id
15788: 
15789: =item $first, student's first name
15790: 
15791: =item $middle
15792: 
15793: =item $last
15794: 
15795: =item $gene
15796: 
15797: =item $usec
15798: 
15799: =item $end
15800: 
15801: =item $start
15802: 
15803: =item $type
15804: 
15805: =item $locktype
15806: 
15807: =item $cid
15808: 
15809: =item $selfenroll
15810: 
15811: =item $context
15812: 
15813: =item $credits, number of credits student will earn from this class
15814: 
15815: =item $instsec, institutional course section code for student
15816: 
15817: =back
15818: 
15819: 
15820: =item *
15821: 
15822: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15823: custom role; give a custom role to a user for the level given by URL.  Specify
15824: name and domain of role author, and role name
15825: 
15826: =item *
15827: 
15828: revokerole($udom,$uname,$url,$role) : revoke a role for url
15829: 
15830: =item *
15831: 
15832: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15833: 
15834: =back
15835: 
15836: =head2 Course Infomation
15837: 
15838: =over 4
15839: 
15840: =item *
15841: 
15842: coursedescription($courseid,$options) : returns a hash of information about the
15843: specified course id, including all environment settings for the
15844: course, the description of the course will be in the hash under the
15845: key 'description'
15846: 
15847: $options is an optional parameter that if supplied is a hash reference that controls
15848: what how this function works.  It has the following key/values:
15849: 
15850: =over 4
15851: 
15852: =item freshen_cache
15853: 
15854: If defined, and the environment cache for the course is valid, it is 
15855: returned in the returned hash.
15856: 
15857: =item one_time
15858: 
15859: If defined, the last cache time is set to _now_
15860: 
15861: =item user
15862: 
15863: If defined, the supplied username is used instead of the current user.
15864: 
15865: 
15866: =back
15867: 
15868: =item *
15869: 
15870: resdata($name,$domain,$type,@which) : request for current parameter
15871: setting for a specific $type, where $type is either 'course' or 'user',
15872: @what should be a list of parameters to ask about. This routine caches
15873: answers for 10 minutes.
15874: 
15875: =item *
15876: 
15877: get_courseresdata($courseid, $domain) : dump the entire course resource
15878: data base, returning a hash that is keyed by the resource name and has
15879: values that are the resource value.  I believe that the timestamps and
15880: versions are also returned.
15881: 
15882: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15883: supplemental content area. This routine caches the number of files for 
15884: 10 minutes.
15885: 
15886: =back
15887: 
15888: =head2 Course Modification
15889: 
15890: =over 4
15891: 
15892: =item *
15893: 
15894: writecoursepref($courseid,%prefs) : write preferences (environment
15895: database) for a course
15896: 
15897: =item *
15898: 
15899: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15900: 
15901: =item *
15902: 
15903: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15904: 
15905: =item *
15906: 
15907: is_course($courseid), is_course($cdom, $cnum)
15908: 
15909: Accepts either a combined $courseid (in the form of domain_courseid) or the
15910: two component version $cdom, $cnum. It checks if the specified course exists.
15911: 
15912: Returns:
15913:     undef if the course doesn't exist, otherwise
15914:     in scalar context the combined courseid.
15915:     in list context the two components of the course identifier, domain and 
15916:     courseid.    
15917: 
15918: =back
15919: 
15920: =head2 Bubblesheet Configuration
15921: 
15922: =over 4
15923: 
15924: =item *
15925: 
15926: get_scantron_config($which)
15927: 
15928: $which - the name of the configuration to parse from the file.
15929: 
15930: Parses and returns the bubblesheet configuration line selected as a
15931: hash of configuration file fields.
15932: 
15933: 
15934: Returns:
15935:     If the named configuration is not in the file, an empty
15936:     hash is returned.
15937: 
15938:     a hash with the fields
15939:       name         - internal name for the this configuration setup
15940:       description  - text to display to operator that describes this config
15941:       CODElocation - if 0 or the string 'none'
15942:                           - no CODE exists for this config
15943:                      if -1 || the string 'letter'
15944:                           - a CODE exists for this config and is
15945:                             a string of letters
15946:                      Unsupported value (but planned for future support)
15947:                           if a positive integer
15948:                                - The CODE exists as the first n items from
15949:                                  the question section of the form
15950:                           if the string 'number'
15951:                                - The CODE exists for this config and is
15952:                                  a string of numbers
15953:       CODEstart   - (only matter if a CODE exists) column in the line where
15954:                      the CODE starts
15955:       CODElength  - length of the CODE
15956:       IDstart     - column where the student/employee ID starts
15957:       IDlength    - length of the student/employee ID info
15958:       Qstart      - column where the information from the bubbled
15959:                     'questions' start
15960:       Qlength     - number of columns comprising a single bubble line from
15961:                     the sheet. (usually either 1 or 10)
15962:       Qon         - either a single character representing the character used
15963:                     to signal a bubble was chosen in the positional setup, or
15964:                     the string 'letter' if the letter of the chosen bubble is
15965:                     in the final, or 'number' if a number representing the
15966:                     chosen bubble is in the file (1->A 0->J)
15967:       Qoff        - the character used to represent that a bubble was
15968:                     left blank
15969:       PaperID     - if the scanning process generates a unique number for each
15970:                     sheet scanned the column that this ID number starts in
15971:       PaperIDlength - number of columns that comprise the unique ID number
15972:                       for the sheet of paper
15973:       FirstName   - column that the first name starts in
15974:       FirstNameLength - number of columns that the first name spans
15975:       LastName    - column that the last name starts in
15976:       LastNameLength - number of columns that the last name spans
15977:       BubblesPerRow - number of bubbles available in each row used to
15978:                       bubble an answer. (If not specified, 10 assumed).
15979: 
15980: 
15981: =item *
15982: 
15983: get_scantronformat_file($cdom)
15984: 
15985: $cdom - the course's domain (optional); if not supplied, uses
15986: domain for current $env{'request.course.id'}.
15987: 
15988: Returns an array containing lines from the scantron format file for
15989: the domain of the course.
15990: 
15991: If a url for a custom.tab file is listed in domain's configuration.db,
15992: lines are from this file.
15993: 
15994: Otherwise, if a default.tab has been published in RES space by the
15995: domainconfig user, lines are from this file.
15996: 
15997: Otherwise, fall back to getting lines from the legacy file on the
15998: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15999: 
16000: =back
16001: 
16002: =head2 Resource Subroutines
16003: 
16004: =over 4
16005: 
16006: =item *
16007: 
16008: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16009: 
16010: =item *
16011: 
16012: repcopy($filename) : subscribes to the requested file, and attempts to
16013: replicate from the owning library server, Might return
16014: 'unavailable', 'not_found', 'forbidden', 'ok', or
16015: 'bad_request', also attempts to grab the metadata for the
16016: resource. Expects the local filesystem pathname
16017: (/home/httpd/html/res/....)
16018: 
16019: =back
16020: 
16021: =head2 Resource Information
16022: 
16023: =over 4
16024: 
16025: =item *
16026: 
16027: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
16028: and returns the value of a variety of different possible values,
16029: $varname should be a request string, and the other parameters can be
16030: used to specify who and what one is asking about. Ordinarily, $cid 
16031: does not need to be specified, as it is retrived from 
16032: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16033: within lonuserstate::loadmap() when initializing a course, before
16034: $env{'request.course.id'} has been set, so it needs to be provided
16035: in that one case.
16036: 
16037: Possible values for $varname are environment.lastname (or other item
16038: from the envirnment hash), user.name (or someother aspect about the
16039: user), resource.0.maxtries (or some other part and parameter of a
16040: resource)
16041: 
16042: =item *
16043: 
16044: directcondval($number) : get current value of a condition; reads from a state
16045: string
16046: 
16047: =item *
16048: 
16049: condval($condidx) : value of condition index based on state
16050: 
16051: =item *
16052: 
16053: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16054: resource's metadata, $what should be either a specific key, or either
16055: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16056: packages that this resource currently uses, the last 3 arguments are 
16057: only used internally for recursive metadata.
16058: 
16059: the toolsymb is only used where the uri is for an external tool (for which
16060: the uri as well as the symb are guaranteed to be unique).
16061: 
16062: this function automatically caches all requests except any made recursively
16063: to retrieve a list of metadata keys for an imported library file ($liburi is 
16064: defined).
16065: 
16066: =item *
16067: 
16068: metadata_query($query,$custom,$customshow) : make a metadata query against the
16069: network of library servers; returns file handle of where SQL and regex results
16070: will be stored for query
16071: 
16072: =item *
16073: 
16074: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
16075: return symbolic list entry (all arguments optional). 
16076: 
16077: Args: filename is the filename (including path) for the file for which a symb 
16078: is required; donotrecurse, if true will prevent calls to allowed() being made 
16079: to check access status if more than one resource was found in the bighash 
16080: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
16081: a randompick); ignorecachednull, if true will prevent a symb of '' being 
16082: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16083: cause possible symbs to be checked to determine if they are subject to content
16084: blocking, if so they will not be included as possible symbs; possibles is a
16085: ref to a hash, which, as a side effect, will be populated with all possible 
16086: symbs (content blocking not tested).
16087:  
16088: returns the data handle
16089: 
16090: =item *
16091: 
16092: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16093: and is a possible symb for the URL in $thisfn, and if is an encrypted
16094: resource that the user accessed using /enc/ returns a 1 on success, 0
16095: on failure, user must be in a course, as it assumes the existence of
16096: the course initial hash, and uses $env('request.course.id'}.  The third
16097: arg is an optional reference to a scalar.  If this arg is passed in the 
16098: call to symbverify, it will be set to 1 if the symb has been set to be 
16099: encrypted; otherwise it will be null.  
16100: 
16101: =item *
16102: 
16103: symbclean($symb) : removes versions numbers from a symb, returns the
16104: cleaned symb
16105: 
16106: =item *
16107: 
16108: is_on_map($uri) : checks if the $uri is somewhere on the current
16109: course map, user must be in a course for it to work.
16110: 
16111: =item *
16112: 
16113: numval($salt) : return random seed value (addend for rndseed)
16114: 
16115: =item *
16116: 
16117: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16118: a random seed, all arguments are optional, if they aren't sent it uses the
16119: environment to derive them. Note: if symb isn't sent and it can't get one
16120: from &symbread it will use the current time as its return value
16121: 
16122: =item *
16123: 
16124: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16125: unfakeable, receipt
16126: 
16127: =item *
16128: 
16129: receipt() : API to ireceipt working off of env values; given out to users
16130: 
16131: =item *
16132: 
16133: countacc($url) : count the number of accesses to a given URL
16134: 
16135: =item *
16136: 
16137: 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
16138: 
16139: =item *
16140: 
16141: 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)
16142: 
16143: =item *
16144: 
16145: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16146: 
16147: =item *
16148: 
16149: devalidate($symb) : devalidate temporary spreadsheet calculations,
16150: forcing spreadsheet to reevaluate the resource scores next time.
16151: 
16152: =item * 
16153: 
16154: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16155: when viewing in course context.
16156: 
16157:  input: six args -- filename (decluttered), course number, course domain,
16158:                     url, symb (if registered) and group (if this is a 
16159:                     group item -- e.g., bulletin board, group page etc.).
16160: 
16161:  output: array of five scalars --
16162:          $cfile -- url for file editing if editable on current server
16163:          $home -- homeserver of resource (i.e., for author if published,
16164:                                           or course if uploaded.).
16165:          $switchserver --  1 if server switch will be needed.
16166:          $forceedit -- 1 if icon/link should be to go to edit mode 
16167:          $forceview -- 1 if icon/link should be to go to view mode
16168: 
16169: =item *
16170: 
16171: is_course_upload($file,$cnum,$cdom)
16172: 
16173: Used in course context to determine if current file was uploaded to 
16174: the course (i.e., would be found in /userfiles/docs on the course's 
16175: homeserver.
16176: 
16177:   input: 3 args -- filename (decluttered), course number and course domain.
16178:   output: boolean -- 1 if file was uploaded.
16179: 
16180: =back
16181: 
16182: =head2 Storing/Retreiving Data
16183: 
16184: =over 4
16185: 
16186: =item *
16187: 
16188: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16189: permanently for this url; hashref needs to be given and should be a \%hashname;
16190: the remaining args aren't required and if they aren't passed or are '' they will
16191: be derived from the env (with the exception of $laststore, which is an 
16192: optional arg used when a user's submission is stored in grading).
16193: $laststore is $version=$timestamp, where $version is the most recent version
16194: number retrieved for the corresponding $symb in the $namespace db file, and
16195: $timestamp is the timestamp for that transaction (UNIX time).
16196: $laststore is currently only passed when cstore() is called by 
16197: structuretags::finalize_storage().
16198: 
16199: =item *
16200: 
16201: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16202: but uses critical subroutine
16203: 
16204: =item *
16205: 
16206: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16207: all args are optional
16208: 
16209: =item *
16210: 
16211: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
16212: dumps the complete (or key matching regexp) namespace into a hash
16213: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16214: normally &store()ed into
16215: 
16216: $range should be either an integer '100' (give me the first 100
16217:                                            matching records)
16218:               or be  two integers sperated by a - with no spaces
16219:                  '30-50' (give me the 30th through the 50th matching
16220:                           records)
16221: 
16222: 
16223: =item *
16224: 
16225: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16226: replaces a &store() version of data with a replacement set of data
16227: for a particular resource in a namespace passed in the $storehash hash 
16228: reference. If $tolog is true, the transaction is logged in the courselog
16229: with an action=PUTSTORE.
16230: 
16231: =item *
16232: 
16233: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16234: works very similar to store/cstore, but all data is stored in a
16235: temporary location and can be reset using tmpreset, $storehash should
16236: be a hash reference, returns nothing on success
16237: 
16238: =item *
16239: 
16240: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16241: similar to restore, but all data is stored in a temporary location and
16242: can be reset using tmpreset. Returns a hash of values on success,
16243: error string otherwise.
16244: 
16245: =item *
16246: 
16247: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16248: deltes all keys for $symb form the temporary storage hash.
16249: 
16250: =item *
16251: 
16252: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16253: reference filled in from namesp ($udom and $uname are optional)
16254: 
16255: =item *
16256: 
16257: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16258: namesp ($udom and $uname are optional)
16259: 
16260: =item *
16261: 
16262: dump($namespace,$udom,$uname,$regexp,$range) : 
16263: dumps the complete (or key matching regexp) namespace into a hash
16264: ($udom, $uname, $regexp, $range are optional)
16265: 
16266: $range should be either an integer '100' (give me the first 100
16267:                                            matching records)
16268:               or be  two integers sperated by a - with no spaces
16269:                  '30-50' (give me the 30th through the 50th matching
16270:                           records)
16271: =item *
16272: 
16273: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16274: $store can be a scalar, an array reference, or if the amount to be 
16275: incremented is > 1, a hash reference.
16276: 
16277: ($udom and $uname are optional)
16278: 
16279: =item *
16280: 
16281: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16282: ($udom and $uname are optional)
16283: 
16284: =item *
16285: 
16286: cput($namespace,$storehash,$udom,$uname) : critical put
16287: ($udom and $uname are optional)
16288: 
16289: =item *
16290: 
16291: newput($namespace,$storehash,$udom,$uname) :
16292: 
16293: Attempts to store the items in the $storehash, but only if they don't
16294: currently exist, if this succeeds you can be certain that you have 
16295: successfully created a new key value pair in the $namespace db.
16296: 
16297: 
16298: Args:
16299:  $namespace: name of database to store values to
16300:  $storehash: hashref to store to the db
16301:  $udom: (optional) domain of user containing the db
16302:  $uname: (optional) name of user caontaining the db
16303: 
16304: Returns:
16305:  'ok' -> succeeded in storing all keys of $storehash
16306:  'key_exists: <key>' -> failed to anything out of $storehash, as at
16307:                         least <key> already existed in the db (other
16308:                         requested keys may also already exist)
16309:  'error: <msg>' -> unable to tie the DB or other error occurred
16310:  'con_lost' -> unable to contact request server
16311:  'refused' -> action was not allowed by remote machine
16312: 
16313: 
16314: =item *
16315: 
16316: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16317: reference filled in from namesp (encrypts the return communication)
16318: ($udom and $uname are optional)
16319: 
16320: =item *
16321: 
16322: log($udom,$name,$home,$message) : write to permanent log for user; use
16323: critical subroutine
16324: 
16325: =item *
16326: 
16327: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16328: array reference filled in from namespace found in domain level on either
16329: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16330: 
16331: =item *
16332: 
16333: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16334: domain level either on specified domain server ($uhome) or primary domain 
16335: server ($udom and $uhome are optional)
16336: 
16337: =item * 
16338: 
16339: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16340: for: authentication, language, quotas, timezone, date locale, and portal URL in
16341: the target domain.
16342: 
16343: May also include additional key => value pairs for the following groups:
16344: 
16345: =over
16346: 
16347: =item
16348: disk quotas (MB allocated by default to portfolios and authoring spaces).
16349: 
16350: =over
16351: 
16352: =item defaultquota, authorquota
16353: 
16354: =back
16355: 
16356: =item
16357: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16358: portfolio for users).
16359: 
16360: =over
16361: 
16362: =item
16363: aboutme, blog, webdav, portfolio
16364: 
16365: =back
16366: 
16367: =item
16368: requestcourses: ability to request courses, and how requests are processed.
16369: 
16370: =over
16371: 
16372: =item
16373: official, unofficial, community, textbook, placement
16374: 
16375: =back
16376: 
16377: =item
16378: inststatus: types of institutional affiliation, and order in which they are displayed.
16379: 
16380: =over
16381: 
16382: =item
16383: inststatustypes, inststatusorder, inststatusguest
16384: 
16385: =back
16386: 
16387: =item
16388: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16389: for course's uploaded content.
16390: 
16391: =over
16392: 
16393: =item
16394: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16395: communityquota, textbookquota, placementquota
16396: 
16397: =back
16398: 
16399: =item
16400: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16401: on your servers.
16402: 
16403: =over
16404: 
16405: =item 
16406: remotesessions, hostedsessions
16407: 
16408: =back
16409: 
16410: =back
16411: 
16412: In cases where a domain coordinator has never used the "Set Domain Configuration"
16413: utility to create a configuration.db file on a domain's primary library server 
16414: only the following domain defaults: auth_def, auth_arg_def, lang_def
16415: -- corresponding values are authentication type (internal, krb4, krb5,
16416: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16417: will be available. Values are retrieved from cache (if current), unless the
16418: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16419: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16420: 
16421: Typical usage:
16422: 
16423: %domdefaults = &get_domain_defaults($target_domain);
16424: 
16425: =back
16426: 
16427: =head2 Network Status Functions
16428: 
16429: =over 4
16430: 
16431: =item *
16432: 
16433: dirlist() : return directory list based on URI (first arg).
16434: 
16435: Inputs: 1 required, 5 optional.
16436: 
16437: =over
16438: 
16439: =item 
16440: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16441: 
16442: =item
16443: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16444: 
16445: =item
16446: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16447: 
16448: =item
16449: $getpropath - boolean: 1 if prepend path using &propath(). 
16450: 
16451: =item
16452: $getuserdir - boolean: 1 if prepend path for "userfiles".
16453: 
16454: =item 
16455: $alternateRoot - path to prepend in place of path from $uri.
16456: 
16457: =back
16458: 
16459: Returns: Array of up to two items.
16460: 
16461: =over
16462: 
16463: a reference to an array of files/subdirectories
16464: 
16465: =over
16466: 
16467: Each element in the array of files/subdirectories is a & separated list of
16468: item name and the result of running stat on the item.  If dirlist was requested
16469: for a file instead of a directory, the item name will be ''. For a directory 
16470: listing, if the item is a metadata file, the element will end &N&M 
16471: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16472: default copyright set (1).  
16473: 
16474: =back
16475: 
16476: a scalar containing error condition (if encountered).
16477: 
16478: =over
16479: 
16480: =item 
16481: no_host (no homeserver identified for $username:$domain).
16482: 
16483: =item 
16484: no_such_host (server contacted for listing not identified as valid host).
16485: 
16486: =item 
16487: con_lost (connection to remote server failed).
16488: 
16489: =item 
16490: refused (invalid $username:$domain received on lond side).
16491: 
16492: =item 
16493: no_such_dir (directory at specified path on lond side does not exist). 
16494: 
16495: =item 
16496: empty (directory at specified path on lond side is empty).
16497: 
16498: =over
16499: 
16500: This is currently not encountered because the &ls3, &ls2, 
16501: &ls (_handler) routines on the lond side do not filter out
16502: . and .. from a directory listing. 
16503: 
16504: =back
16505: 
16506: =back
16507: 
16508: =back
16509: 
16510: =item *
16511: 
16512: spareserver() : find server with least workload from spare.tab
16513: 
16514: 
16515: =item *
16516: 
16517: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16518: if there is no corresponding loncapa host.
16519: 
16520: =back
16521: 
16522: 
16523: =head2 Apache Request
16524: 
16525: =over 4
16526: 
16527: =item *
16528: 
16529: ssi($url,%hash) : server side include, does a complete request cycle on url to
16530: localhost, posts hash
16531: 
16532: =back
16533: 
16534: =head2 Data to String to Data
16535: 
16536: =over 4
16537: 
16538: =item *
16539: 
16540: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16541: and '&' separators, supports elements that are arrayrefs and hashrefs
16542: 
16543: =item *
16544: 
16545: hashref2str($hashref) : convert a hashref into a string complete with
16546: escaping and '=' and '&' separators, supports elements that are
16547: arrayrefs and hashrefs
16548: 
16549: =item *
16550: 
16551: arrayref2str($arrayref) : convert an arrayref into a string complete
16552: with escaping and '&' separators, supports elements that are arrayrefs
16553: and hashrefs
16554: 
16555: =item *
16556: 
16557: str2hash($string) : convert string to hash using unescaping and
16558: splitting on '=' and '&', supports elements that are arrayrefs and
16559: hashrefs
16560: 
16561: =item *
16562: 
16563: str2array($string) : convert string to hash using unescaping and
16564: splitting on '&', supports elements that are arrayrefs and hashrefs
16565: 
16566: =back
16567: 
16568: =head2 Logging Routines
16569: 
16570: 
16571: These routines allow one to make log messages in the lonnet.log and
16572: lonnet.perm logfiles.
16573: 
16574: =over 4
16575: 
16576: =item *
16577: 
16578: logtouch() : make sure the logfile, lonnet.log, exists
16579: 
16580: =item *
16581: 
16582: logthis() : append message to the normal lonnet.log file, it gets
16583: preiodically rolled over and deleted.
16584: 
16585: =item *
16586: 
16587: logperm() : append a permanent message to lonnet.perm.log, this log
16588: file never gets deleted by any automated portion of the system, only
16589: messages of critical importance should go in here.
16590: 
16591: 
16592: =back
16593: 
16594: =head2 General File Helper Routines
16595: 
16596: =over 4
16597: 
16598: =item *
16599: 
16600: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16601: (a) files in /uploaded
16602:   (i) If a local copy of the file exists - 
16603:       compares modification date of local copy with last-modified date for 
16604:       definitive version stored on home server for course. If local copy is 
16605:       stale, requests a new version from the home server and stores it. 
16606:       If the original has been removed from the home server, then local copy 
16607:       is unlinked.
16608:   (ii) If local copy does not exist -
16609:       requests the file from the home server and stores it. 
16610:   
16611:   If $caller is 'uploadrep':  
16612:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16613:     for request for files originally uploaded via DOCS. 
16614:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16615:   
16616:   Otherwise:
16617:      This indicates a call from the content generation phase of the request.
16618:      -  returns the entire contents of the file or -1.
16619:      
16620: (b) files in /res
16621:    - returns the entire contents of a file or -1; 
16622:    it properly subscribes to and replicates the file if neccessary.
16623: 
16624: 
16625: =item *
16626: 
16627: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16628:                   reference
16629: 
16630: returns either a stat() list of data about the file or an empty list
16631: if the file doesn't exist or couldn't find out about it (connection
16632: problems or user unknown)
16633: 
16634: =item *
16635: 
16636: filelocation($dir,$file) : returns file system location of a file
16637: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16638: directory that relative $file lookups are to looked in ($dir of /a/dir
16639: and a file of ../bob will become /a/bob)
16640: 
16641: =item *
16642: 
16643: hreflocation($dir,$file) : returns file system location or a URL; same as
16644: filelocation except for hrefs
16645: 
16646: =item *
16647: 
16648: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16649: also removes beginning /home/httpd/html unless /priv/ follows it.
16650: 
16651: =back
16652: 
16653: =head2 Usererfile file routines (/uploaded*)
16654: 
16655: =over 4
16656: 
16657: =item *
16658: 
16659: userfileupload(): main rotine for putting a file in a user or course's
16660:                   filespace, arguments are,
16661: 
16662:  formname - required - this is the name of the element in $env where the
16663:            filename, and the contents of the file to create/modifed exist
16664:            the filename is in $env{'form.'.$formname.'.filename'} and the
16665:            contents of the file is located in $env{'form.'.$formname}
16666:  context - if coursedoc, store the file in the course of the active role
16667:              of the current user; 
16668:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16669:            if 'canceloverwrite': delete file in tmp/overwrites directory
16670:  subdir - required - subdirectory to put the file in under ../userfiles/
16671:          if undefined, it will be placed in "unknown"
16672: 
16673:  (This routine calls clean_filename() to remove any dangerous
16674:  characters from the filename, and then calls finuserfileupload() to
16675:  complete the transaction)
16676: 
16677:  returns either the url of the uploaded file (/uploaded/....) if successful
16678:  and /adm/notfound.html if unsuccessful
16679: 
16680: =item *
16681: 
16682: clean_filename(): routine for cleaing a filename up for storage in
16683:                  userfile space, argument is:
16684: 
16685:  filename - proposed filename
16686: 
16687: returns: the new clean filename
16688: 
16689: =item *
16690: 
16691: finishuserfileupload(): routine that creates and sends the file to
16692: userspace, probably shouldn't be called directly
16693: 
16694:   docuname: username or courseid of destination for the file
16695:   docudom: domain of user/course of destination for the file
16696:   formname: same as for userfileupload()
16697:   fname: filename (including subdirectories) for the file
16698:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16699:           if hashref, and context is scantron, will convert csv format to standard format
16700:   allfiles: reference to hash used to store objects found by parser
16701:   codebase: reference to hash used for codebases of java objects found by parser
16702:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16703:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16704:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16705:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16706:   context: if 'overwrite', will move the uploaded file from its temporary location to
16707:             userfiles to facilitate overwriting a previously uploaded file with same name.
16708:   mimetype: reference to scalar to accommodate mime type determined
16709:             from File::MMagic if $parser = parse.
16710: 
16711:  returns either the url of the uploaded file (/uploaded/....) if successful
16712:  and /adm/notfound.html if unsuccessful (or an error message if context 
16713:  was 'overwrite').
16714:  
16715: 
16716: =item *
16717: 
16718: renameuserfile(): renames an existing userfile to a new name
16719: 
16720:   Args:
16721:    docuname: username or courseid of destination for the file
16722:    docudom: domain of user/course of destination for the file
16723:    old: current file name (including any subdirs under userfiles)
16724:    new: desired file name (including any subdirs under userfiles)
16725: 
16726: =item *
16727: 
16728: mkdiruserfile(): creates a directory is a userfiles dir
16729: 
16730:   Args:
16731:    docuname: username or courseid of destination for the file
16732:    docudom: domain of user/course of destination for the file
16733:    dir: dir to create (including any subdirs under userfiles)
16734: 
16735: =item *
16736: 
16737: removeuserfile(): removes a file that exists in userfiles
16738: 
16739:   Args:
16740:    docuname: username or courseid of destination for the file
16741:    docudom: domain of user/course of destination for the file
16742:    fname: filname to delete (including any subdirs under userfiles)
16743: 
16744: =item *
16745: 
16746: removeuploadedurl(): convience function for removeuserfile()
16747: 
16748:   Args:
16749:    url:  a full /uploaded/... url to delete
16750: 
16751: =item * 
16752: 
16753: get_portfile_permissions():
16754:   Args:
16755:     domain: domain of user or course contain the portfolio files
16756:     user: name of user or num of course contain the portfolio files
16757:   Returns:
16758:     hashref of a dump of the proper file_permissions.db
16759:    
16760: 
16761: =item * 
16762: 
16763: get_access_controls():
16764: 
16765: Args:
16766:   current_permissions: the hash ref returned from get_portfile_permissions()
16767:   group: (optional) the group you want the files associated with
16768:   file: (optional) the file you want access info on
16769: 
16770: Returns:
16771:     a hash (keys are file names) of hashes containing
16772:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16773:         values are XML containing access control settings (see below) 
16774: 
16775: Internal notes:
16776: 
16777:  access controls are stored in file_permissions.db as key=value pairs.
16778:     key -> path to file/file_name\0uniqueID:scope_end_start
16779:         where scope -> public,guest,course,group,domains or users.
16780:               end -> UNIX time for end of access (0 -> no end date)
16781:               start -> UNIX time for start of access
16782: 
16783:     value -> XML description of access control
16784:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16785:             <start></start>
16786:             <end></end>
16787: 
16788:             <password></password>  for scope type = guest
16789: 
16790:             <domain></domain>     for scope type = course or group
16791:             <number></number>
16792:             <roles id="">
16793:              <role></role>
16794:              <access></access>
16795:              <section></section>
16796:              <group></group>
16797:             </roles>
16798: 
16799:             <dom></dom>         for scope type = domains
16800: 
16801:             <users>             for scope type = users
16802:              <user>
16803:               <uname></uname>
16804:               <udom></udom>
16805:              </user>
16806:             </users>
16807:            </scope> 
16808:               
16809:  Access data is also aggregated for each file in an additional key=value pair:
16810:  key -> path to file/file_name\0accesscontrol 
16811:  value -> reference to hash
16812:           hash contains key = value pairs
16813:           where key = uniqueID:scope_end_start
16814:                 value = UNIX time record was last updated
16815: 
16816:           Used to improve speed of look-ups of access controls for each file.  
16817:  
16818:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16819: 
16820: =item *
16821: 
16822: modify_access_controls():
16823: 
16824: Modifies access controls for a portfolio file
16825: Args
16826: 1. file name
16827: 2. reference to hash of required changes,
16828: 3. domain
16829: 4. username
16830:   where domain,username are the domain of the portfolio owner 
16831:   (either a user or a course) 
16832: 
16833: Returns:
16834: 1. result of additions or updates ('ok' or 'error', with error message). 
16835: 2. result of deletions ('ok' or 'error', with error message).
16836: 3. reference to hash of any new or updated access controls.
16837: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16838:    key = integer (inbound ID)
16839:    value = uniqueID
16840: 
16841: =item *
16842: 
16843: get_timebased_id():
16844: 
16845: Attempts to get a unique timestamp-based suffix for use with items added to a 
16846: course via the Course Editor (e.g., folders, composite pages, 
16847: group bulletin boards).
16848: 
16849: Args: (first three required; six others optional)
16850: 
16851: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16852:    docssequence, or name of group
16853: 
16854: 2. keyid (alphanumeric): name of temporary locking key in hash,
16855:    e.g., num, boardids
16856: 
16857: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16858:    file will be named nohist_namespace.db
16859: 
16860: 4. cdom: domain of course; default is current course domain from %env
16861: 
16862: 5. cnum: course number; default is current course number from %env
16863: 
16864: 6. idtype: set to concat if an additional digit is to be appended to the 
16865:    unix timestamp to form the suffix, if the plain timestamp is already
16866:    in use.  Default is to not do this, but simply increment the unix 
16867:    timestamp by 1 until a unique key is obtained.
16868: 
16869: 7. who: holder of locking key; defaults to user:domain for user.
16870: 
16871: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16872:    retrying); default is 3.
16873: 
16874: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16875: 
16876: Returns:
16877: 
16878: 1. suffix obtained (numeric)
16879: 
16880: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16881: 
16882: 3. error: contains (localized) error message if an error occurred.
16883: 
16884: 
16885: =back
16886: 
16887: =head2 HTTP Helper Routines
16888: 
16889: =over 4
16890: 
16891: =item *
16892: 
16893: escape() : unpack non-word characters into CGI-compatible hex codes
16894: 
16895: =item *
16896: 
16897: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16898: 
16899: =back
16900: 
16901: =head1 PRIVATE SUBROUTINES
16902: 
16903: =head2 Underlying communication routines (Shouldn't call)
16904: 
16905: =over 4
16906: 
16907: =item *
16908: 
16909: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16910: 
16911: =item *
16912: 
16913: reply() : uses subreply to send a message to remote machine, logs all failures
16914: 
16915: =item *
16916: 
16917: critical() : passes a critical message to another server; if cannot
16918: get through then place message in connection buffer directory and
16919: returns con_delayed, if incapable of saving message, returns
16920: con_failed
16921: 
16922: =item *
16923: 
16924: reconlonc() : tries to reconnect lonc client processes.
16925: 
16926: =back
16927: 
16928: =head2 Resource Access Logging
16929: 
16930: =over 4
16931: 
16932: =item *
16933: 
16934: flushcourselogs() : flush (save) buffer logs and access logs
16935: 
16936: =item *
16937: 
16938: courselog($what) : save message for course in hash
16939: 
16940: =item *
16941: 
16942: courseacclog($what) : save message for course using &courselog().  Perform
16943: special processing for specific resource types (problems, exams, quizzes, etc).
16944: 
16945: =item *
16946: 
16947: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16948: as a PerlChildExitHandler
16949: 
16950: =back
16951: 
16952: =head2 Other
16953: 
16954: =over 4
16955: 
16956: =item *
16957: 
16958: symblist($mapname,%newhash) : update symbolic storage links
16959: 
16960: =back
16961: 
16962: =cut
16963: 

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