File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1441: download - view: text, annotated - select for diffs
Mon Feb 8 14:10:17 2021 UTC (3 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Retrieval of requestor's IP address centralized in lonnet::get_requestor_ip()

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1441 2021/02/08 14:10:17 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) {
 1449:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1450:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1451:                 unless (&shared_institution($udom,$try_server)) {
 1452:                     $canhost = 0;
 1453:                 }
 1454:             }
 1455:         }
 1456:     }
 1457:     if (($canhost) && ($uint_dom)) {
 1458:         my @intdoms;
 1459:         my $internet_names = &get_internet_names($try_server);
 1460:         if (ref($internet_names) eq 'ARRAY') {
 1461:             @intdoms = @{$internet_names};
 1462:         }
 1463:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1464:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1465:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1466:                                          $remotesessions,
 1467:                                          $defdomdefaults{'hostedsessions'});
 1468:         }
 1469:     }
 1470:     return $canhost;
 1471: }
 1472: 
 1473: sub this_host_spares {
 1474:     my ($dom) = @_;
 1475:     my ($dom_in_use,$lonhost_in_use,$result);
 1476:     my @hosts = &current_machine_ids();
 1477:     foreach my $lonhost (@hosts) {
 1478:         if (&host_domain($lonhost) eq $dom) {
 1479:             $dom_in_use = $dom;
 1480:             $lonhost_in_use = $lonhost;
 1481:             last;
 1482:         }
 1483:     }
 1484:     if ($dom_in_use ne '') {
 1485:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1486:     }
 1487:     if (ref($result) ne 'HASH') {
 1488:         $lonhost_in_use = $perlvar{'lonHostID'};
 1489:         $dom_in_use = &host_domain($lonhost_in_use);
 1490:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1491:         if (ref($result) ne 'HASH') {
 1492:             $result = \%spareid;
 1493:         }
 1494:     }
 1495:     return $result;
 1496: }
 1497: 
 1498: sub spares_for_offload  {
 1499:     my ($dom_in_use,$lonhost_in_use) = @_;
 1500:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1501:     if (defined($cached)) {
 1502:         return $result;
 1503:     } else {
 1504:         my $cachetime = 60*60*24;
 1505:         my %domconfig =
 1506:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1507:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1508:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1509:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1510:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1511:                 }
 1512:             }
 1513:         }
 1514:     }
 1515:     return;
 1516: }
 1517: 
 1518: sub get_lonbalancer_config {
 1519:     my ($servers) = @_;
 1520:     my ($currbalancer,$currtargets);
 1521:     if (ref($servers) eq 'HASH') {
 1522:         foreach my $server (keys(%{$servers})) {
 1523:             my %what = (
 1524:                          spareid => 1,
 1525:                          perlvar => 1,
 1526:                        );
 1527:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1528:             if ($result eq 'ok') {
 1529:                 if (ref($returnhash) eq 'HASH') {
 1530:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1531:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1532:                             $currbalancer = $server;
 1533:                             $currtargets = {};
 1534:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1535:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1536:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1537:                                 }
 1538:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1539:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1540:                                 }
 1541:                             }
 1542:                             last;
 1543:                         }
 1544:                     }
 1545:                 }
 1546:             }
 1547:         }
 1548:     }
 1549:     return ($currbalancer,$currtargets);
 1550: }
 1551: 
 1552: sub check_loadbalancing {
 1553:     my ($uname,$udom,$caller) = @_;
 1554:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1555:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1556:     my $lonhost = $perlvar{'lonHostID'};
 1557:     my @hosts = &current_machine_ids();
 1558:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1559:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1560:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1561:     my $serverhomedom = &host_domain($lonhost);
 1562:     my $domneedscache;
 1563:     my $cachetime = 60*60*24;
 1564: 
 1565:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1566:         $dom_in_use = $udom;
 1567:         $homeintdom = 1;
 1568:     } else {
 1569:         $dom_in_use = $serverhomedom;
 1570:     }
 1571:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1572:     unless (defined($cached)) {
 1573:         my %domconfig =
 1574:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1575:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1576:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1577:         } else {
 1578:             $domneedscache = $dom_in_use;
 1579:         }
 1580:     }
 1581:     if (ref($result) eq 'HASH') {
 1582:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1583:             &check_balancer_result($result,@hosts);
 1584:         if ($is_balancer) {
 1585:             if (ref($currrules) eq 'HASH') {
 1586:                 if ($homeintdom) {
 1587:                     if ($uname ne '') {
 1588:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1589:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1590:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1591:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1592:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1593:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1594:                             }
 1595:                         }
 1596:                         if ($rule_in_effect eq '') {
 1597:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1598:                             if ($userenv{'inststatus'} ne '') {
 1599:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1600:                                 my ($othertitle,$usertypes,$types) =
 1601:                                     &Apache::loncommon::sorted_inst_types($udom);
 1602:                                 if (ref($types) eq 'ARRAY') {
 1603:                                     foreach my $type (@{$types}) {
 1604:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1605:                                             if (exists($currrules->{$type})) {
 1606:                                                 $rule_in_effect = $currrules->{$type};
 1607:                                             }
 1608:                                         }
 1609:                                     }
 1610:                                 }
 1611:                             } else {
 1612:                                 if (exists($currrules->{'default'})) {
 1613:                                     $rule_in_effect = $currrules->{'default'};
 1614:                                 }
 1615:                             }
 1616:                         }
 1617:                     } else {
 1618:                         if (exists($currrules->{'default'})) {
 1619:                             $rule_in_effect = $currrules->{'default'};
 1620:                         }
 1621:                     }
 1622:                 } else {
 1623:                     if ($currrules->{'_LC_external'} ne '') {
 1624:                         $rule_in_effect = $currrules->{'_LC_external'};
 1625:                     }
 1626:                 }
 1627:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1628:                                                        $uname,$udom);
 1629:             }
 1630:         }
 1631:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1632:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1633:         unless (defined($cached)) {
 1634:             my %domconfig =
 1635:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1636:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1637:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1638:             } else {
 1639:                 $domneedscache = $serverhomedom;
 1640:             }
 1641:         }
 1642:         if (ref($result) eq 'HASH') {
 1643:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1644:                 &check_balancer_result($result,@hosts);
 1645:             if ($is_balancer) {
 1646:                 if (ref($currrules) eq 'HASH') {
 1647:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1648:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1649:                     }
 1650:                 }
 1651:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1652:                                                        $uname,$udom);
 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:     } else {
 1664:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1665:             $is_balancer = 1;
 1666:             $offloadto = &this_host_spares($dom_in_use);
 1667:         }
 1668:         unless (defined($cached)) {
 1669:             $domneedscache = $serverhomedom;
 1670:         }
 1671:     }
 1672:     if ($domneedscache) {
 1673:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1674:     }
 1675:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1676:         my $lowest_load = 30000;
 1677:         if (ref($offloadto) eq 'HASH') {
 1678:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1679:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1680:                     ($otherserver,$lowest_load) =
 1681:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1682:                 }
 1683:             }
 1684:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1685: 
 1686:             if (!$found_server) {
 1687:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1688:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1689:                         ($otherserver,$lowest_load) =
 1690:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1691:                     }
 1692:                 }
 1693:             }
 1694:         } elsif (ref($offloadto) eq 'ARRAY') {
 1695:             if (@{$offloadto} == 1) {
 1696:                 $otherserver = $offloadto->[0];
 1697:             } elsif (@{$offloadto} > 1) {
 1698:                 foreach my $try_server (@{$offloadto}) {
 1699:                     ($otherserver,$lowest_load) =
 1700:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1701:                 }
 1702:             }
 1703:         }
 1704:         unless ($caller eq 'login') {
 1705:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1706:                 $is_balancer = 0;
 1707:                 if ($uname ne '' && $udom ne '') {
 1708:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1709:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1710:                                  'user.loadbalcheck.time' => time});
 1711:                     }
 1712:                 }
 1713:             }
 1714:         }
 1715:     }
 1716:     if (($is_balancer) && (!$homeintdom)) {
 1717:         undef($setcookie);
 1718:     }
 1719:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1720: }
 1721: 
 1722: sub check_balancer_result {
 1723:     my ($result,@hosts) = @_;
 1724:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1725:     if (ref($result) eq 'HASH') {
 1726:         if ($result->{'lonhost'} ne '') {
 1727:             my $currbalancer = $result->{'lonhost'};
 1728:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1729:                 $is_balancer = 1;
 1730:                 $currtargets = $result->{'targets'};
 1731:                 $currrules = $result->{'rules'};
 1732:             }
 1733:             $dom_balancers = $currbalancer;
 1734:         } else {
 1735:             if (keys(%{$result})) {
 1736:                 foreach my $key (keys(%{$result})) {
 1737:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1738:                         (ref($result->{$key}) eq 'HASH')) {
 1739:                         $is_balancer = 1;
 1740:                         $currrules = $result->{$key}{'rules'};
 1741:                         $currtargets = $result->{$key}{'targets'};
 1742:                         $setcookie = $result->{$key}{'cookie'};
 1743:                         last;
 1744:                     }
 1745:                 }
 1746:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1747:             }
 1748:         }
 1749:     }
 1750:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1751: }
 1752: 
 1753: sub get_loadbalancer_targets {
 1754:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1755:     my $offloadto;
 1756:     if ($rule_in_effect eq 'none') {
 1757:         return [$perlvar{'lonHostID'}];
 1758:     } elsif ($rule_in_effect eq '') {
 1759:         $offloadto = $currtargets;
 1760:     } else {
 1761:         if ($rule_in_effect eq 'homeserver') {
 1762:             my $homeserver = &homeserver($uname,$udom);
 1763:             if ($homeserver ne 'no_host') {
 1764:                 $offloadto = [$homeserver];
 1765:             }
 1766:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1767:             my %domconfig =
 1768:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1769:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1770:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1771:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1772:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1773:                     }
 1774:                 }
 1775:             } else {
 1776:                 my %servers = &internet_dom_servers($udom);
 1777:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1778:                 if (&hostname($remotebalancer) ne '') {
 1779:                     $offloadto = [$remotebalancer];
 1780:                 }
 1781:             }
 1782:         } elsif (&hostname($rule_in_effect) ne '') {
 1783:             $offloadto = [$rule_in_effect];
 1784:         }
 1785:     }
 1786:     return $offloadto;
 1787: }
 1788: 
 1789: sub internet_dom_servers {
 1790:     my ($dom) = @_;
 1791:     my (%uniqservers,%servers);
 1792:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1793:     my @machinedoms = &machine_domains($primaryserver);
 1794:     foreach my $mdom (@machinedoms) {
 1795:         my %currservers = %servers;
 1796:         my %server = &get_servers($mdom);
 1797:         %servers = (%currservers,%server);
 1798:     }
 1799:     my %by_hostname;
 1800:     foreach my $id (keys(%servers)) {
 1801:         push(@{$by_hostname{$servers{$id}}},$id);
 1802:     }
 1803:     foreach my $hostname (sort(keys(%by_hostname))) {
 1804:         if (@{$by_hostname{$hostname}} > 1) {
 1805:             my $match = 0;
 1806:             foreach my $id (@{$by_hostname{$hostname}}) {
 1807:                 if (&host_domain($id) eq $dom) {
 1808:                     $uniqservers{$id} = $hostname;
 1809:                     $match = 1;
 1810:                 }
 1811:             }
 1812:             unless ($match) {
 1813:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1814:             }
 1815:         } else {
 1816:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1817:         }
 1818:     }
 1819:     return %uniqservers;
 1820: }
 1821: 
 1822: sub trusted_domains {
 1823:     my ($cmdtype,$calldom) = @_;
 1824:     my ($trusted,$untrusted);
 1825:     if (&domain($calldom) eq '') {
 1826:         return ($trusted,$untrusted);
 1827:     }
 1828:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1829:         return ($trusted,$untrusted);
 1830:     }
 1831:     my $callprimary = &domain($calldom,'primary');
 1832:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1833:     if ($intcalldom eq '') {
 1834:         return ($trusted,$untrusted);
 1835:     }
 1836: 
 1837:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1838:     unless (defined($cached)) {
 1839:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1840:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1841:         $trustconfig = $domconfig{'trust'};
 1842:     }
 1843:     if (ref($trustconfig)) {
 1844:         my (%possexc,%possinc,@allexc,@allinc); 
 1845:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1846:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1847:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1848:             }
 1849:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1850:                 $possinc{$intcalldom} = 1;
 1851:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1852:             }
 1853:         }
 1854:         if (keys(%possexc)) {
 1855:             if (keys(%possinc)) {
 1856:                 foreach my $key (sort(keys(%possexc))) {
 1857:                     next if ($key eq $intcalldom);
 1858:                     unless ($possinc{$key}) {
 1859:                         push(@allexc,$key);
 1860:                     }
 1861:                 }
 1862:             } else {
 1863:                 @allexc = sort(keys(%possexc));
 1864:             }
 1865:         }
 1866:         if (keys(%possinc)) {
 1867:             $possinc{$intcalldom} = 1;
 1868:             @allinc = sort(keys(%possinc));
 1869:         }
 1870:         if ((@allexc > 0) || (@allinc > 0)) {
 1871:             my %doms_by_intdom;
 1872:             my %allintdoms = &all_host_intdom();
 1873:             my %alldoms = &all_host_domain();
 1874:             foreach my $key (%allintdoms) {
 1875:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1876:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1877:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1878:                     }
 1879:                 } else {
 1880:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1881:                 }
 1882:             }
 1883:             foreach my $exc (@allexc) {
 1884:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1885:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1886:                 }
 1887:             }
 1888:             foreach my $inc (@allinc) {
 1889:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1890:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1891:                 }
 1892:             }
 1893:         }
 1894:     }
 1895:     return ($trusted,$untrusted);
 1896: }
 1897: 
 1898: sub will_trust {
 1899:     my ($cmdtype,$domain,$possdom) = @_;
 1900:     return 1 if ($domain eq $possdom);
 1901:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1902:     my $willtrust; 
 1903:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1904:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1905:             $willtrust = 1;
 1906:         }
 1907:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1908:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1909:             $willtrust = 1;
 1910:         }
 1911:     } else {
 1912:         $willtrust = 1;
 1913:     }
 1914:     return $willtrust;
 1915: }
 1916: 
 1917: # ---------------------- Find the homebase for a user from domain's lib servers
 1918: 
 1919: my %homecache;
 1920: sub homeserver {
 1921:     my ($uname,$udom,$ignoreBadCache)=@_;
 1922:     my $index="$uname:$udom";
 1923: 
 1924:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1925: 
 1926:     my %servers = &get_servers($udom,'library');
 1927:     foreach my $tryserver (keys(%servers)) {
 1928:         next if ($ignoreBadCache ne 'true' && 
 1929: 		 exists($badServerCache{$tryserver}));
 1930: 
 1931: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1932: 	if ($answer eq 'found') {
 1933: 	    delete($badServerCache{$tryserver}); 
 1934: 	    return $homecache{$index}=$tryserver;
 1935: 	} elsif ($answer eq 'no_host') {
 1936: 	    $badServerCache{$tryserver}=1;
 1937: 	}
 1938:     }    
 1939:     return 'no_host';
 1940: }
 1941: 
 1942: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1943: 
 1944: sub idget {
 1945:     my ($udom,$idsref,$namespace)=@_;
 1946:     my %returnhash=();
 1947:     my @ids=(); 
 1948:     if (ref($idsref) eq 'ARRAY') {
 1949:         @ids = @{$idsref};
 1950:     } else {
 1951:         return %returnhash; 
 1952:     }
 1953:     if ($namespace eq '') {
 1954:         $namespace = 'ids';
 1955:     }
 1956:     
 1957:     my %servers = &get_servers($udom,'library');
 1958:     foreach my $tryserver (keys(%servers)) {
 1959: 	my $idlist=join('&', map { &escape($_); } @ids);
 1960: 	if ($namespace eq 'ids') {
 1961: 	    $idlist=~tr/A-Z/a-z/;
 1962: 	}
 1963: 	my $reply;
 1964: 	if ($namespace eq 'ids') {
 1965: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1966: 	} else {
 1967: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1968: 	}
 1969: 	my @answer=();
 1970: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1971: 	    @answer=split(/\&/,$reply);
 1972: 	}                    ;
 1973: 	my $i;
 1974: 	for ($i=0;$i<=$#ids;$i++) {
 1975: 	    if ($answer[$i]) {
 1976: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1977: 	    }
 1978: 	}
 1979:     }
 1980:     return %returnhash;
 1981: }
 1982: 
 1983: # ------------------------------------- Find the IDs behind a list of usernames
 1984: 
 1985: sub idrget {
 1986:     my ($udom,@unames)=@_;
 1987:     my %returnhash=();
 1988:     foreach my $uname (@unames) {
 1989:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1990:     }
 1991:     return %returnhash;
 1992: }
 1993: 
 1994: # Store away a list of names and associated student/employee IDs or clicker IDs
 1995: 
 1996: sub idput {
 1997:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1998:     my %servers=();
 1999:     my %ids=();
 2000:     my %byid = ();
 2001:     if (ref($idsref) eq 'HASH') {
 2002:         %ids=%{$idsref};
 2003:     }
 2004:     if ($namespace eq '') {
 2005:         $namespace = 'ids'; 
 2006:     }
 2007:     foreach my $uname (keys(%ids)) {
 2008: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 2009:         if ($uhom eq '') {
 2010:             $uhom=&homeserver($uname,$udom);
 2011:         }
 2012:         if ($uhom ne 'no_host') {
 2013:             my $esc_unam=&escape($uname);
 2014:             if ($namespace eq 'ids') {
 2015:                 my $id=&escape($ids{$uname});
 2016:                 $id=~tr/A-Z/a-z/;
 2017:                 my $esc_unam=&escape($uname);
 2018:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2019:             } else {
 2020:                 my @currids = split(/,/,$ids{$uname});
 2021:                 foreach my $id (@currids) {
 2022:                     $byid{$uhom}{$id} .= $uname.',';
 2023:                 }
 2024:             }
 2025:         }
 2026:     }
 2027:     if ($namespace eq 'clickers') {
 2028:         foreach my $server (keys(%byid)) {
 2029:             if (ref($byid{$server}) eq 'HASH') {
 2030:                 foreach my $id (keys(%{$byid{$server}})) {
 2031:                     $byid{$server} =~ s/,$//;
 2032:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2033:                 }
 2034:             }
 2035:         }
 2036:     }
 2037:     foreach my $server (keys(%servers)) {
 2038:         $servers{$server} =~ s/\&$//;
 2039:         if ($namespace eq 'ids') {     
 2040:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2041:         } else {
 2042:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2043:         }
 2044:     }
 2045: }
 2046: 
 2047: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2048: 
 2049: sub iddel {
 2050:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2051:     my %result=();
 2052:     my %ids=();
 2053:     my %byid = ();
 2054:     if (ref($idshashref) eq 'HASH') {
 2055:         %ids=%{$idshashref};
 2056:     } else {
 2057:         return %result;
 2058:     }
 2059:     if ($namespace eq '') {
 2060:         $namespace = 'ids';
 2061:     }
 2062:     my %servers=();
 2063:     while (my ($id,$unamestr) = each(%ids)) {
 2064:         if ($namespace eq 'ids') {
 2065:             my $uhom = $uhome;
 2066:             if ($uhom eq '') { 
 2067:                 $uhom=&homeserver($unamestr,$udom);
 2068:             }
 2069:             if ($uhom ne 'no_host') {
 2070:                 $servers{$uhom}.='&'.&escape($id);
 2071:             }
 2072:          } else {
 2073:             my @curritems = split(/,/,$ids{$id});
 2074:             foreach my $uname (@curritems) {
 2075:                 my $uhom = $uhome;
 2076:                 if ($uhom eq '') {
 2077:                     $uhom=&homeserver($uname,$udom);
 2078:                 }
 2079:                 if ($uhom ne 'no_host') { 
 2080:                     $byid{$uhom}{$id} .= $uname.',';
 2081:                 }
 2082:             }
 2083:         }
 2084:     }
 2085:     if ($namespace eq 'clickers') {
 2086:         foreach my $server (keys(%byid)) {
 2087:             if (ref($byid{$server}) eq 'HASH') {
 2088:                 foreach my $id (keys(%{$byid{$server}})) {
 2089:                     $byid{$server}{$id} =~ s/,$//;
 2090:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2091:                 }
 2092:             }
 2093:         }
 2094:     }
 2095:     foreach my $server (keys(%servers)) {
 2096:         $servers{$server} =~ s/\&$//;
 2097:         if ($namespace eq 'ids') {
 2098:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2099:         } elsif ($namespace eq 'clickers') {
 2100:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2101:         }
 2102:     }
 2103:     return %result;
 2104: }
 2105: 
 2106: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2107: 
 2108: sub updateclickers {
 2109:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2110:     my %clickers;
 2111:     if (ref($idshashref) eq 'HASH') {
 2112:         %clickers=%{$idshashref};
 2113:     } else {
 2114:         return;
 2115:     }
 2116:     my $items='';
 2117:     foreach my $item (keys(%clickers)) {
 2118:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2119:     }
 2120:     $items=~s/\&$//;
 2121:     my $request = "updateclickers:$udom:$action:$items";
 2122:     if ($critical) {
 2123:         return &critical($request,$uhome);
 2124:     } else {
 2125:         return &reply($request,$uhome);
 2126:     }
 2127: }
 2128: 
 2129: # ------------------------------dump from db file owned by domainconfig user
 2130: sub dump_dom {
 2131:     my ($namespace, $udom, $regexp) = @_;
 2132: 
 2133:     $udom ||= $env{'user.domain'};
 2134: 
 2135:     return () unless $udom;
 2136: 
 2137:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2138: }
 2139: 
 2140: # ------------------------------------------ get items from domain db files   
 2141: 
 2142: sub get_dom {
 2143:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2144:     return if ($udom eq 'public');
 2145:     my $items='';
 2146:     foreach my $item (@$storearr) {
 2147:         $items.=&escape($item).'&';
 2148:     }
 2149:     $items=~s/\&$//;
 2150:     if (!$udom) {
 2151:         $udom=$env{'user.domain'};
 2152:         return if ($udom eq 'public');
 2153:         if (defined(&domain($udom,'primary'))) {
 2154:             $uhome=&domain($udom,'primary');
 2155:         } else {
 2156:             undef($uhome);
 2157:         }
 2158:     } else {
 2159:         if (!$uhome) {
 2160:             if (defined(&domain($udom,'primary'))) {
 2161:                 $uhome=&domain($udom,'primary');
 2162:             }
 2163:         }
 2164:     }
 2165:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2166:         my $rep;
 2167:         if ($namespace =~ /^enc/) {
 2168:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2169:         } else {
 2170:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2171:         }
 2172:         my %returnhash;
 2173:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2174:             return %returnhash;
 2175:         }
 2176:         my @pairs=split(/\&/,$rep);
 2177:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2178:             return @pairs;
 2179:         }
 2180:         my $i=0;
 2181:         foreach my $item (@$storearr) {
 2182:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2183:             $i++;
 2184:         }
 2185:         return %returnhash;
 2186:     } else {
 2187:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2188:     }
 2189: }
 2190: 
 2191: # -------------------------------------------- put items in domain db files 
 2192: 
 2193: sub put_dom {
 2194:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2195:     if (!$udom) {
 2196:         $udom=$env{'user.domain'};
 2197:         if (defined(&domain($udom,'primary'))) {
 2198:             $uhome=&domain($udom,'primary');
 2199:         } else {
 2200:             undef($uhome);
 2201:         }
 2202:     } else {
 2203:         if (!$uhome) {
 2204:             if (defined(&domain($udom,'primary'))) {
 2205:                 $uhome=&domain($udom,'primary');
 2206:             }
 2207:         }
 2208:     } 
 2209:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2210:         my $items='';
 2211:         foreach my $item (keys(%$storehash)) {
 2212:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2213:         }
 2214:         $items=~s/\&$//;
 2215:         if ($namespace =~ /^enc/) {
 2216:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2217:         } else {
 2218:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2219:         }
 2220:     } else {
 2221:         &logthis("put_dom failed - no homeserver and/or domain");
 2222:     }
 2223: }
 2224: 
 2225: # --------------------- newput for items in db file owned by domainconfig user
 2226: sub newput_dom {
 2227:     my ($namespace,$storehash,$udom) = @_;
 2228:     my $result;
 2229:     if (!$udom) {
 2230:         $udom=$env{'user.domain'};
 2231:     }
 2232:     if ($udom) {
 2233:         my $uname = &get_domainconfiguser($udom);
 2234:         $result = &newput($namespace,$storehash,$udom,$uname);
 2235:     }
 2236:     return $result;
 2237: }
 2238: 
 2239: # --------------------- delete for items in db file owned by domainconfig user
 2240: sub del_dom {
 2241:     my ($namespace,$storearr,$udom)=@_;
 2242:     if (ref($storearr) eq 'ARRAY') {
 2243:         if (!$udom) {
 2244:             $udom=$env{'user.domain'};
 2245:         }
 2246:         if ($udom) {
 2247:             my $uname = &get_domainconfiguser($udom); 
 2248:             return &del($namespace,$storearr,$udom,$uname);
 2249:         }
 2250:     }
 2251: }
 2252: 
 2253: # ----------------------------------construct domainconfig user for a domain 
 2254: sub get_domainconfiguser {
 2255:     my ($udom) = @_;
 2256:     return $udom.'-domainconfig';
 2257: }
 2258: 
 2259: sub retrieve_inst_usertypes {
 2260:     my ($udom) = @_;
 2261:     my (%returnhash,@order);
 2262:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2263:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2264:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2265:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2266:     } else {
 2267:         if (defined(&domain($udom,'primary'))) {
 2268:             my $uhome=&domain($udom,'primary');
 2269:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2270:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2271:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2272:                 return (\%returnhash,\@order);
 2273:             }
 2274:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2275:             my @pairs=split(/\&/,$hashitems);
 2276:             foreach my $item (@pairs) {
 2277:                 my ($key,$value)=split(/=/,$item,2);
 2278:                 $key = &unescape($key);
 2279:                 next if ($key =~ /^error: 2 /);
 2280:                 $returnhash{$key}=&thaw_unescape($value);
 2281:             }
 2282:             my @esc_order = split(/\&/,$orderitems);
 2283:             foreach my $item (@esc_order) {
 2284:                 push(@order,&unescape($item));
 2285:             }
 2286:         } else {
 2287:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2288:         }
 2289:         return (\%returnhash,\@order);
 2290:     }
 2291: }
 2292: 
 2293: sub is_domainimage {
 2294:     my ($url) = @_;
 2295:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2296:         if (&domain($1) ne '') {
 2297:             return '1';
 2298:         }
 2299:     }
 2300:     return;
 2301: }
 2302: 
 2303: sub inst_directory_query {
 2304:     my ($srch) = @_;
 2305:     my $udom = $srch->{'srchdomain'};
 2306:     my %results;
 2307:     my $homeserver = &domain($udom,'primary');
 2308:     my $outcome;
 2309:     if ($homeserver ne '') {
 2310:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2311:             if ($srch->{'srchby'} eq 'email') {
 2312:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2313:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2314:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2315:                     (($major == 2) && ($minor < 12))) {
 2316:                     return;
 2317:                 }
 2318:             }
 2319:         }
 2320: 	my $queryid=&reply("querysend:instdirsearch:".
 2321: 			   &escape($srch->{'srchby'}).':'.
 2322: 			   &escape($srch->{'srchterm'}).':'.
 2323: 			   &escape($srch->{'srchtype'}),$homeserver);
 2324: 	my $host=&hostname($homeserver);
 2325: 	if ($queryid !~/^\Q$host\E\_/) {
 2326: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2327: 	    return;
 2328: 	}
 2329: 	my $response = &get_query_reply($queryid);
 2330: 	my $maxtries = 5;
 2331: 	my $tries = 1;
 2332: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2333: 	    $response = &get_query_reply($queryid);
 2334: 	    $tries ++;
 2335: 	}
 2336: 
 2337:         if (!&error($response) && $response ne 'refused') {
 2338:             if ($response eq 'unavailable') {
 2339:                 $outcome = $response;
 2340:             } else {
 2341:                 $outcome = 'ok';
 2342:                 my @matches = split(/\n/,$response);
 2343:                 foreach my $match (@matches) {
 2344:                     my ($key,$value) = split(/=/,$match);
 2345:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2346:                 }
 2347:             }
 2348:         }
 2349:     }
 2350:     return ($outcome,%results);
 2351: }
 2352: 
 2353: sub usersearch {
 2354:     my ($srch) = @_;
 2355:     my $dom = $srch->{'srchdomain'};
 2356:     my %results;
 2357:     my %libserv = &all_library();
 2358:     my $query = 'usersearch';
 2359:     foreach my $tryserver (keys(%libserv)) {
 2360:         if (&host_domain($tryserver) eq $dom) {
 2361:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2362:                 if ($srch->{'srchby'} eq 'email') {
 2363:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2364:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2365:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2366:                              (($major == 2) && ($minor < 12)));
 2367:                 }
 2368:             }
 2369:             my $host=&hostname($tryserver);
 2370:             my $queryid=
 2371:                 &reply("querysend:".&escape($query).':'.
 2372:                        &escape($srch->{'srchby'}).':'.
 2373:                        &escape($srch->{'srchtype'}).':'.
 2374:                        &escape($srch->{'srchterm'}),$tryserver);
 2375:             if ($queryid !~/^\Q$host\E\_/) {
 2376:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2377:                 next;
 2378:             }
 2379:             my $reply = &get_query_reply($queryid);
 2380:             my $maxtries = 1;
 2381:             my $tries = 1;
 2382:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2383:                 $reply = &get_query_reply($queryid);
 2384:                 $tries ++;
 2385:             }
 2386:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2387:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2388:             } else {
 2389:                 my @matches;
 2390:                 if ($reply =~ /\n/) {
 2391:                     @matches = split(/\n/,$reply);
 2392:                 } else {
 2393:                     @matches = split(/\&/,$reply);
 2394:                 }
 2395:                 foreach my $match (@matches) {
 2396:                     my ($uname,$udom,%userhash);
 2397:                     foreach my $entry (split(/:/,$match)) {
 2398:                         my ($key,$value) =
 2399:                             map {&unescape($_);} split(/=/,$entry);
 2400:                         $userhash{$key} = $value;
 2401:                         if ($key eq 'username') {
 2402:                             $uname = $value;
 2403:                         } elsif ($key eq 'domain') {
 2404:                             $udom = $value;
 2405:                         }
 2406:                     }
 2407:                     $results{$uname.':'.$udom} = \%userhash;
 2408:                 }
 2409:             }
 2410:         }
 2411:     }
 2412:     return %results;
 2413: }
 2414: 
 2415: sub get_instuser {
 2416:     my ($udom,$uname,$id) = @_;
 2417:     my $homeserver = &domain($udom,'primary');
 2418:     my ($outcome,%results);
 2419:     if ($homeserver ne '') {
 2420:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2421:                            &escape($id).':'.&escape($udom),$homeserver);
 2422:         my $host=&hostname($homeserver);
 2423:         if ($queryid !~/^\Q$host\E\_/) {
 2424:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2425:             return;
 2426:         }
 2427:         my $response = &get_query_reply($queryid);
 2428:         my $maxtries = 5;
 2429:         my $tries = 1;
 2430:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2431:             $response = &get_query_reply($queryid);
 2432:             $tries ++;
 2433:         }
 2434:         if (!&error($response) && $response ne 'refused') {
 2435:             if ($response eq 'unavailable') {
 2436:                 $outcome = $response;
 2437:             } else {
 2438:                 $outcome = 'ok';
 2439:                 my @matches = split(/\n/,$response);
 2440:                 foreach my $match (@matches) {
 2441:                     my ($key,$value) = split(/=/,$match);
 2442:                     $results{&unescape($key)} = &thaw_unescape($value);
 2443:                 }
 2444:             }
 2445:         }
 2446:     }
 2447:     my %userinfo;
 2448:     if (ref($results{$uname}) eq 'HASH') {
 2449:         %userinfo = %{$results{$uname}};
 2450:     } 
 2451:     return ($outcome,%userinfo);
 2452: }
 2453: 
 2454: sub get_multiple_instusers {
 2455:     my ($udom,$users,$caller) = @_;
 2456:     my ($outcome,$results);
 2457:     if (ref($users) eq 'HASH') {
 2458:         my $count = keys(%{$users}); 
 2459:         my $requested = &freeze_escape($users);
 2460:         my $homeserver = &domain($udom,'primary');
 2461:         if ($homeserver ne '') {
 2462:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2463:             my $host=&hostname($homeserver);
 2464:             if ($queryid !~/^\Q$host\E\_/) {
 2465:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2466:                          ' for host: '.$homeserver.'in domain '.$udom);
 2467:                 return ($outcome,$results);
 2468:             }
 2469:             my $response = &get_query_reply($queryid);
 2470:             my $maxtries = 5;
 2471:             if ($count > 100) {
 2472:                 $maxtries = 1+int($count/20);
 2473:             }
 2474:             my $tries = 1;
 2475:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2476:                 $response = &get_query_reply($queryid);
 2477:                 $tries ++;
 2478:             }
 2479:             if ($response eq '') {
 2480:                 $results = {};
 2481:                 foreach my $key (keys(%{$users})) {
 2482:                     my ($uname,$id);
 2483:                     if ($caller eq 'id') {
 2484:                         $id = $key;
 2485:                     } else {
 2486:                         $uname = $key;
 2487:                     }
 2488:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2489:                     $outcome = $resp;
 2490:                     if ($resp eq 'ok') {
 2491:                         %{$results} = (%{$results}, %info);
 2492:                     } else {
 2493:                         last;
 2494:                     }
 2495:                 }
 2496:             } elsif(!&error($response) && ($response ne 'refused')) {
 2497:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2498:                     $outcome = $response;
 2499:                 } else {
 2500:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2501:                     if ($outcome eq 'ok') {
 2502:                         $results = &thaw_unescape($userdata); 
 2503:                     }
 2504:                 }
 2505:             }
 2506:         }
 2507:     }
 2508:     return ($outcome,$results);
 2509: }
 2510: 
 2511: sub inst_rulecheck {
 2512:     my ($udom,$uname,$id,$item,$rules) = @_;
 2513:     my %returnhash;
 2514:     if ($udom ne '') {
 2515:         if (ref($rules) eq 'ARRAY') {
 2516:             @{$rules} = map {&escape($_);} (@{$rules});
 2517:             my $rulestr = join(':',@{$rules});
 2518:             my $homeserver=&domain($udom,'primary');
 2519:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2520:                 my $response;
 2521:                 if ($item eq 'username') {                
 2522:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2523:                                               ':'.&escape($uname).':'.$rulestr,
 2524:                                               $homeserver));
 2525:                 } elsif ($item eq 'id') {
 2526:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2527:                                               ':'.&escape($id).':'.$rulestr,
 2528:                                               $homeserver));
 2529:                 } elsif ($item eq 'selfcreate') {
 2530:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2531:                                                &escape($udom).':'.&escape($uname).
 2532:                                               ':'.$rulestr,$homeserver));
 2533:                 }
 2534:                 if ($response ne 'refused') {
 2535:                     my @pairs=split(/\&/,$response);
 2536:                     foreach my $item (@pairs) {
 2537:                         my ($key,$value)=split(/=/,$item,2);
 2538:                         $key = &unescape($key);
 2539:                         next if ($key =~ /^error: 2 /);
 2540:                         $returnhash{$key}=&thaw_unescape($value);
 2541:                     }
 2542:                 }
 2543:             }
 2544:         }
 2545:     }
 2546:     return %returnhash;
 2547: }
 2548: 
 2549: sub inst_userrules {
 2550:     my ($udom,$check) = @_;
 2551:     my (%ruleshash,@ruleorder);
 2552:     if ($udom ne '') {
 2553:         my $homeserver=&domain($udom,'primary');
 2554:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2555:             my $response;
 2556:             if ($check eq 'id') {
 2557:                 $response=&reply('instidrules:'.&escape($udom),
 2558:                                  $homeserver);
 2559:             } elsif ($check eq 'email') {
 2560:                 $response=&reply('instemailrules:'.&escape($udom),
 2561:                                  $homeserver);
 2562:             } else {
 2563:                 $response=&reply('instuserrules:'.&escape($udom),
 2564:                                  $homeserver);
 2565:             }
 2566:             if (($response ne 'refused') && ($response ne 'error') && 
 2567:                 ($response ne 'unknown_cmd') && 
 2568:                 ($response ne 'no_such_host')) {
 2569:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2570:                 my @pairs=split(/\&/,$hashitems);
 2571:                 foreach my $item (@pairs) {
 2572:                     my ($key,$value)=split(/=/,$item,2);
 2573:                     $key = &unescape($key);
 2574:                     next if ($key =~ /^error: 2 /);
 2575:                     $ruleshash{$key}=&thaw_unescape($value);
 2576:                 }
 2577:                 my @esc_order = split(/\&/,$orderitems);
 2578:                 foreach my $item (@esc_order) {
 2579:                     push(@ruleorder,&unescape($item));
 2580:                 }
 2581:             }
 2582:         }
 2583:     }
 2584:     return (\%ruleshash,\@ruleorder);
 2585: }
 2586: 
 2587: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2588: 
 2589: sub get_domain_defaults {
 2590:     my ($domain,$ignore_cache) = @_;
 2591:     return if (($domain eq '') || ($domain eq 'public'));
 2592:     my $cachetime = 60*60*24;
 2593:     unless ($ignore_cache) {
 2594:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2595:         if (defined($cached)) {
 2596:             if (ref($result) eq 'HASH') {
 2597:                 return %{$result};
 2598:             }
 2599:         }
 2600:     }
 2601:     my %domdefaults;
 2602:     my %domconfig =
 2603:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2604:                                   'requestcourses','inststatus',
 2605:                                   'coursedefaults','usersessions',
 2606:                                   'requestauthor','selfenrollment',
 2607:                                   'coursecategories','ssl','autoenroll',
 2608:                                   'trust','helpsettings','wafproxy'],$domain);
 2609:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2610:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2611:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2612:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2613:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2614:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2615:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2616:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2617:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2618:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2619:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2620:     } else {
 2621:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2622:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2623:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2624:     }
 2625:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2626:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2627:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2628:         } else {
 2629:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2630:         }
 2631:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2632:         foreach my $item (@usertools) {
 2633:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2634:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2635:             }
 2636:         }
 2637:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2638:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2639:         }
 2640:     }
 2641:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2642:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2643:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2644:         }
 2645:     }
 2646:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2647:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2648:     }
 2649:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2650:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2651:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2652:         }
 2653:     }
 2654:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2655:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2656:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2657:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2658:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2659:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2660:         }
 2661:         foreach my $type (@coursetypes) {
 2662:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2663:                 unless ($type eq 'community') {
 2664:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2665:                 }
 2666:             }
 2667:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2668:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2669:             }
 2670:             if ($domdefaults{'postsubmit'} eq 'on') {
 2671:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2672:                     $domdefaults{$type.'postsubtimeout'} = 
 2673:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2674:                 }
 2675:             }
 2676:         }
 2677:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2678:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2679:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2680:                 if (@clonecodes) {
 2681:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2682:                 }
 2683:             }
 2684:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2685:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2686:         }
 2687:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2688:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2689:         } 
 2690:     }
 2691:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2692:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2693:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2694:         }
 2695:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2696:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2697:         }
 2698:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2699:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2700:         }
 2701:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2702:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2703:         }
 2704:     }
 2705:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2706:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2707:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2708:                             'approval','limit');
 2709:             foreach my $type (@coursetypes) {
 2710:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2711:                     my @mgrdc = ();
 2712:                     foreach my $item (@settings) {
 2713:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2714:                             push(@mgrdc,$item);
 2715:                         }
 2716:                     }
 2717:                     if (@mgrdc) {
 2718:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2719:                     }
 2720:                 }
 2721:             }
 2722:         }
 2723:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2724:             foreach my $type (@coursetypes) {
 2725:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2726:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2727:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2728:                     }
 2729:                 }
 2730:             }
 2731:         }
 2732:     }
 2733:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2734:         $domdefaults{'catauth'} = 'std';
 2735:         $domdefaults{'catunauth'} = 'std';
 2736:         if ($domconfig{'coursecategories'}{'auth'}) {
 2737:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2738:         }
 2739:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2740:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2741:         }
 2742:     }
 2743:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2744:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2745:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2746:         }
 2747:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2748:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2749:         }
 2750:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2751:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2752:         }
 2753:     }
 2754:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2755:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2756:         foreach my $prefix (@prefixes) {
 2757:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2758:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2759:             }
 2760:         }
 2761:     }
 2762:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2763:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2764:     }
 2765:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2766:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2767:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2768:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2769:         }
 2770:     }
 2771:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2772:         foreach my $item ('ipheader','trusted','vpnint','vpnext') {
 2773:             if ($domconfig{'wafproxy'}{$item}) {
 2774:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2775:             }
 2776:         }
 2777:     } 
 2778:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2779:     return %domdefaults;
 2780: }
 2781: 
 2782: sub get_dom_cats {
 2783:     my ($dom) = @_;
 2784:     return unless (&domain($dom));
 2785:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2786:     unless (defined($cached)) {
 2787:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2788:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2789:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2790:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2791:             } else {
 2792:                 $cats = {};
 2793:             }
 2794:         } else {
 2795:             $cats = {};
 2796:         }
 2797:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2798:     }
 2799:     return $cats;
 2800: }
 2801: 
 2802: sub get_dom_instcats {
 2803:     my ($dom) = @_;
 2804:     return unless (&domain($dom));
 2805:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2806:     unless (defined($cached)) {
 2807:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2808:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2809:         if ($totcodes > 0) {
 2810:             my $caller = 'global';
 2811:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2812:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2813:                 $instcats = {
 2814:                                 codes => \%codes,
 2815:                                 codetitles => \@codetitles,
 2816:                                 cat_titles => \%cat_titles,
 2817:                                 cat_order => \%cat_order,
 2818:                             };
 2819:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2820:             }
 2821:         }
 2822:     }
 2823:     return $instcats;
 2824: }
 2825: 
 2826: sub retrieve_instcodes {
 2827:     my ($coursecodes,$dom) = @_;
 2828:     my $totcodes;
 2829:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2830:     foreach my $course (keys(%courses)) {
 2831:         if (ref($courses{$course}) eq 'HASH') {
 2832:             if ($courses{$course}{'inst_code'} ne '') {
 2833:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2834:                 $totcodes ++;
 2835:             }
 2836:         }
 2837:     }
 2838:     return $totcodes;
 2839: }
 2840: 
 2841: sub course_portal_url {
 2842:     my ($cnum,$cdom) = @_;
 2843:     my $chome = &homeserver($cnum,$cdom);
 2844:     my $hostname = &hostname($chome);
 2845:     my $protocol = $protocol{$chome};
 2846:     $protocol = 'http' if ($protocol ne 'https');
 2847:     my %domdefaults = &get_domain_defaults($cdom);
 2848:     my $firsturl;
 2849:     if ($domdefaults{'portal_def'}) {
 2850:         $firsturl = $domdefaults{'portal_def'};
 2851:     } else {
 2852:         $firsturl = $protocol.'://'.$hostname;
 2853:     }
 2854:     return $firsturl;
 2855: }
 2856: 
 2857: # --------------------------------------------- Get domain config for passwords
 2858: 
 2859: sub get_passwdconf {
 2860:     my ($dom) = @_;
 2861:     my (%passwdconf,$gotconf,$lookup);
 2862:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2863:     if (defined($cached)) {
 2864:         if (ref($result) eq 'HASH') {
 2865:             %passwdconf = %{$result};
 2866:             $gotconf = 1;
 2867:         }
 2868:     }
 2869:     unless ($gotconf) {
 2870:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2871:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2872:             %passwdconf = %{$domconfig{'passwords'}};
 2873:         }
 2874:         my $cachetime = 24*60*60;
 2875:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2876:     }
 2877:     return %passwdconf;
 2878: }
 2879: 
 2880: # --------------------------------------------------- Assign a key to a student
 2881: 
 2882: sub assign_access_key {
 2883: #
 2884: # a valid key looks like uname:udom#comments
 2885: # comments are being appended
 2886: #
 2887:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2888:     $kdom=
 2889:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2890:     $knum=
 2891:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2892:     $cdom=
 2893:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2894:     $cnum=
 2895:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2896:     $udom=$env{'user.name'} unless (defined($udom));
 2897:     $uname=$env{'user.domain'} unless (defined($uname));
 2898:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2899:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2900:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2901:                                                   # assigned to this person
 2902:                                                   # - this should not happen,
 2903:                                                   # unless something went wrong
 2904:                                                   # the first time around
 2905: # ready to assign
 2906:         $logentry=$1.'; '.$logentry;
 2907:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2908:                                                  $kdom,$knum) eq 'ok') {
 2909: # key now belongs to user
 2910: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2911:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2912:                 &appenv({'environment.'.$envkey => $ckey});
 2913:                 return 'ok';
 2914:             } else {
 2915:                 return 
 2916:   'error: Count not permanently assign key, will need to be re-entered later.';
 2917: 	    }
 2918:         } else {
 2919:             return 'error: Could not assign key, try again later.';
 2920:         }
 2921:     } elsif (!$existing{$ckey}) {
 2922: # the key does not exist
 2923: 	return 'error: The key does not exist';
 2924:     } else {
 2925: # the key is somebody else's
 2926: 	return 'error: The key is already in use';
 2927:     }
 2928: }
 2929: 
 2930: # ------------------------------------------ put an additional comment on a key
 2931: 
 2932: sub comment_access_key {
 2933: #
 2934: # a valid key looks like uname:udom#comments
 2935: # comments are being appended
 2936: #
 2937:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2938:     $cdom=
 2939:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2940:     $cnum=
 2941:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2942:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2943:     if ($existing{$ckey}) {
 2944:         $existing{$ckey}.='; '.$logentry;
 2945: # ready to assign
 2946:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2947:                                                  $cdom,$cnum) eq 'ok') {
 2948: 	    return 'ok';
 2949:         } else {
 2950: 	    return 'error: Count not store comment.';
 2951:         }
 2952:     } else {
 2953: # the key does not exist
 2954: 	return 'error: The key does not exist';
 2955:     }
 2956: }
 2957: 
 2958: # ------------------------------------------------------ Generate a set of keys
 2959: 
 2960: sub generate_access_keys {
 2961:     my ($number,$cdom,$cnum,$logentry)=@_;
 2962:     $cdom=
 2963:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2964:     $cnum=
 2965:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2966:     unless (&allowed('mky',$cdom)) { return 0; }
 2967:     unless (($cdom) && ($cnum)) { return 0; }
 2968:     if ($number>10000) { return 0; }
 2969:     sleep(2); # make sure don't get same seed twice
 2970:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2971:     my $total=0;
 2972:     for (my $i=1;$i<=$number;$i++) {
 2973:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2974:                   sprintf("%lx",int(100000*rand)).'-'.
 2975:                   sprintf("%lx",int(100000*rand));
 2976:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2977:        $newkey=~s/0/h/g; # and also 0 and O
 2978:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2979:        if ($existing{$newkey}) {
 2980:            $i--;
 2981:        } else {
 2982: 	  if (&put('accesskeys',
 2983:               { $newkey => '# generated '.localtime().
 2984:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2985:                            '; '.$logentry },
 2986: 		   $cdom,$cnum) eq 'ok') {
 2987:               $total++;
 2988: 	  }
 2989:        }
 2990:     }
 2991:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2992:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2993:     return $total;
 2994: }
 2995: 
 2996: # ------------------------------------------------------- Validate an accesskey
 2997: 
 2998: sub validate_access_key {
 2999:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3000:     $cdom=
 3001:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3002:     $cnum=
 3003:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3004:     $udom=$env{'user.domain'} unless (defined($udom));
 3005:     $uname=$env{'user.name'} unless (defined($uname));
 3006:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3007:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3008: }
 3009: 
 3010: # ------------------------------------- Find the section of student in a course
 3011: sub devalidate_getsection_cache {
 3012:     my ($udom,$unam,$courseid)=@_;
 3013:     my $hashid="$udom:$unam:$courseid";
 3014:     &devalidate_cache_new('getsection',$hashid);
 3015: }
 3016: 
 3017: sub courseid_to_courseurl {
 3018:     my ($courseid) = @_;
 3019:     #already url style courseid
 3020:     return $courseid if ($courseid =~ m{^/});
 3021: 
 3022:     if (exists($env{'course.'.$courseid.'.num'})) {
 3023: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3024: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3025: 	return "/$cdom/$cnum";
 3026:     }
 3027: 
 3028:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 3029:     if (exists($courseinfo{'num'})) {
 3030: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3031:     }
 3032: 
 3033:     return undef;
 3034: }
 3035: 
 3036: sub getsection {
 3037:     my ($udom,$unam,$courseid)=@_;
 3038:     my $cachetime=1800;
 3039: 
 3040:     my $hashid="$udom:$unam:$courseid";
 3041:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3042:     if (defined($cached)) { return $result; }
 3043: 
 3044:     my %Pending; 
 3045:     my %Expired;
 3046:     #
 3047:     # Each role can either have not started yet (pending), be active, 
 3048:     #    or have expired.
 3049:     #
 3050:     # If there is an active role, we are done.
 3051:     #
 3052:     # If there is more than one role which has not started yet, 
 3053:     #     choose the one which will start sooner
 3054:     # If there is one role which has not started yet, return it.
 3055:     #
 3056:     # If there is more than one expired role, choose the one which ended last.
 3057:     # If there is a role which has expired, return it.
 3058:     #
 3059:     $courseid = &courseid_to_courseurl($courseid);
 3060:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3061:     foreach my $key (keys(%roleshash)) {
 3062:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3063:         my $section=$1;
 3064:         if ($key eq $courseid.'_st') { $section=''; }
 3065:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3066:         my $now=time;
 3067:         if (defined($end) && $end && ($now > $end)) {
 3068:             $Expired{$end}=$section;
 3069:             next;
 3070:         }
 3071:         if (defined($start) && $start && ($now < $start)) {
 3072:             $Pending{$start}=$section;
 3073:             next;
 3074:         }
 3075:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3076:     }
 3077:     #
 3078:     # Presumedly there will be few matching roles from the above
 3079:     # loop and the sorting time will be negligible.
 3080:     if (scalar(keys(%Pending))) {
 3081:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3082:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3083:     } 
 3084:     if (scalar(keys(%Expired))) {
 3085:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3086:         my $time = pop(@sorted);
 3087:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3088:     }
 3089:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3090: }
 3091: 
 3092: sub save_cache {
 3093:     &purge_remembered();
 3094:     #&Apache::loncommon::validate_page();
 3095:     undef(%env);
 3096:     undef($env_loaded);
 3097: }
 3098: 
 3099: my $to_remember=-1;
 3100: my %remembered;
 3101: my %accessed;
 3102: my $kicks=0;
 3103: my $hits=0;
 3104: sub make_key {
 3105:     my ($name,$id) = @_;
 3106:     if (length($id) > 65 
 3107: 	&& length(&escape($id)) > 200) {
 3108: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3109:     }
 3110:     return &escape($name.':'.$id);
 3111: }
 3112: 
 3113: sub devalidate_cache_new {
 3114:     my ($name,$id,$debug) = @_;
 3115:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3116:     my $remembered_id=$name.':'.$id;
 3117:     $id=&make_key($name,$id);
 3118:     $memcache->delete($id);
 3119:     delete($remembered{$remembered_id});
 3120:     delete($accessed{$remembered_id});
 3121: }
 3122: 
 3123: sub is_cached_new {
 3124:     my ($name,$id,$debug) = @_;
 3125:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3126:     if (exists($remembered{$remembered_id})) {
 3127: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3128: 	$accessed{$remembered_id}=[&gettimeofday()];
 3129: 	$hits++;
 3130: 	return ($remembered{$remembered_id},1);
 3131:     }
 3132:     $id=&make_key($name,$id);
 3133:     my $value = $memcache->get($id);
 3134:     if (!(defined($value))) {
 3135: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3136: 	return (undef,undef);
 3137:     }
 3138:     if ($value eq '__undef__') {
 3139: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3140: 	$value=undef;
 3141:     }
 3142:     &make_room($remembered_id,$value,$debug);
 3143:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3144:     return ($value,1);
 3145: }
 3146: 
 3147: sub do_cache_new {
 3148:     my ($name,$id,$value,$time,$debug) = @_;
 3149:     my $remembered_id=$name.':'.$id;
 3150:     $id=&make_key($name,$id);
 3151:     my $setvalue=$value;
 3152:     if (!defined($setvalue)) {
 3153: 	$setvalue='__undef__';
 3154:     }
 3155:     if (!defined($time) ) {
 3156: 	$time=600;
 3157:     }
 3158:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3159:     my $result = $memcache->set($id,$setvalue,$time);
 3160:     if (! $result) {
 3161: 	&logthis("caching of id -> $id  failed");
 3162: 	$memcache->disconnect_all();
 3163:     }
 3164:     # need to make a copy of $value
 3165:     &make_room($remembered_id,$value,$debug);
 3166:     return $value;
 3167: }
 3168: 
 3169: sub make_room {
 3170:     my ($remembered_id,$value,$debug)=@_;
 3171: 
 3172:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3173:                                     : $value;
 3174:     if ($to_remember<0) { return; }
 3175:     $accessed{$remembered_id}=[&gettimeofday()];
 3176:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3177:     my $to_kick;
 3178:     my $max_time=0;
 3179:     foreach my $other (keys(%accessed)) {
 3180: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3181: 	    $to_kick=$other;
 3182: 	    $max_time=&tv_interval($accessed{$other});
 3183: 	}
 3184:     }
 3185:     delete($remembered{$to_kick});
 3186:     delete($accessed{$to_kick});
 3187:     $kicks++;
 3188:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3189:     return;
 3190: }
 3191: 
 3192: sub purge_remembered {
 3193:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3194:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3195:     undef(%remembered);
 3196:     undef(%accessed);
 3197: }
 3198: # ------------------------------------- Read an entry from a user's environment
 3199: 
 3200: sub userenvironment {
 3201:     my ($udom,$unam,@what)=@_;
 3202:     my $items;
 3203:     foreach my $item (@what) {
 3204:         $items.=&escape($item).'&';
 3205:     }
 3206:     $items=~s/\&$//;
 3207:     my %returnhash=();
 3208:     my $uhome = &homeserver($unam,$udom);
 3209:     unless ($uhome eq 'no_host') {
 3210:         my @answer=split(/\&/, 
 3211:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3212:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3213:             return %returnhash;
 3214:         }
 3215:         my $i;
 3216:         for ($i=0;$i<=$#what;$i++) {
 3217: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3218:         }
 3219:     }
 3220:     return %returnhash;
 3221: }
 3222: 
 3223: # ---------------------------------------------------------- Get a studentphoto
 3224: sub studentphoto {
 3225:     my ($udom,$unam,$ext) = @_;
 3226:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3227:     if (defined($env{'request.course.id'})) {
 3228:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3229:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3230:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3231:             } else {
 3232:                 my ($result,$perm_reqd)=
 3233: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3234:                 if ($result eq 'ok') {
 3235:                     if (!($perm_reqd eq 'yes')) {
 3236:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3237:                     }
 3238:                 }
 3239:             }
 3240:         }
 3241:     } else {
 3242:         my ($result,$perm_reqd) = 
 3243: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3244:         if ($result eq 'ok') {
 3245:             if (!($perm_reqd eq 'yes')) {
 3246:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3247:             }
 3248:         }
 3249:     }
 3250:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3251: }
 3252: 
 3253: sub retrievestudentphoto {
 3254:     my ($udom,$unam,$ext,$type) = @_;
 3255:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3256:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3257:     if ($ret eq 'ok') {
 3258:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3259:         if ($type eq 'thumbnail') {
 3260:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3261:         }
 3262:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3263:         return $tokenurl;
 3264:     } else {
 3265:         if ($type eq 'thumbnail') {
 3266:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3267:         } else { 
 3268:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3269:         }
 3270:     }
 3271: }
 3272: 
 3273: # -------------------------------------------------------------------- New chat
 3274: 
 3275: sub chatsend {
 3276:     my ($newentry,$anon,$group)=@_;
 3277:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3278:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3279:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3280:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3281: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3282: 		   &escape($newentry)).':'.$group,$chome);
 3283: }
 3284: 
 3285: # ------------------------------------------ Find current version of a resource
 3286: 
 3287: sub getversion {
 3288:     my $fname=&clutter(shift);
 3289:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3290:     return &currentversion(&filelocation('',$fname));
 3291: }
 3292: 
 3293: sub currentversion {
 3294:     my $fname=shift;
 3295:     my $author=$fname;
 3296:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3297:     my ($udom,$uname)=split(/\//,$author);
 3298:     my $home=&homeserver($uname,$udom);
 3299:     if ($home eq 'no_host') { 
 3300:         return -1; 
 3301:     }
 3302:     my $answer=&reply("currentversion:$fname",$home);
 3303:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3304: 	return -1;
 3305:     }
 3306:     return $answer;
 3307: }
 3308: 
 3309: #
 3310: # Return special version number of resource if set by override, empty otherwise
 3311: #
 3312: sub usedversion {
 3313:     my $fname=shift;
 3314:     unless ($fname) { $fname=$env{'request.uri'}; }
 3315:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3316:     if ($urlversion) { return $urlversion; }
 3317:     return '';
 3318: }
 3319: 
 3320: # ----------------------------- Subscribe to a resource, return URL if possible
 3321: 
 3322: sub subscribe {
 3323:     my $fname=shift;
 3324:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3325:     $fname=~s/[\n\r]//g;
 3326:     my $author=$fname;
 3327:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3328:     my ($udom,$uname)=split(/\//,$author);
 3329:     my $home=homeserver($uname,$udom);
 3330:     if ($home eq 'no_host') {
 3331:         return 'not_found';
 3332:     }
 3333:     my $answer=reply("sub:$fname",$home);
 3334:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3335: 	$answer.=' by '.$home;
 3336:     }
 3337:     return $answer;
 3338: }
 3339:     
 3340: # -------------------------------------------------------------- Replicate file
 3341: 
 3342: sub repcopy {
 3343:     my $filename=shift;
 3344:     $filename=~s/\/+/\//g;
 3345:     my $londocroot = $perlvar{'lonDocRoot'};
 3346:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3347:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3348:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3349: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3350: 	return &repcopy_userfile($filename);
 3351:     }
 3352:     $filename=~s/[\n\r]//g;
 3353:     my $transname="$filename.in.transfer";
 3354: # FIXME: this should flock
 3355:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3356:     my $remoteurl=subscribe($filename);
 3357:     if ($remoteurl =~ /^con_lost by/) {
 3358: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3359:            return 'unavailable';
 3360:     } elsif ($remoteurl eq 'not_found') {
 3361: 	   #&logthis("Subscribe returned not_found: $filename");
 3362: 	   return 'not_found';
 3363:     } elsif ($remoteurl =~ /^rejected by/) {
 3364: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3365:            return 'forbidden';
 3366:     } elsif ($remoteurl eq 'directory') {
 3367:            return 'ok';
 3368:     } else {
 3369:         my $author=$filename;
 3370:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3371:         my ($udom,$uname)=split(/\//,$author);
 3372:         my $home=homeserver($uname,$udom);
 3373:         unless ($home eq $perlvar{'lonHostID'}) {
 3374:            my @parts=split(/\//,$filename);
 3375:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3376:            if ($path ne "$londocroot/res") {
 3377:                &logthis("Malconfiguration for replication: $filename");
 3378: 	       return 'bad_request';
 3379:            }
 3380:            my $count;
 3381:            for ($count=5;$count<$#parts;$count++) {
 3382:                $path.="/$parts[$count]";
 3383:                if ((-e $path)!=1) {
 3384: 		   mkdir($path,0777);
 3385:                }
 3386:            }
 3387:            my $request=new HTTP::Request('GET',"$remoteurl");
 3388:            my $response;
 3389:            if ($remoteurl =~ m{/raw/}) {
 3390:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3391:            } else {
 3392:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3393:            }
 3394:            if ($response->is_error()) {
 3395: 	       unlink($transname);
 3396:                my $message=$response->status_line;
 3397:                &logthis("<font color=\"blue\">WARNING:"
 3398:                        ." LWP get: $message: $filename</font>");
 3399:                return 'unavailable';
 3400:            } else {
 3401: 	       if ($remoteurl!~/\.meta$/) {
 3402:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3403:                   my $mresponse;
 3404:                   if ($remoteurl =~ m{/raw/}) {
 3405:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3406:                   } else {
 3407:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3408:                   }
 3409:                   if ($mresponse->is_error()) {
 3410: 		      unlink($filename.'.meta');
 3411:                       &logthis(
 3412:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3413:                   }
 3414: 	       }
 3415:                rename($transname,$filename);
 3416:                return 'ok';
 3417:            }
 3418:        }
 3419:     }
 3420: }
 3421: 
 3422: # ------------------------------------------------- Unsubscribe from a resource
 3423: 
 3424: sub unsubscribe {
 3425:     my ($fname) = @_;
 3426:     my $answer;
 3427:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3428:     $fname=~s/[\n\r]//g;
 3429:     my $author=$fname;
 3430:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3431:     my ($udom,$uname)=split(/\//,$author);
 3432:     my $home=homeserver($uname,$udom);
 3433:     if ($home eq 'no_host') {
 3434:         $answer = 'no_host';
 3435:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3436:         $answer = 'home';
 3437:     } else {
 3438:         my $defdom = $perlvar{'lonDefDomain'};
 3439:         if (&will_trust('content',$defdom,$udom)) {
 3440:             $answer = reply("unsub:$fname",$home);
 3441:         } else {
 3442:             $answer = 'untrusted';
 3443:         }
 3444:     }
 3445:     return $answer;
 3446: }
 3447: 
 3448: # ------------------------------------------------ Get server side include body
 3449: sub ssi_body {
 3450:     my ($filelink,%form)=@_;
 3451:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3452:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3453:     }
 3454:     my $output='';
 3455:     my $response;
 3456:     if ($filelink=~/^https?\:/) {
 3457:        ($output,$response)=&externalssi($filelink);
 3458:     } else {
 3459:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3460:        $filelink .= 'inhibitmenu=yes';
 3461:        ($output,$response)=&ssi($filelink,%form);
 3462:     }
 3463:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3464:     $output=~s/^.*?\<body[^\>]*\>//si;
 3465:     $output=~s/\<\/body\s*\>.*?$//si;
 3466:     if (wantarray) {
 3467:         return ($output, $response);
 3468:     } else {
 3469:         return $output;
 3470:     }
 3471: }
 3472: 
 3473: # --------------------------------------------------------- Server Side Include
 3474: 
 3475: sub absolute_url {
 3476:     my ($host_name) = @_;
 3477:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3478:     if ($host_name eq '') {
 3479: 	$host_name = $ENV{'SERVER_NAME'};
 3480:     }
 3481:     return $protocol.$host_name;
 3482: }
 3483: 
 3484: #
 3485: #   Server side include.
 3486: # Parameters:
 3487: #  fn     Possibly encrypted resource name/id.
 3488: #  form   Hash that describes how the rendering should be done
 3489: #         and other things.
 3490: # Returns:
 3491: #   Scalar context: The content of the response.
 3492: #   Array context:  2 element list of the content and the full response object.
 3493: #     
 3494: sub ssi {
 3495: 
 3496:     my ($fn,%form)=@_;
 3497:     my $request;
 3498: 
 3499:     $form{'no_update_last_known'}=1;
 3500:     &Apache::lonenc::check_encrypt(\$fn);
 3501:     if (%form) {
 3502:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3503:       $request->content(join('&',map { 
 3504:             my $name = escape($_);
 3505:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3506:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3507:             : &escape($form{$_}) );    
 3508:         } keys(%form)));
 3509:     } else {
 3510:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3511:     }
 3512: 
 3513:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3514:     my $lonhost = $perlvar{'lonHostID'};
 3515:     my $islocal;
 3516:     if (($env{'request.course.id'}) &&
 3517:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3518:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3519:         ($form{'grade_symb'} ne '') &&
 3520:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3521:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3522:         $islocal = 1;
 3523:     }
 3524:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3525:                                                 '','','',$islocal);
 3526: 
 3527:     if (wantarray) {
 3528: 	return ($response->content, $response);
 3529:     } else {
 3530: 	return $response->content;
 3531:     }
 3532: }
 3533: 
 3534: sub externalssi {
 3535:     my ($url)=@_;
 3536:     my $request=new HTTP::Request('GET',$url);
 3537:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3538:     if (wantarray) {
 3539:         return ($response->content, $response);
 3540:     } else {
 3541:         return $response->content;
 3542:     }
 3543: }
 3544: 
 3545: 
 3546: # If the local copy of a replicated resource is outdated, trigger a  
 3547: # connection from the homeserver to flush the delayed queue. If no update 
 3548: # happens, remove local copies of outdated resource (and corresponding
 3549: # metadata file).
 3550: 
 3551: sub remove_stale_resfile {
 3552:     my ($url) = @_;
 3553:     my $removed;
 3554:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3555:         my $audom = $1;
 3556:         my $auname = $2;
 3557:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3558:             my $homeserver = &homeserver($auname,$audom);
 3559:             unless (($homeserver eq 'no_host') ||
 3560:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3561:                 my $fname = &filelocation('',$url);
 3562:                 if (-e $fname) {
 3563:                     my $hostname = &hostname($homeserver);
 3564:                     if ($hostname) {
 3565:                         my $protocol = $protocol{$homeserver};
 3566:                         $protocol = 'http' if ($protocol ne 'https');
 3567:                         my $uri = &declutter($url);
 3568:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3569:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3570:                         if ($response->is_success()) {
 3571:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3572:                             my $locmodtime = (stat($fname))[9];
 3573:                             if ($locmodtime < $remmodtime) {
 3574:                                 my $stale;
 3575:                                 my $answer = &reply('pong',$homeserver);
 3576:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3577:                                     sleep(0.2);
 3578:                                     $locmodtime = (stat($fname))[9];
 3579:                                     if ($locmodtime < $remmodtime) {
 3580:                                         my $posstransfer = $fname.'.in.transfer';
 3581:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3582:                                             $removed = 1;
 3583:                                         } else {
 3584:                                             $stale = 1;
 3585:                                         }
 3586:                                     } else {
 3587:                                         $removed = 1;
 3588:                                     }
 3589:                                 } else {
 3590:                                     $stale = 1;
 3591:                                 }
 3592:                                 if ($stale) {
 3593:                                     if (unlink($fname)) {
 3594:                                         if ($uri!~/\.meta$/) {
 3595:                                             if (-e $fname.'.meta') {
 3596:                                                 unlink($fname.'.meta');
 3597:                                             }
 3598:                                         }
 3599:                                         my $unsubresult = &unsubscribe($fname);
 3600:                                         unless ($unsubresult eq 'ok') {
 3601:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3602:                                         }
 3603:                                         $removed = 1;
 3604:                                     }
 3605:                                 }
 3606:                             }
 3607:                         }
 3608:                     }
 3609:                 }
 3610:             }
 3611:         }
 3612:     }
 3613:     return $removed;
 3614: }
 3615: 
 3616: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3617: 
 3618: sub allowuploaded {
 3619:     my ($srcurl,$url)=@_;
 3620:     $url=&clutter(&declutter($url));
 3621:     my $dir=$url;
 3622:     $dir=~s/\/[^\/]+$//;
 3623:     my %httpref=();
 3624:     my $httpurl=&hreflocation('',$url);
 3625:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3626:     &Apache::lonnet::appenv(\%httpref);
 3627: }
 3628: 
 3629: #
 3630: # Determine if the current user should be able to edit a particular resource,
 3631: # when viewing in course context.
 3632: # (a) When viewing resource used to determine if "Edit" item is included in 
 3633: #     Functions.
 3634: # (b) When displaying folder contents in course editor, used to determine if
 3635: #     "Edit" link will be displayed alongside resource.
 3636: #
 3637: #  input: six args -- filename (decluttered), course number, course domain,
 3638: #                   url, symb (if registered) and group (if this is a group
 3639: #                   item -- e.g., bulletin board, group page etc.).
 3640: #  output: array of five scalars -- 
 3641: #          $cfile -- url for file editing if editable on current server
 3642: #          $home -- homeserver of resource (i.e., for author if published,
 3643: #                                           or course if uploaded.).
 3644: #          $switchserver --  1 if server switch will be needed.
 3645: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3646: #          $forceview -- 1 if icon/link should be to go to view mode
 3647: #
 3648: 
 3649: sub can_edit_resource {
 3650:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3651:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3652: #
 3653: # For aboutme pages user can only edit his/her own.
 3654: #
 3655:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3656:         my ($sdom,$sname) = ($1,$2);
 3657:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3658:             $home = $env{'user.home'};
 3659:             $cfile = $resurl;
 3660:             if ($env{'form.forceedit'}) {
 3661:                 $forceview = 1;
 3662:             } else {
 3663:                 $forceedit = 1;
 3664:             }
 3665:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3666:         } else {
 3667:             return;
 3668:         }
 3669:     }
 3670: 
 3671:     if ($env{'request.course.id'}) {
 3672:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3673:         if ($group ne '') {
 3674: # if this is a group homepage or group bulletin board, check group privs
 3675:             my $allowed = 0;
 3676:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3677:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3678:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3679:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3680:                     $allowed = 1;
 3681:                 }
 3682:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3683:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3684:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3685:                     $allowed = 1;
 3686:                 }
 3687:             }
 3688:             if ($allowed) {
 3689:                 $home=&homeserver($cnum,$cdom);
 3690:                 if ($env{'form.forceedit'}) {
 3691:                     $forceview = 1;
 3692:                 } else {
 3693:                     $forceedit = 1;
 3694:                 }
 3695:                 $cfile = $resurl;
 3696:             } else {
 3697:                 return;
 3698:             }
 3699:         } else {
 3700:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3701:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3702:                     return;
 3703:                 }
 3704:             } elsif (!$crsedit) {
 3705: #
 3706: # No edit allowed where CC has switched to student role.
 3707: #
 3708:                 return;
 3709:             }
 3710:         }
 3711:     }
 3712: 
 3713:     if ($file ne '') {
 3714:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3715:             if (&is_course_upload($file,$cnum,$cdom)) {
 3716:                 $uploaded = 1;
 3717:                 $incourse = 1;
 3718:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3719:                     $cfile = &hreflocation('',$file);
 3720:                     if ($env{'form.forceedit'}) {
 3721:                         $forceview = 1;
 3722:                     } else {
 3723:                         $forceedit = 1;
 3724:                     }
 3725:                 }
 3726:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3727:                 $incourse = 1;
 3728:                 if ($env{'form.forceedit'}) {
 3729:                     $forceview = 1;
 3730:                 } else {
 3731:                     $forceedit = 1;
 3732:                 }
 3733:                 $cfile = $resurl;
 3734:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3735:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3736:                     $incourse = 1;
 3737:                     if ($env{'form.forceedit'}) {
 3738:                         $forceview = 1;
 3739:                     } else {
 3740:                         $forceedit = 1;
 3741:                     }
 3742:                     $cfile = $resurl;
 3743:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3744:                     $incourse = 1;
 3745:                     $cfile = $resurl.'/smpedit';
 3746:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3747:                     $incourse = 1;
 3748:                     if ($env{'form.forceedit'}) {
 3749:                         $forceview = 1;
 3750:                     } else {
 3751:                         $forceedit = 1;
 3752:                     }
 3753:                     $cfile = $resurl;
 3754:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3755:                     my ($map,$id,$res) = &decode_symb($symb);
 3756:                     if ($map =~ /\.page$/) {
 3757:                         $incourse = 1;
 3758:                         if ($env{'form.forceedit'}) {
 3759:                             $forceview = 1;
 3760:                             $cfile = $map;
 3761:                         } else {
 3762:                             $forceedit = 1;
 3763:                             $cfile =  '/adm/wrapper'.$resurl;
 3764:                         }
 3765:                     }
 3766:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3767:                     $incourse = 1;
 3768:                     if ($env{'form.forceedit'}) {
 3769:                         $forceview = 1;
 3770:                     } else {
 3771:                         $forceedit = 1;
 3772:                     }
 3773:                     $cfile = $resurl;
 3774:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3775:                     $incourse = 1;
 3776:                     if ($env{'form.forceedit'}) {
 3777:                         $forceview = 1;
 3778:                     } else {
 3779:                         $forceedit = 1;
 3780:                     }
 3781:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3782:                 }
 3783:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3784:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3785:                 if (&is_on_map($template)) { 
 3786:                     $incourse = 1;
 3787:                     $forceview = 1;
 3788:                     $cfile = $template;
 3789:                 }
 3790:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3791:                 $incourse = 1;
 3792:                 if ($env{'form.forceedit'}) {
 3793:                     $forceview = 1;
 3794:                 } else {
 3795:                     $forceedit = 1;
 3796:                 }
 3797:                 $cfile = $resurl;
 3798:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3799:                 $incourse = 1;
 3800:                 if ($env{'form.forceedit'}) {
 3801:                     $forceview = 1;
 3802:                 } else {
 3803:                     $forceedit = 1;
 3804:                 }
 3805:                 $cfile = $resurl;
 3806:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3807:                 $incourse = 1;
 3808:                 $forceview = 1;
 3809:                 if ($symb) {
 3810:                     my ($map,$id,$res)=&decode_symb($symb);
 3811:                     $env{'request.symb'} = $symb;
 3812:                     $cfile = &clutter($res);
 3813:                 } else {
 3814:                     $cfile = $env{'form.suppurl'};
 3815:                     my $escfile = &unescape($cfile);
 3816:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3817:                         $cfile = '/adm/wrapper'.$escfile;
 3818:                     } else {
 3819:                         $escfile =~ s{^http://}{};
 3820:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3821:                     }
 3822:                 }
 3823:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3824:                 if ($env{'form.forceedit'}) {
 3825:                     $forceview = 1;
 3826:                 } else {
 3827:                     $forceedit = 1;
 3828:                 }
 3829:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3830:             }
 3831:         }
 3832:         if ($uploaded || $incourse) {
 3833:             $home=&homeserver($cnum,$cdom);
 3834:         } elsif ($file !~ m{/$}) {
 3835:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3836:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3837:             # Check that the user has permission to edit this resource
 3838:             my $setpriv = 1;
 3839:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3840:             if (defined($cfudom)) {
 3841:                 $home=&homeserver($cfuname,$cfudom);
 3842:                 $cfile=$file;
 3843:             }
 3844:         }
 3845:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3846:             (($home ne '') && ($home ne 'no_host'))) {
 3847:             my @ids=&current_machine_ids();
 3848:             unless (grep(/^\Q$home\E$/,@ids)) {
 3849:                 $switchserver=1;
 3850:             }
 3851:         }
 3852:     }
 3853:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3854: }
 3855: 
 3856: sub is_course_upload {
 3857:     my ($file,$cnum,$cdom) = @_;
 3858:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3859:     $uploadpath =~ s{^\/}{};
 3860:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3861:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3862:         return 1;
 3863:     }
 3864:     return;
 3865: }
 3866: 
 3867: sub in_course {
 3868:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3869:     if ($hideprivileged) {
 3870:         my $skipuser;
 3871:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3872:         my @possdoms = ($cdom);  
 3873:         if ($coursehash{'checkforpriv'}) { 
 3874:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3875:         }
 3876:         if (&privileged($uname,$udom,\@possdoms)) {
 3877:             $skipuser = 1;
 3878:             if ($coursehash{'nothideprivileged'}) {
 3879:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3880:                     my $user;
 3881:                     if ($item =~ /:/) {
 3882:                         $user = $item;
 3883:                     } else {
 3884:                         $user = join(':',split(/[\@]/,$item));
 3885:                     }
 3886:                     if ($user eq $uname.':'.$udom) {
 3887:                         undef($skipuser);
 3888:                         last;
 3889:                     }
 3890:                 }
 3891:             }
 3892:             if ($skipuser) {
 3893:                 return 0;
 3894:             }
 3895:         }
 3896:     }
 3897:     $type ||= 'any';
 3898:     if (!defined($cdom) || !defined($cnum)) {
 3899:         my $cid  = $env{'request.course.id'};
 3900:         $cdom = $env{'course.'.$cid.'.domain'};
 3901:         $cnum = $env{'course.'.$cid.'.num'};
 3902:     }
 3903:     my $typesref;
 3904:     if (($type eq 'any') || ($type eq 'all')) {
 3905:         $typesref = ['active','previous','future'];
 3906:     } elsif ($type eq 'previous' || $type eq 'future') {
 3907:         $typesref = [$type];
 3908:     }
 3909:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3910:                               $typesref,undef,[$cdom]);
 3911:     my ($tmp) = keys(%roles);
 3912:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3913:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3914:     if (@course_roles > 0) {
 3915:         return 1;
 3916:     }
 3917:     return 0;
 3918: }
 3919: 
 3920: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3921: # input: action, courseID, current domain, intended
 3922: #        path to file, source of file, instruction to parse file for objects,
 3923: #        ref to hash for embedded objects,
 3924: #        ref to hash for codebase of java objects.
 3925: #        reference to scalar to accommodate mime type determined
 3926: #          from File::MMagic if $parser = parse.
 3927: #
 3928: # output: url to file (if action was uploaddoc), 
 3929: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3930: #
 3931: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3932: # course.
 3933: #
 3934: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3935: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3936: #          course's home server.
 3937: #
 3938: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3939: #          be copied from $source (current location) to 
 3940: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3941: #         and will then be copied to
 3942: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3943: #         course's home server.
 3944: #
 3945: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3946: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3947: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3948: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3949: #         in course's home server.
 3950: #
 3951: 
 3952: sub process_coursefile {
 3953:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3954:         $mimetype)=@_;
 3955:     my $fetchresult;
 3956:     my $home=&homeserver($docuname,$docudom);
 3957:     if ($action eq 'propagate') {
 3958:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3959: 			     $home);
 3960:     } else {
 3961:         my $fpath = '';
 3962:         my $fname = $file;
 3963:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3964:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3965:         my $filepath = &build_filepath($fpath);
 3966:         if ($action eq 'copy') {
 3967:             if ($source eq '') {
 3968:                 $fetchresult = 'no source file';
 3969:                 return $fetchresult;
 3970:             } else {
 3971:                 my $destination = $filepath.'/'.$fname;
 3972:                 rename($source,$destination);
 3973:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3974:                                  $home);
 3975:             }
 3976:         } elsif ($action eq 'uploaddoc') {
 3977:             open(my $fh,'>',$filepath.'/'.$fname);
 3978:             print $fh $env{'form.'.$source};
 3979:             close($fh);
 3980:             if ($parser eq 'parse') {
 3981:                 my $mm = new File::MMagic;
 3982:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3983:                 if ($type eq 'text/html') {
 3984:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3985:                     unless ($parse_result eq 'ok') {
 3986:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3987:                     }
 3988:                 }
 3989:                 if (ref($mimetype)) {
 3990:                     $$mimetype = $type;
 3991:                 } 
 3992:             }
 3993:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3994:                                  $home);
 3995:             if ($fetchresult eq 'ok') {
 3996:                 return '/uploaded/'.$fpath.'/'.$fname;
 3997:             } else {
 3998:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3999:                         ' to host '.$home.': '.$fetchresult);
 4000:                 return '/adm/notfound.html';
 4001:             }
 4002:         }
 4003:     }
 4004:     unless ( $fetchresult eq 'ok') {
 4005:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4006:              ' to host '.$home.': '.$fetchresult);
 4007:     }
 4008:     return $fetchresult;
 4009: }
 4010: 
 4011: sub build_filepath {
 4012:     my ($fpath) = @_;
 4013:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4014:     unless ($fpath eq '') {
 4015:         my @parts=split('/',$fpath);
 4016:         foreach my $part (@parts) {
 4017:             $filepath.= '/'.$part;
 4018:             if ((-e $filepath)!=1) {
 4019:                 mkdir($filepath,0777);
 4020:             }
 4021:         }
 4022:     }
 4023:     return $filepath;
 4024: }
 4025: 
 4026: sub store_edited_file {
 4027:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4028:     my $file = $primary_url;
 4029:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4030:     my $fpath = '';
 4031:     my $fname = $file;
 4032:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4033:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4034:     my $filepath = &build_filepath($fpath);
 4035:     open(my $fh,'>',$filepath.'/'.$fname);
 4036:     print $fh $content;
 4037:     close($fh);
 4038:     my $home=&homeserver($docuname,$docudom);
 4039:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4040: 			  $home);
 4041:     if ($$fetchresult eq 'ok') {
 4042:         return '/uploaded/'.$fpath.'/'.$fname;
 4043:     } else {
 4044:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4045: 		 ' to host '.$home.': '.$$fetchresult);
 4046:         return '/adm/notfound.html';
 4047:     }
 4048: }
 4049: 
 4050: sub clean_filename {
 4051:     my ($fname,$args)=@_;
 4052: # Replace Windows backslashes by forward slashes
 4053:     $fname=~s/\\/\//g;
 4054:     if (!$args->{'keep_path'}) {
 4055:         # Get rid of everything but the actual filename
 4056: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4057:     }
 4058: # Replace spaces by underscores
 4059:     $fname=~s/\s+/\_/g;
 4060: # Transliterate non-ascii text to ascii
 4061:     my $lang = &Apache::lonlocal::current_language();
 4062:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4063: # Replace all other weird characters by nothing
 4064:     $fname=~s{[^/\w\.\-]}{}g;
 4065: # Replace all .\d. sequences with _\d. so they no longer look like version
 4066: # numbers
 4067:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4068:     return $fname;
 4069: }
 4070: 
 4071: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4072: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4073: # image with the same aspect ratio as the original, but with dimensions which do 
 4074: # not exceed $resizewidth and $resizeheight.
 4075:  
 4076: sub resizeImage {
 4077:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4078:     my $ima = Image::Magick->new;
 4079:     my $resized;
 4080:     if (-e $img_path) {
 4081:         $ima->Read($img_path);
 4082:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4083:             my $width = $ima->Get('width');
 4084:             my $height = $ima->Get('height');
 4085:             if ($width > $resizewidth) {
 4086: 	        my $factor = $width/$resizewidth;
 4087:                 my $newheight = $height/$factor;
 4088:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4089:                 $resized = 1;
 4090:             }
 4091:         }
 4092:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4093:             my $width = $ima->Get('width');
 4094:             my $height = $ima->Get('height');
 4095:             if ($height > $resizeheight) {
 4096:                 my $factor = $height/$resizeheight;
 4097:                 my $newwidth = $width/$factor;
 4098:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4099:                 $resized = 1;
 4100:             }
 4101:         }
 4102:         if ($resized) {
 4103:             $ima->Write($img_path);
 4104:         }
 4105:     }
 4106:     return;
 4107: }
 4108: 
 4109: # --------------- Take an uploaded file and put it into the userfiles directory
 4110: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4111: #                    the desired filename is in $env{"form.$formname.filename"}
 4112: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4113: #                                    canceloverwrite, scantron or ''.
 4114: #                   if 'coursedoc': upload to the current course
 4115: #                   if 'existingfile': write file to tmp/overwrites directory 
 4116: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4117: #                   $context is passed as argument to &finishuserfileupload
 4118: #        $subdir - directory in userfile to store the file into
 4119: #        $parser - instruction to parse file for objects ($parser = parse) or
 4120: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4121: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4122: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4123: #        $allfiles - reference to hash for embedded objects
 4124: #        $codebase - reference to hash for codebase of java objects
 4125: #        $desuname - username for permanent storage of uploaded file
 4126: #        $dsetudom - domain for permanaent storage of uploaded file
 4127: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4128: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4129: #        $resizewidth - width (pixels) to which to resize uploaded image
 4130: #        $resizeheight - height (pixels) to which to resize uploaded image
 4131: #        $mimetype - reference to scalar to accommodate mime type determined
 4132: #                    from File::MMagic.
 4133: # 
 4134: # output: url of file in userspace, or error: <message> 
 4135: #             or /adm/notfound.html if failure to upload occurse
 4136: 
 4137: sub userfileupload {
 4138:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4139:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4140:     if (!defined($subdir)) { $subdir='unknown'; }
 4141:     my $fname=$env{'form.'.$formname.'.filename'};
 4142:     $fname=&clean_filename($fname);
 4143:     # See if there is anything left
 4144:     unless ($fname) { return 'error: no uploaded file'; }
 4145:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4146:     if ($fname =~ /^\./) {
 4147:         my ($s,$usec) = &gettimeofday();
 4148:         while (length($usec) < 6) {
 4149:             $usec = '0'.$usec;
 4150:         }
 4151:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4152:     }
 4153:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4154:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4155:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4156:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4157:         my $now = time;
 4158:         my $filepath;
 4159:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4160:              $filepath = 'tmp/helprequests/'.$now;
 4161:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4162:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4163:                          '_'.$env{'user.domain'}.'/pending';
 4164:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4165:             my ($docuname,$docudom);
 4166:             if ($destudom =~ /^$match_domain$/) {
 4167:                 $docudom = $destudom;
 4168:             } else {
 4169:                 $docudom = $env{'user.domain'};
 4170:             }
 4171:             if ($destuname =~ /^$match_username$/) {
 4172:                 $docuname = $destuname;
 4173:             } else {
 4174:                 $docuname = $env{'user.name'};
 4175:             }
 4176:             if (exists($env{'form.group'})) {
 4177:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4178:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4179:             }
 4180:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4181:             if ($context eq 'canceloverwrite') {
 4182:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4183:                 if (-e  $tempfile) {
 4184:                     my @info = stat($tempfile);
 4185:                     if ($info[9] eq $env{'form.timestamp'}) {
 4186:                         unlink($tempfile);
 4187:                     }
 4188:                 }
 4189:                 return;
 4190:             }
 4191:         }
 4192:         # Create the directory if not present
 4193:         my @parts=split(/\//,$filepath);
 4194:         my $fullpath = $perlvar{'lonDaemons'};
 4195:         for (my $i=0;$i<@parts;$i++) {
 4196:             $fullpath .= '/'.$parts[$i];
 4197:             if ((-e $fullpath)!=1) {
 4198:                 mkdir($fullpath,0777);
 4199:             }
 4200:         }
 4201:         open(my $fh,'>',$fullpath.'/'.$fname);
 4202:         print $fh $env{'form.'.$formname};
 4203:         close($fh);
 4204:         if ($context eq 'existingfile') {
 4205:             my @info = stat($fullpath.'/'.$fname);
 4206:             return ($fullpath.'/'.$fname,$info[9]);
 4207:         } else {
 4208:             return $fullpath.'/'.$fname;
 4209:         }
 4210:     }
 4211:     if ($subdir eq 'scantron') {
 4212:         $fname = 'scantron_orig_'.$fname;
 4213:     } else {
 4214:         $fname="$subdir/$fname";
 4215:     }
 4216:     if ($context eq 'coursedoc') {
 4217: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4218: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4219:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4220:             return &finishuserfileupload($docuname,$docudom,
 4221: 					 $formname,$fname,$parser,$allfiles,
 4222: 					 $codebase,$thumbwidth,$thumbheight,
 4223:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4224:         } else {
 4225:             if ($env{'form.folder'}) {
 4226:                 $fname=$env{'form.folder'}.'/'.$fname;
 4227:             }
 4228:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4229: 				       $fname,$formname,$parser,
 4230: 				       $allfiles,$codebase,$mimetype);
 4231:         }
 4232:     } elsif (defined($destuname)) {
 4233:         my $docuname=$destuname;
 4234:         my $docudom=$destudom;
 4235: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4236: 				     $parser,$allfiles,$codebase,
 4237:                                      $thumbwidth,$thumbheight,
 4238:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4239:     } else {
 4240:         my $docuname=$env{'user.name'};
 4241:         my $docudom=$env{'user.domain'};
 4242:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4243:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4244:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4245:         }
 4246: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4247: 				     $parser,$allfiles,$codebase,
 4248:                                      $thumbwidth,$thumbheight,
 4249:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4250:     }
 4251: }
 4252: 
 4253: sub finishuserfileupload {
 4254:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4255:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4256:     my $path=$docudom.'/'.$docuname.'/';
 4257:     my $filepath=$perlvar{'lonDocRoot'};
 4258:   
 4259:     my ($fnamepath,$file,$fetchthumb);
 4260:     $file=$fname;
 4261:     if ($fname=~m|/|) {
 4262:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4263: 	$path.=$fnamepath.'/';
 4264:     }
 4265:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4266:     my $count;
 4267:     for ($count=4;$count<=$#parts;$count++) {
 4268:         $filepath.="/$parts[$count]";
 4269:         if ((-e $filepath)!=1) {
 4270: 	    mkdir($filepath,0777);
 4271:         }
 4272:     }
 4273: 
 4274: # Save the file
 4275:     {
 4276: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4277: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4278: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4279: 	    return '/adm/notfound.html';
 4280: 	}
 4281:         if ($context eq 'overwrite') {
 4282:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4283:             my $target = $filepath.'/'.$file;
 4284:             if (-e $source) {
 4285:                 my @info = stat($source);
 4286:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4287:                     unless (&File::Copy::move($source,$target)) {
 4288:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4289:                         return "Moving from $source failed";
 4290:                     }
 4291:                 } else {
 4292:                     return "Temporary file: $source had unexpected date/time for last modification";
 4293:                 }
 4294:             } else {
 4295:                 return "Temporary file: $source missing";
 4296:             }
 4297:         } elsif (!print FH ($env{'form.'.$formname})) {
 4298: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4299: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4300: 	    return '/adm/notfound.html';
 4301: 	}
 4302: 	close(FH);
 4303:         if ($resizewidth && $resizeheight) {
 4304:             my $mm = new File::MMagic;
 4305:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4306:             if ($mime_type =~ m{^image/}) {
 4307: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4308:             }  
 4309: 	}
 4310:     }
 4311:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4312:         if (ref($mimetype)) {
 4313:             if ($$mimetype eq '') {
 4314:                 my $mm = new File::MMagic;
 4315:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4316:                 $$mimetype = $type;
 4317:             }
 4318:         }
 4319:     }
 4320:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4321:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4322:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4323:                                                        $allfiles,$codebase);
 4324:             unless ($parse_result eq 'ok') {
 4325:                 &logthis('Failed to parse '.$filepath.$file.
 4326: 	   	         ' for embedded media: '.$parse_result); 
 4327:             }
 4328:         }
 4329:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4330:         my $format = $env{'form.scantron_format'};
 4331:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4332:     }
 4333:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4334:         my $input = $filepath.'/'.$file;
 4335:         my $output = $filepath.'/'.'tn-'.$file;
 4336:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4337:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4338:         system({$args[0]} @args);
 4339:         if (-e $filepath.'/'.'tn-'.$file) {
 4340:             $fetchthumb  = 1; 
 4341:         }
 4342:     }
 4343:  
 4344: # Notify homeserver to grep it
 4345: #
 4346:     my $docuhome=&homeserver($docuname,$docudom);	
 4347:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4348:     if ($fetchresult eq 'ok') {
 4349:         if ($fetchthumb) {
 4350:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4351:             if ($thumbresult ne 'ok') {
 4352:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4353:                          $docuhome.': '.$thumbresult);
 4354:             }
 4355:         }
 4356: #
 4357: # Return the URL to it
 4358:         return '/uploaded/'.$path.$file;
 4359:     } else {
 4360:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4361: 		 ': '.$fetchresult);
 4362:         return '/adm/notfound.html';
 4363:     }
 4364: }
 4365: 
 4366: sub extract_embedded_items {
 4367:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4368:     my @state = ();
 4369:     my (%lastids,%related,%shockwave,%flashvars);
 4370:     my %javafiles = (
 4371:                       codebase => '',
 4372:                       code => '',
 4373:                       archive => ''
 4374:                     );
 4375:     my %mediafiles = (
 4376:                       src => '',
 4377:                       movie => '',
 4378:                      );
 4379:     my $p;
 4380:     if ($content) {
 4381:         $p = HTML::LCParser->new($content);
 4382:     } else {
 4383:         $p = HTML::LCParser->new($fullpath);
 4384:     }
 4385:     while (my $t=$p->get_token()) {
 4386: 	if ($t->[0] eq 'S') {
 4387: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4388: 	    push(@state, $tagname);
 4389:             if (lc($tagname) eq 'allow') {
 4390:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4391:             }
 4392: 	    if (lc($tagname) eq 'img') {
 4393: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4394: 	    }
 4395: 	    if (lc($tagname) eq 'a') {
 4396:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4397:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4398:                 }
 4399: 	    }
 4400:             if (lc($tagname) eq 'script') {
 4401:                 my $src;
 4402:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4403:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4404:                 } else {
 4405:                     if ($attr->{'src'} ne '') {
 4406:                         $src = $attr->{'src'};
 4407:                         &add_filetype($allfiles,$src,'src');
 4408:                     }
 4409:                 }
 4410:                 my $text = $p->get_trimmed_text();
 4411:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4412:                     my @swfargs = split(/,/,$1);
 4413:                     foreach my $item (@swfargs) {
 4414:                         $item =~ s/["']//g;
 4415:                         $item =~ s/^\s+//;
 4416:                         $item =~ s/\s+$//;
 4417:                     }
 4418:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4419:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4420:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4421:                         } else {
 4422:                             $related{$swfargs[0]} = [$swfargs[2]];
 4423:                         }
 4424:                     }
 4425:                 }
 4426:             }
 4427:             if (lc($tagname) eq 'link') {
 4428:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4429:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4430:                 }
 4431:             }
 4432: 	    if (lc($tagname) eq 'object' ||
 4433: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4434: 		foreach my $item (keys(%javafiles)) {
 4435: 		    $javafiles{$item} = '';
 4436: 		}
 4437:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4438:                     $lastids{lc($tagname)} = $attr->{'id'};
 4439:                 }
 4440: 	    }
 4441: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4442: 		my $name = lc($attr->{'name'});
 4443: 		foreach my $item (keys(%javafiles)) {
 4444: 		    if ($name eq $item) {
 4445: 			$javafiles{$item} = $attr->{'value'};
 4446: 			last;
 4447: 		    }
 4448: 		}
 4449:                 my $pathfrom;
 4450: 		foreach my $item (keys(%mediafiles)) {
 4451: 		    if ($name eq $item) {
 4452:                         $pathfrom = $attr->{'value'};
 4453:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4454: 			&add_filetype($allfiles,$pathfrom,$name);
 4455: 			last;
 4456: 		    }
 4457: 		}
 4458:                 if ($name eq 'flashvars') {
 4459:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4460:                 }
 4461:                 if ($pathfrom ne '') {
 4462:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4463:                                          $pathfrom);
 4464:                 }
 4465: 	    }
 4466: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4467: 		foreach my $item (keys(%javafiles)) {
 4468: 		    if ($attr->{$item}) {
 4469: 			$javafiles{$item} = $attr->{$item};
 4470: 			last;
 4471: 		    }
 4472: 		}
 4473: 		foreach my $item (keys(%mediafiles)) {
 4474: 		    if ($attr->{$item}) {
 4475: 			&add_filetype($allfiles,$attr->{$item},$item);
 4476: 			last;
 4477: 		    }
 4478: 		}
 4479:                 if (lc($tagname) eq 'embed') {
 4480:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4481:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4482:                                              $attr->{'src'});
 4483:                     }
 4484:                 }
 4485: 	    }
 4486:             if (lc($tagname) eq 'iframe') {
 4487:                 my $src = $attr->{'src'} ;
 4488:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4489:                     &add_filetype($allfiles,$src,'src');
 4490:                 } elsif ($src =~ m{^/}) {
 4491:                     if ($env{'request.course.id'}) {
 4492:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4493:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4494:                         my $url = &hreflocation('',$fullpath);
 4495:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4496:                             my $relpath = $1;
 4497:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4498:                                 &add_filetype($allfiles,$1,'src');
 4499:                             }
 4500:                         }
 4501:                     }
 4502:                 }
 4503:             }
 4504:             if ($t->[4] =~ m{/>$}) {
 4505:                 pop(@state);
 4506:             }
 4507: 	} elsif ($t->[0] eq 'E') {
 4508: 	    my ($tagname) = ($t->[1]);
 4509: 	    if ($javafiles{'codebase'} ne '') {
 4510: 		$javafiles{'codebase'} .= '/';
 4511: 	    }  
 4512: 	    if (lc($tagname) eq 'applet' ||
 4513: 		lc($tagname) eq 'object' ||
 4514: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4515: 		) {
 4516: 		foreach my $item (keys(%javafiles)) {
 4517: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4518: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4519: 			&add_filetype($allfiles,$file,$item);
 4520: 		    }
 4521: 		}
 4522: 	    } 
 4523: 	    pop @state;
 4524: 	}
 4525:     }
 4526:     foreach my $id (sort(keys(%flashvars))) {
 4527:         if ($shockwave{$id} ne '') {
 4528:             my @pairs = split(/\&/,$flashvars{$id});
 4529:             foreach my $pair (@pairs) {
 4530:                 my ($key,$value) = split(/\=/,$pair);
 4531:                 if ($key eq 'thumb') {
 4532:                     &add_filetype($allfiles,$value,$key);
 4533:                 } elsif ($key eq 'content') {
 4534:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4535:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4536:                     if ($ext ne '') {
 4537:                         &add_filetype($allfiles,$path.$value,$ext);
 4538:                     }
 4539:                 }
 4540:             }
 4541:         }
 4542:     }
 4543:     return 'ok';
 4544: }
 4545: 
 4546: sub add_filetype {
 4547:     my ($allfiles,$file,$type)=@_;
 4548:     if (exists($allfiles->{$file})) {
 4549: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4550: 	    push(@{$allfiles->{$file}}, &escape($type));
 4551: 	}
 4552:     } else {
 4553: 	@{$allfiles->{$file}} = (&escape($type));
 4554:     }
 4555: }
 4556: 
 4557: sub embedded_dependency {
 4558:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4559:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4560:         if (($identifier ne '') &&
 4561:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4562:             ($pathfrom ne '')) {
 4563:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4564:             foreach my $dep (@{$related->{$identifier}}) {
 4565:                 &add_filetype($allfiles,$path.$dep,'object');
 4566:             }
 4567:         }
 4568:     }
 4569:     return;
 4570: }
 4571: 
 4572: sub bubblesheet_converter {
 4573:     my ($cdom,$fullpath,$config,$format) = @_;
 4574:     if ((&domain($cdom) ne '') &&
 4575:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4576:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4577:         my (%csvcols,%csvoptions);
 4578:         if (ref($config->{'fields'}) eq 'HASH') {  
 4579:             %csvcols = %{$config->{'fields'}};
 4580:         }
 4581:         if (ref($config->{'options'}) eq 'HASH') {
 4582:             %csvoptions = %{$config->{'options'}};
 4583:         }
 4584:         my %csvbynum = reverse(%csvcols);
 4585:         my %scantronconf = &get_scantron_config($format,$cdom);
 4586:         if (keys(%scantronconf)) {
 4587:             my %bynum = (
 4588:                           $scantronconf{CODEstart} => 'CODEstart',
 4589:                           $scantronconf{IDstart}   => 'IDstart',
 4590:                           $scantronconf{PaperID}   => 'PaperID',
 4591:                           $scantronconf{FirstName} => 'FirstName',
 4592:                           $scantronconf{LastName}  => 'LastName',
 4593:                           $scantronconf{Qstart}    => 'Qstart',
 4594:                         );
 4595:             my @ordered;
 4596:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4597:                 push(@ordered,$bynum{$item});
 4598:             }
 4599:             my %mapstart = (
 4600:                               CODEstart => 'CODE',
 4601:                               IDstart   => 'ID',
 4602:                               PaperID   => 'PaperID',
 4603:                               FirstName => 'FirstName',
 4604:                               LastName  => 'LastName',
 4605:                               Qstart    => 'FirstQuestion',
 4606:                            );
 4607:             my %maplength = (
 4608:                               CODEstart => 'CODElength',
 4609:                               IDstart   => 'IDlength',
 4610:                               PaperID   => 'PaperIDlength',
 4611:                               FirstName => 'FirstNamelength',
 4612:                               LastName  => 'LastNamelength',
 4613:             );
 4614:             if (open(my $fh,'<',$fullpath)) {
 4615:                 my $output;
 4616:                 my %lettdig = &letter_to_digits();
 4617:                 my %diglett = reverse(%lettdig);
 4618:                 my $numletts = scalar(keys(%lettdig));
 4619:                 my $num = 0;
 4620:                 while (my $line=<$fh>) {
 4621:                     $num ++;
 4622:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4623:                     $line =~ s{[\r\n]+$}{};
 4624:                     my %found;
 4625:                     my @values = split(/,/,$line);
 4626:                     my ($qstart,$record);
 4627:                     for (my $i=0; $i<@values; $i++) {
 4628:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4629:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4630:                             if ($values[$i] eq '') {
 4631:                                 $values[$i] = $scantronconf{'Qoff'};
 4632:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4633:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4634:                                     $values[$i] = $lettdig{uc($values[$i])};
 4635:                                 }
 4636:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4637:                                 if ($values[$i] =~ /^[0-9]$/) {
 4638:                                     $values[$i] = $diglett{$values[$i]};
 4639:                                 }
 4640:                             } else {
 4641:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4642:                                     my $digit;
 4643:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4644:                                         $digit = $lettdig{uc($values[$i])}-1;
 4645:                                         if ($values[$i] eq 'J') {
 4646:                                             $digit += $numletts;
 4647:                                         }
 4648:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4649:                                         $digit = $values[$i]-1;
 4650:                                         if ($values[$i] eq '0') {
 4651:                                             $digit += $numletts;
 4652:                                         }
 4653:                                     }
 4654:                                     my $qval='';
 4655:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4656:                                         if ($j == $digit) {
 4657:                                             $qval .= $scantronconf{'Qon'};
 4658:                                         } else {
 4659:                                             $qval .= $scantronconf{'Qoff'};
 4660:                                         }
 4661:                                     }
 4662:                                     $values[$i] = $qval;
 4663:                                 }
 4664:                             }
 4665:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4666:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4667:                             }
 4668:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4669:                             if ($numblank > 0) {
 4670:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4671:                             }
 4672:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4673:                                 $qstart = $i;
 4674:                                 $found{$csvbynum{$i}} = $values[$i];
 4675:                             } else {
 4676:                                 $found{'FirstQuestion'} .= $values[$i];
 4677:                             }
 4678:                         } elsif (exists($csvbynum{$i})) {
 4679:                             if ($csvoptions{'rem'}) {
 4680:                                 $values[$i] =~ s/^\s+//;
 4681:                             }
 4682:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4683:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4684:                                     $values[$i] = '0'.$values[$i];
 4685:                                 }
 4686:                             }
 4687:                             $found{$csvbynum{$i}} = $values[$i];
 4688:                         }
 4689:                     }
 4690:                     foreach my $item (@ordered) {
 4691:                         my $currlength = 1+length($record);
 4692:                         my $numspaces = $scantronconf{$item} - $currlength;
 4693:                         if ($numspaces > 0) {
 4694:                             $record .= (' ' x $numspaces);
 4695:                         }
 4696:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4697:                             unless ($item eq 'Qstart') {
 4698:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4699:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4700:                                 }
 4701:                             }
 4702:                             $record .= $found{$mapstart{$item}};
 4703:                         }
 4704:                     }
 4705:                     $output .= "$record\n";
 4706:                 }
 4707:                 close($fh);
 4708:                 if ($output) {
 4709:                     if (open(my $fh,'>',$fullpath)) {
 4710:                         print $fh $output;
 4711:                         close($fh);
 4712:                     }
 4713:                 }
 4714:             }
 4715:         }
 4716:         return;
 4717:     }
 4718: }
 4719: 
 4720: sub letter_to_digits {
 4721:     my %lettdig = (
 4722:                     A => 1,
 4723:                     B => 2,
 4724:                     C => 3,
 4725:                     D => 4,
 4726:                     E => 5,
 4727:                     F => 6,
 4728:                     G => 7,
 4729:                     H => 8,
 4730:                     I => 9,
 4731:                     J => 0,
 4732:                   );
 4733:     return %lettdig;
 4734: }
 4735: 
 4736: sub get_scantron_config {
 4737:     my ($which,$cdom) = @_;
 4738:     my @lines = &get_scantronformat_file($cdom);
 4739:     my %config;
 4740:     #FIXME probably should move to XML it has already gotten a bit much now
 4741:     foreach my $line (@lines) {
 4742:         my ($name,$descrip)=split(/:/,$line);
 4743:         if ($name ne $which ) { next; }
 4744:         chomp($line);
 4745:         my @config=split(/:/,$line);
 4746:         $config{'name'}=$config[0];
 4747:         $config{'description'}=$config[1];
 4748:         $config{'CODElocation'}=$config[2];
 4749:         $config{'CODEstart'}=$config[3];
 4750:         $config{'CODElength'}=$config[4];
 4751:         $config{'IDstart'}=$config[5];
 4752:         $config{'IDlength'}=$config[6];
 4753:         $config{'Qstart'}=$config[7];
 4754:         $config{'Qlength'}=$config[8];
 4755:         $config{'Qoff'}=$config[9];
 4756:         $config{'Qon'}=$config[10];
 4757:         $config{'PaperID'}=$config[11];
 4758:         $config{'PaperIDlength'}=$config[12];
 4759:         $config{'FirstName'}=$config[13];
 4760:         $config{'FirstNamelength'}=$config[14];
 4761:         $config{'LastName'}=$config[15];
 4762:         $config{'LastNamelength'}=$config[16];
 4763:         $config{'BubblesPerRow'}=$config[17];
 4764:         last;
 4765:     }
 4766:     return %config;
 4767: }
 4768: 
 4769: sub get_scantronformat_file {
 4770:     my ($cdom) = @_;
 4771:     if ($cdom eq '') {
 4772:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4773:     }
 4774:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4775:     my $gottab = 0;
 4776:     my @lines;
 4777:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4778:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4779:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4780:             if ($formatfile ne '-1') {
 4781:                 @lines = split("\n",$formatfile,-1);
 4782:                 $gottab = 1;
 4783:             }
 4784:         }
 4785:     }
 4786:     if (!$gottab) {
 4787:         my $confname = $cdom.'-domainconfig';
 4788:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4789:         my $formatfile = &getfile($default);
 4790:         if ($formatfile ne '-1') {
 4791:             @lines = split("\n",$formatfile,-1);
 4792:             $gottab = 1;
 4793:         }
 4794:     }
 4795:     if (!$gottab) {
 4796:         my @domains = &current_machine_domains();
 4797:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4798:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4799:                 @lines = <$fh>;
 4800:                 close($fh);
 4801:             }
 4802:         } else {
 4803:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4804:                 @lines = <$fh>;
 4805:                 close($fh);
 4806:             }
 4807:         }
 4808:     }
 4809:     return @lines;
 4810: }
 4811: 
 4812: sub removeuploadedurl {
 4813:     my ($url)=@_;	
 4814:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4815:     return &removeuserfile($uname,$udom,$fname);
 4816: }
 4817: 
 4818: sub removeuserfile {
 4819:     my ($docuname,$docudom,$fname)=@_;
 4820:     my $home=&homeserver($docuname,$docudom);    
 4821:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4822:     if ($result eq 'ok') {	
 4823:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4824:             my $metafile = $fname.'.meta';
 4825:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4826: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4827:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4828:             my $sqlresult = 
 4829:                 &update_portfolio_table($docuname,$docudom,$file,
 4830:                                         'portfolio_metadata',$group,
 4831:                                         'delete');
 4832:         }
 4833:     }
 4834:     return $result;
 4835: }
 4836: 
 4837: sub mkdiruserfile {
 4838:     my ($docuname,$docudom,$dir)=@_;
 4839:     my $home=&homeserver($docuname,$docudom);
 4840:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4841: }
 4842: 
 4843: sub renameuserfile {
 4844:     my ($docuname,$docudom,$old,$new)=@_;
 4845:     my $home=&homeserver($docuname,$docudom);
 4846:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4847:                         &escape("$old").':'.&escape("$new"),$home);
 4848:     if ($result eq 'ok') {
 4849:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4850:             my $oldmeta = $old.'.meta';
 4851:             my $newmeta = $new.'.meta';
 4852:             my $metaresult = 
 4853:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4854: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4855:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4856:             my $sqlresult = 
 4857:                 &update_portfolio_table($docuname,$docudom,$file,
 4858:                                         'portfolio_metadata',$group,
 4859:                                         'delete');
 4860:         }
 4861:     }
 4862:     return $result;
 4863: }
 4864: 
 4865: # ------------------------------------------------------------------------- Log
 4866: 
 4867: sub log {
 4868:     my ($dom,$nam,$hom,$what)=@_;
 4869:     return critical("log:$dom:$nam:$what",$hom);
 4870: }
 4871: 
 4872: # ------------------------------------------------------------------ Course Log
 4873: #
 4874: # This routine flushes several buffers of non-mission-critical nature
 4875: #
 4876: 
 4877: sub flushcourselogs {
 4878:     &logthis('Flushing log buffers');
 4879: #
 4880: # course logs
 4881: # This is a log of all transactions in a course, which can be used
 4882: # for data mining purposes
 4883: #
 4884: # It also collects the courseid database, which lists last transaction
 4885: # times and course titles for all courseids
 4886: #
 4887:     my %courseidbuffer=();
 4888:     foreach my $crsid (keys(%courselogs)) {
 4889:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4890: 		          &escape($courselogs{$crsid}),
 4891: 		          $coursehombuf{$crsid}) eq 'ok') {
 4892: 	    delete $courselogs{$crsid};
 4893:         } else {
 4894:             &logthis('Failed to flush log buffer for '.$crsid);
 4895:             if (length($courselogs{$crsid})>40000) {
 4896:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4897:                         " exceeded maximum size, deleting.</font>");
 4898:                delete $courselogs{$crsid};
 4899:             }
 4900:         }
 4901:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4902:             'description' => $coursedescrbuf{$crsid},
 4903:             'inst_code'    => $courseinstcodebuf{$crsid},
 4904:             'type'        => $coursetypebuf{$crsid},
 4905:             'owner'       => $courseownerbuf{$crsid},
 4906:         };
 4907:     }
 4908: #
 4909: # Write course id database (reverse lookup) to homeserver of courses 
 4910: # Is used in pickcourse
 4911: #
 4912:     foreach my $crs_home (keys(%courseidbuffer)) {
 4913:         my $response = &courseidput(&host_domain($crs_home),
 4914:                                     $courseidbuffer{$crs_home},
 4915:                                     $crs_home,'timeonly');
 4916:     }
 4917: #
 4918: # File accesses
 4919: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4920: #
 4921:     foreach my $entry (keys(%accesshash)) {
 4922:         if ($entry =~ /___count$/) {
 4923:             my ($dom,$name);
 4924:             ($dom,$name,undef)=
 4925: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4926:             if (! defined($dom) || $dom eq '' || 
 4927:                 ! defined($name) || $name eq '') {
 4928:                 my $cid = $env{'request.course.id'};
 4929:                 $dom  = $env{'request.'.$cid.'.domain'};
 4930:                 $name = $env{'request.'.$cid.'.num'};
 4931:             }
 4932:             my $value = $accesshash{$entry};
 4933:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4934:             my %temphash=($url => $value);
 4935:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4936:             if ($result eq 'ok') {
 4937:                 delete $accesshash{$entry};
 4938:             }
 4939:         } else {
 4940:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4941:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4942:             my %temphash=($entry => $accesshash{$entry});
 4943:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4944:                 delete $accesshash{$entry};
 4945:             }
 4946:         }
 4947:     }
 4948: #
 4949: # Roles
 4950: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4951: #
 4952:     foreach my $entry (keys(%userrolehash)) {
 4953:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4954: 	    split(/\:/,$entry);
 4955:         if (&Apache::lonnet::put('nohist_userroles',
 4956:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4957:                 $rudom,$runame) eq 'ok') {
 4958: 	    delete $userrolehash{$entry};
 4959:         }
 4960:     }
 4961: #
 4962: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4963: #
 4964:     my %domrolebuffer = ();
 4965:     foreach my $entry (keys(%domainrolehash)) {
 4966:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4967:         if ($domrolebuffer{$rudom}) {
 4968:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4969:                       '='.&escape($domainrolehash{$entry});
 4970:         } else {
 4971:             $domrolebuffer{$rudom}.=&escape($entry).
 4972:                       '='.&escape($domainrolehash{$entry});
 4973:         }
 4974:         delete $domainrolehash{$entry};
 4975:     }
 4976:     foreach my $dom (keys(%domrolebuffer)) {
 4977: 	my %servers;
 4978: 	if (defined(&domain($dom,'primary'))) {
 4979: 	    my $primary=&domain($dom,'primary');
 4980: 	    my $hostname=&hostname($primary);
 4981: 	    $servers{$primary} = $hostname;
 4982: 	} else { 
 4983: 	    %servers = &get_servers($dom,'library');
 4984: 	}
 4985: 	foreach my $tryserver (keys(%servers)) {
 4986: 	    if (&reply('domroleput:'.$dom.':'.
 4987: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4988: 		last;
 4989: 	    } else {  
 4990: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4991: 	    }
 4992:         }
 4993:     }
 4994:     $dumpcount++;
 4995: }
 4996: 
 4997: sub courselog {
 4998:     my $what=shift;
 4999:     $what=time.':'.$what;
 5000:     unless ($env{'request.course.id'}) { return ''; }
 5001:     $coursedombuf{$env{'request.course.id'}}=
 5002:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5003:     $coursenumbuf{$env{'request.course.id'}}=
 5004:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5005:     $coursehombuf{$env{'request.course.id'}}=
 5006:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5007:     $coursedescrbuf{$env{'request.course.id'}}=
 5008:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5009:     $courseinstcodebuf{$env{'request.course.id'}}=
 5010:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5011:     $courseownerbuf{$env{'request.course.id'}}=
 5012:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5013:     $coursetypebuf{$env{'request.course.id'}}=
 5014:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5015:     if (defined $courselogs{$env{'request.course.id'}}) {
 5016: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5017:     } else {
 5018: 	$courselogs{$env{'request.course.id'}}.=$what;
 5019:     }
 5020:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5021: 	&flushcourselogs();
 5022:     }
 5023: }
 5024: 
 5025: sub courseacclog {
 5026:     my $fnsymb=shift;
 5027:     unless ($env{'request.course.id'}) { return ''; }
 5028:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5029:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5030:         $what.=':POST';
 5031:         # FIXME: Probably ought to escape things....
 5032: 	foreach my $key (keys(%env)) {
 5033:             if ($key=~/^form\.(.*)/) {
 5034:                 my $formitem = $1;
 5035:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5036:                     $what.=':'.$formitem.'='.$env{$key};
 5037:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5038:                     if ($formitem eq 'proctorpassword') {
 5039:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5040:                     } else {
 5041:                         $what.=':'.$formitem.'='.$env{$key};
 5042:                     }
 5043:                 }
 5044:             }
 5045:         }
 5046:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5047:         # FIXME: We should not be depending on a form parameter that someone
 5048:         # editing lonsearchcat.pm might change in the future.
 5049:         if ($env{'form.phase'} eq 'course_search') {
 5050:             $what.= ':POST';
 5051:             # FIXME: Probably ought to escape things....
 5052:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5053:                                  'crsdiscuss') {
 5054:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5055:             }
 5056:         }
 5057:     }
 5058:     &courselog($what);
 5059: }
 5060: 
 5061: sub countacc {
 5062:     my $url=&declutter(shift);
 5063:     return if (! defined($url) || $url eq '');
 5064:     unless ($env{'request.course.id'}) { return ''; }
 5065: #
 5066: # Mark that this url was used in this course
 5067: #
 5068:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5069: #
 5070: # Increase the access count for this resource in this child process
 5071: #
 5072:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5073:     $accesshash{$key}++;
 5074: }
 5075: 
 5076: sub linklog {
 5077:     my ($from,$to)=@_;
 5078:     $from=&declutter($from);
 5079:     $to=&declutter($to);
 5080:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5081:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5082: }
 5083: 
 5084: sub statslog {
 5085:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5086:     if ($users<2) { return; }
 5087:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5088:             'course'       => $env{'request.course.id'},
 5089:             'sections'     => '"all"',
 5090:             'num_students' => $users,
 5091:             'part'         => $part,
 5092:             'symb'         => $symb,
 5093:             'mean_tries'   => $av_attempts,
 5094:             'deg_of_diff'  => $degdiff});
 5095:     foreach my $key (keys(%dynstore)) {
 5096:         $accesshash{$key}=$dynstore{$key};
 5097:     }
 5098: }
 5099:   
 5100: sub userrolelog {
 5101:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5102:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5103:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5104:        $userrolehash
 5105:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5106:                     =$tend.':'.$tstart;
 5107:     }
 5108:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5109:        $userrolehash
 5110:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5111:                     =$tend.':'.$tstart;
 5112:     }
 5113:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5114:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5115:        $domainrolehash
 5116:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5117:                     = $tend.':'.$tstart;
 5118:     }
 5119: }
 5120: 
 5121: sub courserolelog {
 5122:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5123:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5124:         my $cdom = $1;
 5125:         my $cnum = $2;
 5126:         my $sec = $3;
 5127:         my $namespace = 'rolelog';
 5128:         my %storehash = (
 5129:                            role    => $trole,
 5130:                            start   => $tstart,
 5131:                            end     => $tend,
 5132:                            selfenroll => $selfenroll,
 5133:                            context    => $context,
 5134:                         );
 5135:         if ($trole eq 'gr') {
 5136:             $namespace = 'groupslog';
 5137:             $storehash{'group'} = $sec;
 5138:         } else {
 5139:             $storehash{'section'} = $sec;
 5140:         }
 5141:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5142:                    $domain,$cnum,$cdom);
 5143:         if (($trole ne 'st') || ($sec ne '')) {
 5144:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5145:         }
 5146:     }
 5147:     return;
 5148: }
 5149: 
 5150: sub domainrolelog {
 5151:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5152:     if ($area =~ m{^/($match_domain)/$}) {
 5153:         my $cdom = $1;
 5154:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5155:         my $namespace = 'rolelog';
 5156:         my %storehash = (
 5157:                            role    => $trole,
 5158:                            start   => $tstart,
 5159:                            end     => $tend,
 5160:                            context => $context,
 5161:                         );
 5162:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5163:                    $domain,$domconfiguser,$cdom);
 5164:     }
 5165:     return;
 5166: 
 5167: }
 5168: 
 5169: sub coauthorrolelog {
 5170:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5171:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5172:         my $audom = $1;
 5173:         my $auname = $2;
 5174:         my $namespace = 'rolelog';
 5175:         my %storehash = (
 5176:                            role    => $trole,
 5177:                            start   => $tstart,
 5178:                            end     => $tend,
 5179:                            context => $context,
 5180:                         );
 5181:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5182:                    $domain,$auname,$audom);
 5183:     }
 5184:     return;
 5185: }
 5186: 
 5187: sub get_course_adv_roles {
 5188:     my ($cid,$codes) = @_;
 5189:     $cid=$env{'request.course.id'} unless (defined($cid));
 5190:     my %coursehash=&coursedescription($cid);
 5191:     my $crstype = &Apache::loncommon::course_type($cid);
 5192:     my %nothide=();
 5193:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5194:         if ($user !~ /:/) {
 5195: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5196:         } else {
 5197:             $nothide{$user}=1;
 5198:         }
 5199:     }
 5200:     my @possdoms = ($coursehash{'domain'});
 5201:     if ($coursehash{'checkforpriv'}) {
 5202:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5203:     }
 5204:     my %returnhash=();
 5205:     my %dumphash=
 5206:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5207:     my $now=time;
 5208:     my %privileged;
 5209:     foreach my $entry (keys(%dumphash)) {
 5210: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5211:         if (($tstart) && ($tstart<0)) { next; }
 5212:         if (($tend) && ($tend<$now)) { next; }
 5213:         if (($tstart) && ($now<$tstart)) { next; }
 5214:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5215: 	if ($username eq '' || $domain eq '') { next; }
 5216:         if ((&privileged($username,$domain,\@possdoms)) &&
 5217:             (!$nothide{$username.':'.$domain})) { next; }
 5218: 	if ($role eq 'cr') { next; }
 5219:         if ($codes) {
 5220:             if ($section) { $role .= ':'.$section; }
 5221:             if ($returnhash{$role}) {
 5222:                 $returnhash{$role}.=','.$username.':'.$domain;
 5223:             } else {
 5224:                 $returnhash{$role}=$username.':'.$domain;
 5225:             }
 5226:         } else {
 5227:             my $key=&plaintext($role,$crstype);
 5228:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5229:             if ($returnhash{$key}) {
 5230: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5231:             } else {
 5232:                 $returnhash{$key}=$username.':'.$domain;
 5233:             }
 5234:         }
 5235:     }
 5236:     return %returnhash;
 5237: }
 5238: 
 5239: sub get_my_roles {
 5240:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5241:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5242:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5243:     my (%dumphash,%nothide);
 5244:     if ($context eq 'userroles') {
 5245:         %dumphash = &dump('roles',$udom,$uname);
 5246:     } else {
 5247:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5248:         if ($hidepriv) {
 5249:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5250:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5251:                 if ($user !~ /:/) {
 5252:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5253:                 } else {
 5254:                     $nothide{$user} = 1;
 5255:                 }
 5256:             }
 5257:         }
 5258:     }
 5259:     my %returnhash=();
 5260:     my $now=time;
 5261:     my %privileged;
 5262:     foreach my $entry (keys(%dumphash)) {
 5263:         my ($role,$tend,$tstart);
 5264:         if ($context eq 'userroles') {
 5265:             next if ($entry =~ /^rolesdef/);
 5266: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5267:         } else {
 5268:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5269:         }
 5270:         if (($tstart) && ($tstart<0)) { next; }
 5271:         my $status = 'active';
 5272:         if (($tend) && ($tend<=$now)) {
 5273:             $status = 'previous';
 5274:         } 
 5275:         if (($tstart) && ($now<$tstart)) {
 5276:             $status = 'future';
 5277:         }
 5278:         if (ref($types) eq 'ARRAY') {
 5279:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5280:                 next;
 5281:             } 
 5282:         } else {
 5283:             if ($status ne 'active') {
 5284:                 next;
 5285:             }
 5286:         }
 5287:         my ($rolecode,$username,$domain,$section,$area);
 5288:         if ($context eq 'userroles') {
 5289:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5290:             (undef,$domain,$username,$section) = split(/\//,$area);
 5291:         } else {
 5292:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5293:         }
 5294:         if (ref($roledoms) eq 'ARRAY') {
 5295:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5296:                 next;
 5297:             }
 5298:         }
 5299:         if (ref($roles) eq 'ARRAY') {
 5300:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5301:                 if ($role =~ /^cr\//) {
 5302:                     if (!grep(/^cr$/,@{$roles})) {
 5303:                         next;
 5304:                     }
 5305:                 } elsif ($role =~ /^gr\//) {
 5306:                     if (!grep(/^gr$/,@{$roles})) {
 5307:                         next;
 5308:                     }
 5309:                 } else {
 5310:                     next;
 5311:                 }
 5312:             }
 5313:         }
 5314:         if ($hidepriv) {
 5315:             my @privroles = ('dc','su');
 5316:             if ($context eq 'userroles') {
 5317:                 next if (grep(/^\Q$role\E$/,@privroles));
 5318:             } else {
 5319:                 my $possdoms = [$domain];
 5320:                 if (ref($roledoms) eq 'ARRAY') {
 5321:                    push(@{$possdoms},@{$roledoms}); 
 5322:                 }
 5323:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5324:                     if (!$nothide{$username.':'.$domain}) {
 5325:                         next;
 5326:                     }
 5327:                 }
 5328:             }
 5329:         }
 5330:         if ($withsec) {
 5331:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5332:                 $tstart.':'.$tend;
 5333:         } else {
 5334:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5335:         }
 5336:     }
 5337:     return %returnhash;
 5338: }
 5339: 
 5340: sub get_all_adhocroles {
 5341:     my ($dom) = @_;
 5342:     my @roles_by_num = ();
 5343:     my %domdefaults = &get_domain_defaults($dom);
 5344:     my (%description,%access_in_dom,%access_info);
 5345:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5346:         my $count = 0;
 5347:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5348:         my %ordered;
 5349:         foreach my $role (sort(keys(%domcurrent))) {
 5350:             my ($order,$desc,$access_in_dom);
 5351:             if (ref($domcurrent{$role}) eq 'HASH') {
 5352:                 $order = $domcurrent{$role}{'order'};
 5353:                 $desc = $domcurrent{$role}{'desc'};
 5354:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5355:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5356:             }
 5357:             if ($order eq '') {
 5358:                 $order = $count;
 5359:             }
 5360:             $ordered{$order} = $role;
 5361:             if ($desc ne '') {
 5362:                 $description{$role} = $desc;
 5363:             } else {
 5364:                 $description{$role}= $role;
 5365:             }
 5366:             $count++;
 5367:         }
 5368:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5369:             push(@roles_by_num,$ordered{$item});
 5370:         }
 5371:     }
 5372:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5373: }
 5374: 
 5375: sub get_my_adhocroles {
 5376:     my ($cid,$checkreg) = @_;
 5377:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5378:     if ($env{'request.course.id'} eq $cid) {
 5379:         $cdom = $env{'course.'.$cid.'.domain'};
 5380:         $cnum = $env{'course.'.$cid.'.num'};
 5381:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5382:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5383:         $cdom = $1;
 5384:         $cnum = $2;
 5385:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5386:                                      $cdom,$cnum);
 5387:     }
 5388:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5389:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5390:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5391:         if ($rosterhash{$user} ne '') {
 5392:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5393:             return ([],{}) if ($type eq 'auto');
 5394:         }
 5395:     }
 5396:     if (($cdom ne '') && ($cnum ne ''))  {
 5397:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5398:             my $then=$env{'user.login.time'};
 5399:             my $update=$env{'user.update.time'};
 5400:             if (!$update) {
 5401:                 $update = $then;
 5402:             }
 5403:             my @liveroles;
 5404:             foreach my $role ('dh','da') {
 5405:                 if ($env{"user.role.$role./$cdom/"}) {
 5406:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5407:                     my $limit = $update;
 5408:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5409:                         $limit = $then;
 5410:                     }
 5411:                     my $activerole = 1;
 5412:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5413:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5414:                     if ($activerole) {
 5415:                         push(@liveroles,$role);
 5416:                     }
 5417:                 }
 5418:             }
 5419:             if (@liveroles) {
 5420:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5421:                     my ($accessref,$accessinfo,%access_in_dom);
 5422:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5423:                     if (ref($roles_by_num) eq 'ARRAY') {
 5424:                         if (@{$roles_by_num}) {
 5425:                             my %settings;
 5426:                             if ($env{'request.course.id'} eq $cid) {
 5427:                                 foreach my $envkey (keys(%env)) {
 5428:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5429:                                         $settings{$1} = $env{$envkey};
 5430:                                     }
 5431:                                 }
 5432:                             } else {
 5433:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5434:                             }
 5435:                             my %setincrs;
 5436:                             if ($settings{'internal.adhocaccess'}) {
 5437:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5438:                             }
 5439:                             my @statuses;
 5440:                             if ($env{'environment.inststatus'}) {
 5441:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5442:                             }
 5443:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5444:                             if (ref($accessref) eq 'HASH') {
 5445:                                 %access_in_dom = %{$accessref};
 5446:                             }
 5447:                             foreach my $role (@{$roles_by_num}) {
 5448:                                 my ($curraccess,@okstatus,@personnel);
 5449:                                 if ($setincrs{$role}) {
 5450:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5451:                                     if ($curraccess eq 'status') {
 5452:                                         @okstatus = split(/\&/,$rest);
 5453:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5454:                                         @personnel = split(/\&/,$rest);
 5455:                                     }
 5456:                                 } else {
 5457:                                     $curraccess = $access_in_dom{$role};
 5458:                                     if (ref($accessinfo) eq 'HASH') {
 5459:                                         if ($curraccess eq 'status') {
 5460:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5461:                                                 @okstatus = @{$accessinfo->{$role}};
 5462:                                             }
 5463:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5464:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5465:                                                 @personnel = @{$accessinfo->{$role}};
 5466:                                             }
 5467:                                         }
 5468:                                     }
 5469:                                 }
 5470:                                 if ($curraccess eq 'none') {
 5471:                                     next;
 5472:                                 } elsif ($curraccess eq 'all') {
 5473:                                     push(@possroles,$role);
 5474:                                 } elsif ($curraccess eq 'dh') {
 5475:                                     if (grep(/^dh$/,@liveroles)) {
 5476:                                         push(@possroles,$role);
 5477:                                     } else {
 5478:                                         next;
 5479:                                     }
 5480:                                 } elsif ($curraccess eq 'da') {
 5481:                                     if (grep(/^da$/,@liveroles)) {
 5482:                                         push(@possroles,$role);
 5483:                                     } else {
 5484:                                         next;
 5485:                                     }
 5486:                                 } elsif ($curraccess eq 'status') {
 5487:                                     if (@okstatus) {
 5488:                                         if (!@statuses) {
 5489:                                             if (grep(/^default$/,@okstatus)) {
 5490:                                                 push(@possroles,$role);
 5491:                                             }
 5492:                                         } else {
 5493:                                             foreach my $status (@okstatus) {
 5494:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5495:                                                     push(@possroles,$role);
 5496:                                                     last;
 5497:                                                 }
 5498:                                             }
 5499:                                         }
 5500:                                     }
 5501:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5502:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5503:                                         if ($curraccess eq 'exc') {
 5504:                                             push(@possroles,$role);
 5505:                                         }
 5506:                                     } elsif ($curraccess eq 'inc') {
 5507:                                         push(@possroles,$role);
 5508:                                     }
 5509:                                 }
 5510:                             }
 5511:                         }
 5512:                     }
 5513:                 }
 5514:             }
 5515:         }
 5516:     }
 5517:     unless (ref($description) eq 'HASH') {
 5518:         if (ref($roles_by_num) eq 'ARRAY') {
 5519:             my %desc;
 5520:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5521:             $description = \%desc;
 5522:         } else {
 5523:             $description = {};
 5524:         }
 5525:     }
 5526:     return (\@possroles,$description);
 5527: }
 5528: 
 5529: # ----------------------------------------------------- Frontpage Announcements
 5530: #
 5531: #
 5532: 
 5533: sub postannounce {
 5534:     my ($server,$text)=@_;
 5535:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5536:     unless ($text=~/\w/) { $text=''; }
 5537:     return &reply('setannounce:'.&escape($text),$server);
 5538: }
 5539: 
 5540: sub getannounce {
 5541: 
 5542:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5543: 	my $announcement='';
 5544: 	while (my $line = <$fh>) { $announcement .= $line; }
 5545: 	close($fh);
 5546: 	if ($announcement=~/\w/) { 
 5547: 	    return 
 5548:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5549:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5550: 	} else {
 5551: 	    return '';
 5552: 	}
 5553:     } else {
 5554: 	return '';
 5555:     }
 5556: }
 5557: 
 5558: # ---------------------------------------------------------- Course ID routines
 5559: # Deal with domain's nohist_courseid.db files
 5560: #
 5561: 
 5562: sub courseidput {
 5563:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5564:     return unless (ref($storehash) eq 'HASH');
 5565:     my $outcome;
 5566:     if ($caller eq 'timeonly') {
 5567:         my $cids = '';
 5568:         foreach my $item (keys(%$storehash)) {
 5569:             $cids.=&escape($item).'&';
 5570:         }
 5571:         $cids=~s/\&$//;
 5572:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5573:                           $coursehome);       
 5574:     } else {
 5575:         my $items = '';
 5576:         foreach my $item (keys(%$storehash)) {
 5577:             $items.= &escape($item).'='.
 5578:                      &freeze_escape($$storehash{$item}).'&';
 5579:         }
 5580:         $items=~s/\&$//;
 5581:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5582:                           $coursehome);
 5583:     }
 5584:     if ($outcome eq 'unknown_cmd') {
 5585:         my $what;
 5586:         foreach my $cid (keys(%$storehash)) {
 5587:             $what .= &escape($cid).'=';
 5588:             foreach my $item ('description','inst_code','owner','type') {
 5589:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5590:             }
 5591:             $what =~ s/\:$/&/;
 5592:         }
 5593:         $what =~ s/\&$//;  
 5594:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5595:     } else {
 5596:         return $outcome;
 5597:     }
 5598: }
 5599: 
 5600: sub courseiddump {
 5601:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5602:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5603:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5604:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5605:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5606:     my $as_hash = 1;
 5607:     my %returnhash;
 5608:     if (!$domfilter) { $domfilter=''; }
 5609:     my %libserv = &all_library();
 5610:     foreach my $tryserver (keys(%libserv)) {
 5611:         if ( (  $hostidflag == 1 
 5612: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5613: 	     || (!defined($hostidflag)) ) {
 5614: 
 5615: 	    if (($domfilter eq '') ||
 5616: 		(&host_domain($tryserver) eq $domfilter)) {
 5617:                 my $rep;
 5618:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5619:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5620:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5621:                                 &escape($descfilter), &escape($instcodefilter), 
 5622:                                 &escape($ownerfilter), &escape($coursefilter),
 5623:                                 &escape($typefilter), &escape($regexp_ok), 
 5624:                                 $as_hash, &escape($selfenrollonly), 
 5625:                                 &escape($catfilter), $showhidden, $caller, 
 5626:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5627:                                 &escape($createdbefore), &escape($createdafter), 
 5628:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5629:                                 $reqcrsdom,&escape($reqinstcode))));
 5630:                 } else {
 5631:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5632:                              $sincefilter.':'.&escape($descfilter).':'.
 5633:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5634:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5635:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5636:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5637:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5638:                              &escape($cc_clone).':'.$cloneonly.':'.
 5639:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5640:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5641:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5642:                 }
 5643:                      
 5644:                 my @pairs=split(/\&/,$rep);
 5645:                 foreach my $item (@pairs) {
 5646:                     my ($key,$value)=split(/\=/,$item,2);
 5647:                     $key = &unescape($key);
 5648:                     next if ($key =~ /^error: 2 /);
 5649:                     my $result = &thaw_unescape($value);
 5650:                     if (ref($result) eq 'HASH') {
 5651:                         $returnhash{$key}=$result;
 5652:                     } else {
 5653:                         my @responses = split(/:/,$value);
 5654:                         my @items = ('description','inst_code','owner','type');
 5655:                         for (my $i=0; $i<@responses; $i++) {
 5656:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5657:                         }
 5658:                     }
 5659:                 }
 5660:             }
 5661:         }
 5662:     }
 5663:     return %returnhash;
 5664: }
 5665: 
 5666: sub courselastaccess {
 5667:     my ($cdom,$cnum,$hostidref) = @_;
 5668:     my %returnhash;
 5669:     if ($cdom && $cnum) {
 5670:         my $chome = &homeserver($cnum,$cdom);
 5671:         if ($chome ne 'no_host') {
 5672:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5673:             &extract_lastaccess(\%returnhash,$rep);
 5674:         }
 5675:     } else {
 5676:         if (!$cdom) { $cdom=''; }
 5677:         my %libserv = &all_library();
 5678:         foreach my $tryserver (keys(%libserv)) {
 5679:             if (ref($hostidref) eq 'ARRAY') {
 5680:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5681:             } 
 5682:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5683:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5684:                 &extract_lastaccess(\%returnhash,$rep);
 5685:             }
 5686:         }
 5687:     }
 5688:     return %returnhash;
 5689: }
 5690: 
 5691: sub extract_lastaccess {
 5692:     my ($returnhash,$rep) = @_;
 5693:     if (ref($returnhash) eq 'HASH') {
 5694:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5695:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5696:                  $rep eq '') {
 5697:             my @pairs=split(/\&/,$rep);
 5698:             foreach my $item (@pairs) {
 5699:                 my ($key,$value)=split(/\=/,$item,2);
 5700:                 $key = &unescape($key);
 5701:                 next if ($key =~ /^error: 2 /);
 5702:                 $returnhash->{$key} = &thaw_unescape($value);
 5703:             }
 5704:         }
 5705:     }
 5706:     return;
 5707: }
 5708: 
 5709: # ---------------------------------------------------------- DC e-mail
 5710: 
 5711: sub dcmailput {
 5712:     my ($domain,$msgid,$message,$server)=@_;
 5713:     my $status = &Apache::lonnet::critical(
 5714:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5715:        &escape($message),$server);
 5716:     return $status;
 5717: }
 5718: 
 5719: sub dcmaildump {
 5720:     my ($dom,$startdate,$enddate,$senders) = @_;
 5721:     my %returnhash=();
 5722: 
 5723:     if (defined(&domain($dom,'primary'))) {
 5724:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5725:                                                          &escape($enddate).':';
 5726: 	my @esc_senders=map { &escape($_)} @$senders;
 5727: 	$cmd.=&escape(join('&',@esc_senders));
 5728: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5729:             my ($key,$value) = split(/\=/,$line,2);
 5730:             if (($key) && ($value)) {
 5731:                 $returnhash{&unescape($key)} = &unescape($value);
 5732:             }
 5733:         }
 5734:     }
 5735:     return %returnhash;
 5736: }
 5737: # ---------------------------------------------------------- Domain roles
 5738: 
 5739: sub get_domain_roles {
 5740:     my ($dom,$roles,$startdate,$enddate)=@_;
 5741:     if ((!defined($startdate)) || ($startdate eq '')) {
 5742:         $startdate = '.';
 5743:     }
 5744:     if ((!defined($enddate)) || ($enddate eq '')) {
 5745:         $enddate = '.';
 5746:     }
 5747:     my $rolelist;
 5748:     if (ref($roles) eq 'ARRAY') {
 5749:         $rolelist = join('&',@{$roles});
 5750:     }
 5751:     my %personnel = ();
 5752: 
 5753:     my %servers = &get_servers($dom,'library');
 5754:     foreach my $tryserver (keys(%servers)) {
 5755: 	%{$personnel{$tryserver}}=();
 5756: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5757: 					    &escape($startdate).':'.
 5758: 					    &escape($enddate).':'.
 5759: 					    &escape($rolelist), $tryserver))) {
 5760: 	    my ($key,$value) = split(/\=/,$line,2);
 5761: 	    if (($key) && ($value)) {
 5762: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5763: 	    }
 5764: 	}
 5765:     }
 5766:     return %personnel;
 5767: }
 5768: 
 5769: sub get_active_domroles {
 5770:     my ($dom,$roles) = @_;
 5771:     return () unless (ref($roles) eq 'ARRAY');
 5772:     my $now = time;
 5773:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5774:     my %domroles;
 5775:     foreach my $server (keys(%dompersonnel)) {
 5776:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5777:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5778:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5779:         }
 5780:     }
 5781:     return %domroles;
 5782: }
 5783: 
 5784: # ----------------------------------------------------------- Interval timing 
 5785: 
 5786: {
 5787: # Caches needed for speedup of navmaps
 5788: # We don't want to cache this for very long at all (5 seconds at most)
 5789: # 
 5790: # The user for whom we cache
 5791: my $cachedkey='';
 5792: # The cached times for this user
 5793: my %cachedtimes=();
 5794: # When this was last done
 5795: my $cachedtime='';
 5796: 
 5797: sub load_all_first_access {
 5798:     my ($uname,$udom,$ignorecache)=@_;
 5799:     if (($cachedkey eq $uname.':'.$udom) &&
 5800:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5801:         (!$ignorecache)) {
 5802:         return;
 5803:     }
 5804:     $cachedtime=time;
 5805:     $cachedkey=$uname.':'.$udom;
 5806:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5807: }
 5808: 
 5809: sub get_first_access {
 5810:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5811:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5812:     if ($argsymb) { $symb=$argsymb; }
 5813:     my ($map,$id,$res)=&decode_symb($symb);
 5814:     if ($argmap) { $map = $argmap; }
 5815:     if ($type eq 'course') {
 5816: 	$res='course';
 5817:     } elsif ($type eq 'map') {
 5818: 	$res=&symbread($map);
 5819:     } else {
 5820: 	$res=$symb;
 5821:     }
 5822:     &load_all_first_access($uname,$udom,$ignorecache);
 5823:     return $cachedtimes{"$courseid\0$res"};
 5824: }
 5825: 
 5826: sub set_first_access {
 5827:     my ($type,$interval)=@_;
 5828:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5829:     my ($map,$id,$res)=&decode_symb($symb);
 5830:     if ($type eq 'course') {
 5831: 	$res='course';
 5832:     } elsif ($type eq 'map') {
 5833: 	$res=&symbread($map);
 5834:     } else {
 5835: 	$res=$symb;
 5836:     }
 5837:     $cachedkey='';
 5838:     my $firstaccess=&get_first_access($type,$symb,$map);
 5839:     if ($firstaccess) {
 5840:         &logthis("First access time already set ($firstaccess) when attempting ".
 5841:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5842:                  "in $courseid");
 5843:         return 'already_set';
 5844:     } else {
 5845:         my $start = time;
 5846: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5847:                           $udom,$uname);
 5848:         if ($putres eq 'ok') {
 5849:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5850:                  $udom,$uname); 
 5851:             &appenv(
 5852:                      {
 5853:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5854:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5855:                      }
 5856:                   );
 5857:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5858:                 $cachedtimes{"$courseid\0$res"} = $start;
 5859:             }
 5860:         } elsif ($putres ne 'refused') {
 5861:             &logthis("Result: $putres when attempting to set first access time ".
 5862:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5863:         }
 5864:         return $putres;
 5865:     }
 5866:     return 'already_set';
 5867: }
 5868: }
 5869: 
 5870: # --------------------------------------------- Set Expire Date for Spreadsheet
 5871: 
 5872: sub expirespread {
 5873:     my ($uname,$udom,$stype,$usymb)=@_;
 5874:     my $cid=$env{'request.course.id'}; 
 5875:     if ($cid) {
 5876:        my $now=time;
 5877:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5878:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5879:                             $env{'course.'.$cid.'.num'}.
 5880: 	        	    ':nohist_expirationdates:'.
 5881:                             &escape($key).'='.$now,
 5882:                             $env{'course.'.$cid.'.home'})
 5883:     }
 5884:     return 'ok';
 5885: }
 5886: 
 5887: # ----------------------------------------------------- Devalidate Spreadsheets
 5888: 
 5889: sub devalidate {
 5890:     my ($symb,$uname,$udom)=@_;
 5891:     my $cid=$env{'request.course.id'}; 
 5892:     if ($cid) {
 5893:         # delete the stored spreadsheets for
 5894:         # - the student level sheet of this user in course's homespace
 5895:         # - the assessment level sheet for this resource 
 5896:         #   for this user in user's homespace
 5897: 	# - current conditional state info
 5898: 	my $key=$uname.':'.$udom.':';
 5899:         my $status=
 5900: 	    &del('nohist_calculatedsheets',
 5901: 		 [$key.'studentcalc:'],
 5902: 		 $env{'course.'.$cid.'.domain'},
 5903: 		 $env{'course.'.$cid.'.num'})
 5904: 		.' '.
 5905: 	    &del('nohist_calculatedsheets_'.$cid,
 5906: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5907:         unless ($status eq 'ok ok') {
 5908:            &logthis('Could not devalidate spreadsheet '.
 5909:                     $uname.' at '.$udom.' for '.
 5910: 		    $symb.': '.$status);
 5911:         }
 5912: 	&delenv('user.state.'.$cid);
 5913:     }
 5914: }
 5915: 
 5916: sub get_scalar {
 5917:     my ($string,$end) = @_;
 5918:     my $value;
 5919:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5920: 	$value = $1;
 5921:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5922: 	$value = $1;
 5923:     }
 5924:     return &unescape($value);
 5925: }
 5926: 
 5927: sub array2str {
 5928:   my (@array) = @_;
 5929:   my $result=&arrayref2str(\@array);
 5930:   $result=~s/^__ARRAY_REF__//;
 5931:   $result=~s/__END_ARRAY_REF__$//;
 5932:   return $result;
 5933: }
 5934: 
 5935: sub arrayref2str {
 5936:   my ($arrayref) = @_;
 5937:   my $result='__ARRAY_REF__';
 5938:   foreach my $elem (@$arrayref) {
 5939:     if(ref($elem) eq 'ARRAY') {
 5940:       $result.=&arrayref2str($elem).'&';
 5941:     } elsif(ref($elem) eq 'HASH') {
 5942:       $result.=&hashref2str($elem).'&';
 5943:     } elsif(ref($elem)) {
 5944:       #print("Got a ref of ".(ref($elem))." skipping.");
 5945:     } else {
 5946:       $result.=&escape($elem).'&';
 5947:     }
 5948:   }
 5949:   $result=~s/\&$//;
 5950:   $result .= '__END_ARRAY_REF__';
 5951:   return $result;
 5952: }
 5953: 
 5954: sub hash2str {
 5955:   my (%hash) = @_;
 5956:   my $result=&hashref2str(\%hash);
 5957:   $result=~s/^__HASH_REF__//;
 5958:   $result=~s/__END_HASH_REF__$//;
 5959:   return $result;
 5960: }
 5961: 
 5962: sub hashref2str {
 5963:   my ($hashref)=@_;
 5964:   my $result='__HASH_REF__';
 5965:   foreach my $key (sort(keys(%$hashref))) {
 5966:     if (ref($key) eq 'ARRAY') {
 5967:       $result.=&arrayref2str($key).'=';
 5968:     } elsif (ref($key) eq 'HASH') {
 5969:       $result.=&hashref2str($key).'=';
 5970:     } elsif (ref($key)) {
 5971:       $result.='=';
 5972:       #print("Got a ref of ".(ref($key))." skipping.");
 5973:     } else {
 5974: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5975:     }
 5976: 
 5977:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5978:       $result.=&arrayref2str($hashref->{$key}).'&';
 5979:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5980:       $result.=&hashref2str($hashref->{$key}).'&';
 5981:     } elsif(ref($hashref->{$key})) {
 5982:        $result.='&';
 5983:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5984:     } else {
 5985:       $result.=&escape($hashref->{$key}).'&';
 5986:     }
 5987:   }
 5988:   $result=~s/\&$//;
 5989:   $result .= '__END_HASH_REF__';
 5990:   return $result;
 5991: }
 5992: 
 5993: sub str2hash {
 5994:     my ($string)=@_;
 5995:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5996:     return %$hash;
 5997: }
 5998: 
 5999: sub str2hashref {
 6000:   my ($string) = @_;
 6001: 
 6002:   my %hash;
 6003: 
 6004:   if($string !~ /^__HASH_REF__/) {
 6005:       if (! ($string eq '' || !defined($string))) {
 6006: 	  $hash{'error'}='Not hash reference';
 6007:       }
 6008:       return (\%hash, $string);
 6009:   }
 6010: 
 6011:   $string =~ s/^__HASH_REF__//;
 6012: 
 6013:   while($string !~ /^__END_HASH_REF__/) {
 6014:       #key
 6015:       my $key='';
 6016:       if($string =~ /^__HASH_REF__/) {
 6017:           ($key, $string)=&str2hashref($string);
 6018:           if(defined($key->{'error'})) {
 6019:               $hash{'error'}='Bad data';
 6020:               return (\%hash, $string);
 6021:           }
 6022:       } elsif($string =~ /^__ARRAY_REF__/) {
 6023:           ($key, $string)=&str2arrayref($string);
 6024:           if($key->[0] eq 'Array reference error') {
 6025:               $hash{'error'}='Bad data';
 6026:               return (\%hash, $string);
 6027:           }
 6028:       } else {
 6029:           $string =~ s/^(.*?)=//;
 6030: 	  $key=&unescape($1);
 6031:       }
 6032:       $string =~ s/^=//;
 6033: 
 6034:       #value
 6035:       my $value='';
 6036:       if($string =~ /^__HASH_REF__/) {
 6037:           ($value, $string)=&str2hashref($string);
 6038:           if(defined($value->{'error'})) {
 6039:               $hash{'error'}='Bad data';
 6040:               return (\%hash, $string);
 6041:           }
 6042:       } elsif($string =~ /^__ARRAY_REF__/) {
 6043:           ($value, $string)=&str2arrayref($string);
 6044:           if($value->[0] eq 'Array reference error') {
 6045:               $hash{'error'}='Bad data';
 6046:               return (\%hash, $string);
 6047:           }
 6048:       } else {
 6049: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6050:       }
 6051:       $string =~ s/^&//;
 6052: 
 6053:       $hash{$key}=$value;
 6054:   }
 6055: 
 6056:   $string =~ s/^__END_HASH_REF__//;
 6057: 
 6058:   return (\%hash, $string);
 6059: }
 6060: 
 6061: sub str2array {
 6062:     my ($string)=@_;
 6063:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6064:     return @$array;
 6065: }
 6066: 
 6067: sub str2arrayref {
 6068:   my ($string) = @_;
 6069:   my @array;
 6070: 
 6071:   if($string !~ /^__ARRAY_REF__/) {
 6072:       if (! ($string eq '' || !defined($string))) {
 6073: 	  $array[0]='Array reference error';
 6074:       }
 6075:       return (\@array, $string);
 6076:   }
 6077: 
 6078:   $string =~ s/^__ARRAY_REF__//;
 6079: 
 6080:   while($string !~ /^__END_ARRAY_REF__/) {
 6081:       my $value='';
 6082:       if($string =~ /^__HASH_REF__/) {
 6083:           ($value, $string)=&str2hashref($string);
 6084:           if(defined($value->{'error'})) {
 6085:               $array[0] ='Array reference error';
 6086:               return (\@array, $string);
 6087:           }
 6088:       } elsif($string =~ /^__ARRAY_REF__/) {
 6089:           ($value, $string)=&str2arrayref($string);
 6090:           if($value->[0] eq 'Array reference error') {
 6091:               $array[0] ='Array reference error';
 6092:               return (\@array, $string);
 6093:           }
 6094:       } else {
 6095: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6096:       }
 6097:       $string =~ s/^&//;
 6098: 
 6099:       push(@array, $value);
 6100:   }
 6101: 
 6102:   $string =~ s/^__END_ARRAY_REF__//;
 6103: 
 6104:   return (\@array, $string);
 6105: }
 6106: 
 6107: # -------------------------------------------------------------------Temp Store
 6108: 
 6109: sub tmpreset {
 6110:   my ($symb,$namespace,$domain,$stuname) = @_;
 6111:   if (!$symb) {
 6112:     $symb=&symbread();
 6113:     if (!$symb) { $symb= $env{'request.url'}; }
 6114:   }
 6115:   $symb=escape($symb);
 6116: 
 6117:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6118:   $namespace=~s/\//\_/g;
 6119:   $namespace=~s/\W//g;
 6120: 
 6121:   if (!$domain) { $domain=$env{'user.domain'}; }
 6122:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6123:   if ($domain eq 'public' && $stuname eq 'public') {
 6124:       $stuname=&get_requestor_ip();
 6125:   }
 6126:   my $path=LONCAPA::tempdir();
 6127:   my %hash;
 6128:   if (tie(%hash,'GDBM_File',
 6129: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6130: 	  &GDBM_WRCREAT(),0640)) {
 6131:     foreach my $key (keys(%hash)) {
 6132:       if ($key=~ /:$symb/) {
 6133: 	delete($hash{$key});
 6134:       }
 6135:     }
 6136:   }
 6137: }
 6138: 
 6139: sub tmpstore {
 6140:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6141: 
 6142:   if (!$symb) {
 6143:     $symb=&symbread();
 6144:     if (!$symb) { $symb= $env{'request.url'}; }
 6145:   }
 6146:   $symb=escape($symb);
 6147: 
 6148:   if (!$namespace) {
 6149:     # I don't think we would ever want to store this for a course.
 6150:     # it seems this will only be used if we don't have a course.
 6151:     #$namespace=$env{'request.course.id'};
 6152:     #if (!$namespace) {
 6153:       $namespace=$env{'request.state'};
 6154:     #}
 6155:   }
 6156:   $namespace=~s/\//\_/g;
 6157:   $namespace=~s/\W//g;
 6158:   if (!$domain) { $domain=$env{'user.domain'}; }
 6159:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6160:   if ($domain eq 'public' && $stuname eq 'public') {
 6161:       $stuname=&get_requestor_ip();
 6162:   }
 6163:   my $now=time;
 6164:   my %hash;
 6165:   my $path=LONCAPA::tempdir();
 6166:   if (tie(%hash,'GDBM_File',
 6167: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6168: 	  &GDBM_WRCREAT(),0640)) {
 6169:     $hash{"version:$symb"}++;
 6170:     my $version=$hash{"version:$symb"};
 6171:     my $allkeys=''; 
 6172:     foreach my $key (keys(%$storehash)) {
 6173:       $allkeys.=$key.':';
 6174:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6175:     }
 6176:     $hash{"$version:$symb:timestamp"}=$now;
 6177:     $allkeys.='timestamp';
 6178:     $hash{"$version:keys:$symb"}=$allkeys;
 6179:     if (untie(%hash)) {
 6180:       return 'ok';
 6181:     } else {
 6182:       return "error:$!";
 6183:     }
 6184:   } else {
 6185:     return "error:$!";
 6186:   }
 6187: }
 6188: 
 6189: # -----------------------------------------------------------------Temp Restore
 6190: 
 6191: sub tmprestore {
 6192:   my ($symb,$namespace,$domain,$stuname) = @_;
 6193: 
 6194:   if (!$symb) {
 6195:     $symb=&symbread();
 6196:     if (!$symb) { $symb= $env{'request.url'}; }
 6197:   }
 6198:   $symb=escape($symb);
 6199: 
 6200:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6201: 
 6202:   if (!$domain) { $domain=$env{'user.domain'}; }
 6203:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6204:   if ($domain eq 'public' && $stuname eq 'public') {
 6205:       $stuname=&get_requestor_ip();
 6206:   }
 6207:   my %returnhash;
 6208:   $namespace=~s/\//\_/g;
 6209:   $namespace=~s/\W//g;
 6210:   my %hash;
 6211:   my $path=LONCAPA::tempdir();
 6212:   if (tie(%hash,'GDBM_File',
 6213: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6214: 	  &GDBM_READER(),0640)) {
 6215:     my $version=$hash{"version:$symb"};
 6216:     $returnhash{'version'}=$version;
 6217:     my $scope;
 6218:     for ($scope=1;$scope<=$version;$scope++) {
 6219:       my $vkeys=$hash{"$scope:keys:$symb"};
 6220:       my @keys=split(/:/,$vkeys);
 6221:       my $key;
 6222:       $returnhash{"$scope:keys"}=$vkeys;
 6223:       foreach $key (@keys) {
 6224: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6225: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6226:       }
 6227:     }
 6228:     if (!(untie(%hash))) {
 6229:       return "error:$!";
 6230:     }
 6231:   } else {
 6232:     return "error:$!";
 6233:   }
 6234:   return %returnhash;
 6235: }
 6236: 
 6237: # ----------------------------------------------------------------------- Store
 6238: 
 6239: sub store {
 6240:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6241:     my $home='';
 6242: 
 6243:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6244: 
 6245:     $symb=&symbclean($symb);
 6246:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6247: 
 6248:     if (!$domain) { $domain=$env{'user.domain'}; }
 6249:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6250: 
 6251:     &devalidate($symb,$stuname,$domain);
 6252: 
 6253:     $symb=escape($symb);
 6254:     if (!$namespace) { 
 6255:        unless ($namespace=$env{'request.course.id'}) { 
 6256:           return ''; 
 6257:        } 
 6258:     }
 6259:     if (!$home) { $home=$env{'user.home'}; }
 6260: 
 6261:     $$storehash{'ip'}=&get_requestor_ip();
 6262:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6263: 
 6264:     my $namevalue='';
 6265:     foreach my $key (keys(%$storehash)) {
 6266:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6267:     }
 6268:     $namevalue=~s/\&$//;
 6269:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6270:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6271: }
 6272: 
 6273: # -------------------------------------------------------------- Critical Store
 6274: 
 6275: sub cstore {
 6276:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6277:     my $home='';
 6278: 
 6279:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6280: 
 6281:     $symb=&symbclean($symb);
 6282:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6283: 
 6284:     if (!$domain) { $domain=$env{'user.domain'}; }
 6285:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6286: 
 6287:     &devalidate($symb,$stuname,$domain);
 6288: 
 6289:     $symb=escape($symb);
 6290:     if (!$namespace) { 
 6291:        unless ($namespace=$env{'request.course.id'}) { 
 6292:           return ''; 
 6293:        } 
 6294:     }
 6295:     if (!$home) { $home=$env{'user.home'}; }
 6296: 
 6297:     $$storehash{'ip'}=&get_requestor_ip();
 6298:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6299: 
 6300:     my $namevalue='';
 6301:     foreach my $key (keys(%$storehash)) {
 6302:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6303:     }
 6304:     $namevalue=~s/\&$//;
 6305:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6306:     return critical
 6307:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6308: }
 6309: 
 6310: # --------------------------------------------------------------------- Restore
 6311: 
 6312: sub restore {
 6313:     my ($symb,$namespace,$domain,$stuname) = @_;
 6314:     my $home='';
 6315: 
 6316:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6317: 
 6318:     if (!$symb) {
 6319:         return if ($namespace eq 'courserequests');
 6320:         unless ($symb=escape(&symbread())) { return ''; }
 6321:     } else {
 6322:         unless ($namespace eq 'courserequests') {
 6323:             $symb=&escape(&symbclean($symb));
 6324:         }
 6325:     }
 6326:     if (!$namespace) { 
 6327:        unless ($namespace=$env{'request.course.id'}) { 
 6328:           return ''; 
 6329:        } 
 6330:     }
 6331:     if (!$domain) { $domain=$env{'user.domain'}; }
 6332:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6333:     if (!$home) { $home=$env{'user.home'}; }
 6334:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6335: 
 6336:     my %returnhash=();
 6337:     foreach my $line (split(/\&/,$answer)) {
 6338: 	my ($name,$value)=split(/\=/,$line);
 6339:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6340:     }
 6341:     my $version;
 6342:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6343:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6344:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6345:        }
 6346:     }
 6347:     return %returnhash;
 6348: }
 6349: 
 6350: # ---------------------------------------------------------- Course Description
 6351: #
 6352: #  
 6353: 
 6354: sub coursedescription {
 6355:     my ($courseid,$args)=@_;
 6356:     $courseid=~s/^\///;
 6357:     $courseid=~s/\_/\//g;
 6358:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6359:     my $chome=&homeserver($cnum,$cdomain);
 6360:     my $normalid=$cdomain.'_'.$cnum;
 6361:     # need to always cache even if we get errors otherwise we keep 
 6362:     # trying and trying and trying to get the course description.
 6363:     my %envhash=();
 6364:     my %returnhash=();
 6365:     
 6366:     my $expiretime=600;
 6367:     if ($env{'request.course.id'} eq $normalid) {
 6368: 	$expiretime=120;
 6369:     }
 6370: 
 6371:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6372:     if (!$args->{'freshen_cache'}
 6373: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6374: 	foreach my $key (keys(%env)) {
 6375: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6376: 	    my ($setting) = $1;
 6377: 	    $returnhash{$setting} = $env{$key};
 6378: 	}
 6379: 	return %returnhash;
 6380:     }
 6381: 
 6382:     # get the data again
 6383: 
 6384:     if (!$args->{'one_time'}) {
 6385: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6386:     }
 6387: 
 6388:     if ($chome ne 'no_host') {
 6389:        %returnhash=&dump('environment',$cdomain,$cnum);
 6390:        if (!exists($returnhash{'con_lost'})) {
 6391: 	   my $username = $env{'user.name'}; # Defult username
 6392: 	   if(defined $args->{'user'}) {
 6393: 	       $username = $args->{'user'};
 6394: 	   }
 6395:            $returnhash{'home'}= $chome;
 6396: 	   $returnhash{'domain'} = $cdomain;
 6397: 	   $returnhash{'num'} = $cnum;
 6398:            if (!defined($returnhash{'type'})) {
 6399:                $returnhash{'type'} = 'Course';
 6400:            }
 6401:            while (my ($name,$value) = each %returnhash) {
 6402:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6403:            }
 6404:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6405:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6406: 	       $username.'_'.$cdomain.'_'.$cnum;
 6407:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6408:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6409:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6410:        }
 6411:     }
 6412:     if (!$args->{'one_time'}) {
 6413: 	&appenv(\%envhash);
 6414:     }
 6415:     return %returnhash;
 6416: }
 6417: 
 6418: sub update_released_required {
 6419:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6420:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6421:         $cid = $env{'request.course.id'};
 6422:         $cdom = $env{'course.'.$cid.'.domain'};
 6423:         $cnum = $env{'course.'.$cid.'.num'};
 6424:         $chome = $env{'course.'.$cid.'.home'};
 6425:     }
 6426:     if ($needsrelease) {
 6427:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6428:         my $needsupdate;
 6429:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6430:             $needsupdate = 1;
 6431:         } else {
 6432:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6433:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6434:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6435:                 $needsupdate = 1;
 6436:             }
 6437:         }
 6438:         if ($needsupdate) {
 6439:             my %needshash = (
 6440:                              'internal.releaserequired' => $needsrelease,
 6441:                             );
 6442:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6443:             if ($putresult eq 'ok') {
 6444:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6445:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6446:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6447:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6448:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6449:                 }
 6450:             }
 6451:         }
 6452:     }
 6453:     return;
 6454: }
 6455: 
 6456: # -------------------------------------------------See if a user is privileged
 6457: 
 6458: sub privileged {
 6459:     my ($username,$domain,$possdomains,$possroles)=@_;
 6460:     my $now = time;
 6461:     my $roles;
 6462:     if (ref($possroles) eq 'ARRAY') {
 6463:         $roles = $possroles; 
 6464:     } else {
 6465:         $roles = ['dc','su'];
 6466:     }
 6467:     if (ref($possdomains) eq 'ARRAY') {
 6468:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6469:         foreach my $dom (@{$possdomains}) {
 6470:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6471:                 (ref($privileged{$dom}) eq 'HASH')) {
 6472:                 foreach my $role (@{$roles}) {
 6473:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6474:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6475:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6476:                             return 1 unless (($end && $end < $now) ||
 6477:                                              ($start && $start > $now));
 6478:                         }
 6479:                     }
 6480:                 }
 6481:             }
 6482:         }
 6483:     } else {
 6484:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6485:         my $now = time;
 6486: 
 6487:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6488:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6489:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6490:                 return 1 unless ($tend && $tend < $now) 
 6491:                         or ($tstart && $tstart > $now);
 6492:             }
 6493:         }
 6494:     }
 6495:     return 0;
 6496: }
 6497: 
 6498: sub privileged_by_domain {
 6499:     my ($domains,$roles) = @_;
 6500:     my %privileged = ();
 6501:     my $cachetime = 60*60*24;
 6502:     my $now = time;
 6503:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6504:         return %privileged;
 6505:     }
 6506:     foreach my $dom (@{$domains}) {
 6507:         next if (ref($privileged{$dom}) eq 'HASH');
 6508:         my $needroles;
 6509:         foreach my $role (@{$roles}) {
 6510:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6511:             if (defined($cached)) {
 6512:                 if (ref($result) eq 'HASH') {
 6513:                     $privileged{$dom}{$role} = $result;
 6514:                 }
 6515:             } else {
 6516:                 $needroles = 1;
 6517:             }
 6518:         }
 6519:         if ($needroles) {
 6520:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6521:             $privileged{$dom} = {};
 6522:             foreach my $server (keys(%dompersonnel)) {
 6523:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6524:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6525:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6526:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6527:                         next if ($end && $end < $now);
 6528:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6529:                             $dompersonnel{$server}{$item};
 6530:                     }
 6531:                 }
 6532:             }
 6533:             if (ref($privileged{$dom}) eq 'HASH') {
 6534:                 foreach my $role (@{$roles}) {
 6535:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6536:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6537:                     } else {
 6538:                         my %hash = ();
 6539:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6540:                     }
 6541:                 }
 6542:             }
 6543:         }
 6544:     }
 6545:     return %privileged;
 6546: }
 6547: 
 6548: # -------------------------------------------------------- Get user privileges
 6549: 
 6550: sub rolesinit {
 6551:     my ($domain, $username) = @_;
 6552:     my %userroles = ('user.login.time' => time);
 6553:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6554: 
 6555:     # firstaccess and timerinterval are related to timed maps/resources. 
 6556:     # also, blocking can be triggered by an activating timer
 6557:     # it's saved in the user's %env.
 6558:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6559:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6560:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6561:         %timerintchk, %timerintenv);
 6562: 
 6563:     foreach my $key (keys(%firstaccess)) {
 6564:         my ($cid, $rest) = split(/\0/, $key);
 6565:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6566:     }
 6567: 
 6568:     foreach my $key (keys(%timerinterval)) {
 6569:         my ($cid,$rest) = split(/\0/,$key);
 6570:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6571:     }
 6572: 
 6573:     my %allroles=();
 6574:     my %allgroups=();
 6575: 
 6576:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6577:         my $role = $rolesdump{$area};
 6578:         $area =~ s/\_\w\w$//;
 6579: 
 6580:         my ($trole, $tend, $tstart, $group_privs);
 6581: 
 6582:         if ($role =~ /^cr/) {
 6583:         # Custom role, defined by a user 
 6584:         # e.g., user.role.cr/msu/smith/mynewrole
 6585:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6586:                 $trole = $1;
 6587:                 ($tend, $tstart) = split('_', $2);
 6588:             } else {
 6589:                 $trole = $role;
 6590:             }
 6591:         } elsif ($role =~ m|^gr/|) {
 6592:         # Role of member in a group, defined within a course/community
 6593:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6594:             ($trole, $tend, $tstart) = split(/_/, $role);
 6595:             next if $tstart eq '-1';
 6596:             ($trole, $group_privs) = split(/\//, $trole);
 6597:             $group_privs = &unescape($group_privs);
 6598:         } else {
 6599:         # Just a normal role, defined in roles.tab
 6600:             ($trole, $tend, $tstart) = split(/_/,$role);
 6601:         }
 6602: 
 6603:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6604:                  $username);
 6605:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6606: 
 6607:         # role expired or not available yet?
 6608:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6609:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6610: 
 6611:         next if $area eq '' or $trole eq '';
 6612: 
 6613:         my $spec = "$trole.$area";
 6614:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6615: 
 6616:         if ($trole =~ /^cr\//) {
 6617:         # Custom role, defined by a user
 6618:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6619:         } elsif ($trole eq 'gr') {
 6620:         # Role of a member in a group, defined within a course/community
 6621:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6622:             next;
 6623:         } else {
 6624:         # Normal role, defined in roles.tab
 6625:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6626:         }
 6627: 
 6628:         my $cid = $tdomain.'_'.$trest;
 6629:         unless ($firstaccchk{$cid}) {
 6630:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6631:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6632:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6633:                         $coursetimerstarts{$cid}{$item}; 
 6634:                 }
 6635:             }
 6636:             $firstaccchk{$cid} = 1;
 6637:         }
 6638:         unless ($timerintchk{$cid}) {
 6639:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6640:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6641:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6642:                        $coursetimerintervals{$cid}{$item};
 6643:                 }
 6644:             }
 6645:             $timerintchk{$cid} = 1;
 6646:         }
 6647:     }
 6648: 
 6649:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6650:                                                           \%allroles, \%allgroups);
 6651:     $env{'user.adv'} = $userroles{'user.adv'};
 6652:     $env{'user.rar'} = $userroles{'user.rar'};
 6653: 
 6654:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6655: }
 6656: 
 6657: sub set_arearole {
 6658:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6659:     unless ($nolog) {
 6660: # log the associated role with the area
 6661:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6662:     }
 6663:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6664: }
 6665: 
 6666: sub custom_roleprivs {
 6667:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6668:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6669:     my $homsvr = &homeserver($rauthor,$rdomain);
 6670:     if (&hostname($homsvr) ne '') {
 6671:         my ($rdummy,$roledef)=
 6672:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6673:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6674:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6675:             if (defined($syspriv)) {
 6676:                 if ($trest =~ /^$match_community$/) {
 6677:                     $syspriv =~ s/bre\&S//; 
 6678:                 }
 6679:                 $$allroles{'cm./'}.=':'.$syspriv;
 6680:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6681:             }
 6682:             if ($tdomain ne '') {
 6683:                 if (defined($dompriv)) {
 6684:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6685:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6686:                 }
 6687:                 if (($trest ne '') && (defined($coursepriv))) {
 6688:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6689:                         my $rolename = $1;
 6690:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6691:                     }
 6692:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6693:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6694:                 }
 6695:             }
 6696:         }
 6697:     }
 6698: }
 6699: 
 6700: sub course_adhocrole_privs {
 6701:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6702:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6703:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6704:         my (%currprivs,%storeprivs);
 6705:         foreach my $item (split(/:/,$coursepriv)) {
 6706:             my ($priv,$restrict) = split(/\&/,$item);
 6707:             $currprivs{$priv} = $restrict;
 6708:         }
 6709:         my (%possadd,%possremove,%full);
 6710:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6711:             my ($priv,$restrict)=split(/\&/,$item);
 6712:             $full{$priv} = $restrict;
 6713:         }
 6714:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6715:              next if ($item eq '');
 6716:              my ($rule,$rest) = split(/=/,$item);
 6717:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6718:              foreach my $priv (split(/:/,$rest)) {
 6719:                  if ($priv ne '') {
 6720:                      if ($rule eq 'off') {
 6721:                          $possremove{$priv} = 1;
 6722:                      } else {
 6723:                          $possadd{$priv} = 1;
 6724:                      }
 6725:                  }
 6726:              }
 6727:          }
 6728:          foreach my $priv (sort(keys(%full))) {
 6729:              if (exists($currprivs{$priv})) {
 6730:                  unless (exists($possremove{$priv})) {
 6731:                      $storeprivs{$priv} = $currprivs{$priv};
 6732:                  }
 6733:              } elsif (exists($possadd{$priv})) {
 6734:                  $storeprivs{$priv} = $full{$priv};
 6735:              }
 6736:          }
 6737:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6738:      }
 6739:      return $coursepriv;
 6740: }
 6741: 
 6742: sub group_roleprivs {
 6743:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6744:     my $access = 1;
 6745:     my $now = time;
 6746:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6747:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6748:     if ($access) {
 6749:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6750:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6751:     }
 6752: }
 6753: 
 6754: sub standard_roleprivs {
 6755:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6756:     if (defined($pr{$trole.':s'})) {
 6757:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6758:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6759:     }
 6760:     if ($tdomain ne '') {
 6761:         if (defined($pr{$trole.':d'})) {
 6762:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6763:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6764:         }
 6765:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6766:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6767:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6768:         }
 6769:     }
 6770: }
 6771: 
 6772: sub set_userprivs {
 6773:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6774:     my $author=0;
 6775:     my $adv=0;
 6776:     my $rar=0;
 6777:     my %grouproles = ();
 6778:     if (keys(%{$allgroups}) > 0) {
 6779:         my @groupkeys; 
 6780:         foreach my $role (keys(%{$allroles})) {
 6781:             push(@groupkeys,$role);
 6782:         }
 6783:         if (ref($groups_roles) eq 'HASH') {
 6784:             foreach my $key (keys(%{$groups_roles})) {
 6785:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6786:                     push(@groupkeys,$key);
 6787:                 }
 6788:             }
 6789:         }
 6790:         if (@groupkeys > 0) {
 6791:             foreach my $role (@groupkeys) {
 6792:                 my ($trole,$area,$sec,$extendedarea);
 6793:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6794:                     $trole = $1;
 6795:                     $area = $2;
 6796:                     $sec = $3;
 6797:                     $extendedarea = $area.$sec;
 6798:                     if (exists($$allgroups{$area})) {
 6799:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6800:                             my $spec = $trole.'.'.$extendedarea;
 6801:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6802:                                                 $$allgroups{$area}{$group};
 6803:                         }
 6804:                     }
 6805:                 }
 6806:             }
 6807:         }
 6808:     }
 6809:     foreach my $group (keys(%grouproles)) {
 6810:         $$allroles{$group} = $grouproles{$group};
 6811:     }
 6812:     foreach my $role (keys(%{$allroles})) {
 6813:         my %thesepriv;
 6814:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6815:         foreach my $item (split(/:/,$$allroles{$role})) {
 6816:             if ($item ne '') {
 6817:                 my ($privilege,$restrictions)=split(/&/,$item);
 6818:                 if ($restrictions eq '') {
 6819:                     $thesepriv{$privilege}='F';
 6820:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6821:                     $thesepriv{$privilege}.=$restrictions;
 6822:                 }
 6823:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6824:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6825:             }
 6826:         }
 6827:         my $thesestr='';
 6828:         foreach my $priv (sort(keys(%thesepriv))) {
 6829: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6830: 	}
 6831:         $userroles->{'user.priv.'.$role} = $thesestr;
 6832:     }
 6833:     return ($author,$adv,$rar);
 6834: }
 6835: 
 6836: sub role_status {
 6837:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6838:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6839:         my ($one,$two) = split(m{\./},$rolekey,2);
 6840:         (undef,undef,$$role) = split(/\./,$one,3);
 6841:         unless (!defined($$role) || $$role eq '') {
 6842:             $$where = '/'.$two;
 6843:             $$trolecode=$$role.'.'.$$where;
 6844:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6845:             $$tstatus='is';
 6846:             if ($$tstart && $$tstart>$update) {
 6847:                 $$tstatus='future';
 6848:                 if ($$tstart<$now) {
 6849:                     if ($$tstart && $$tstart>$refresh) {
 6850:                         if (($$where ne '') && ($$role ne '')) {
 6851:                             my (%allroles,%allgroups,$group_privs,
 6852:                                 %groups_roles,@rolecodes);
 6853:                             my %userroles = (
 6854:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6855:                             );
 6856:                             @rolecodes = ('cm'); 
 6857:                             my $spec=$$role.'.'.$$where;
 6858:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6859:                             if ($$role =~ /^cr\//) {
 6860:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6861:                                 push(@rolecodes,'cr');
 6862:                             } elsif ($$role eq 'gr') {
 6863:                                 push(@rolecodes,$$role);
 6864:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6865:                                                     $env{'user.name'});
 6866:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6867:                                 (undef,my $group_privs) = split(/\//,$trole);
 6868:                                 $group_privs = &unescape($group_privs);
 6869:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6870:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6871:                                 &get_groups_roles($tdomain,$trest,
 6872:                                                   \%course_roles,\@rolecodes,
 6873:                                                   \%groups_roles);
 6874:                             } else {
 6875:                                 push(@rolecodes,$$role);
 6876:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6877:                             }
 6878:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6879:                                                                    \%groups_roles);
 6880:                             &appenv(\%userroles,\@rolecodes);
 6881:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6882:                         }
 6883:                     }
 6884:                     $$tstatus = 'is';
 6885:                 }
 6886:             }
 6887:             if ($$tend) {
 6888:                 if ($$tend<$update) {
 6889:                     $$tstatus='expired';
 6890:                 } elsif ($$tend<$now) {
 6891:                     $$tstatus='will_not';
 6892:                 }
 6893:             }
 6894:         }
 6895:     }
 6896: }
 6897: 
 6898: sub get_groups_roles {
 6899:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6900:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6901:                   (ref($rolecodes) eq 'ARRAY') && 
 6902:                   (ref($groups_roles) eq 'HASH')); 
 6903:     if (keys(%{$cdom_courseroles}) > 0) {
 6904:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6905:         if ($cdom ne '' && $cnum ne '') {
 6906:             foreach my $key (keys(%{$cdom_courseroles})) {
 6907:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6908:                     my $crsrole = $1;
 6909:                     my $crssec = $2;
 6910:                     if ($crsrole =~ /^cr/) {
 6911:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6912:                             push(@{$rolecodes},'cr');
 6913:                         }
 6914:                     } else {
 6915:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6916:                             push(@{$rolecodes},$crsrole);
 6917:                         }
 6918:                     }
 6919:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6920:                     if ($crssec ne '') {
 6921:                         $rolekey .= "/$crssec";
 6922:                     }
 6923:                     $rolekey .= './';
 6924:                     $groups_roles->{$rolekey} = $rolecodes;
 6925:                 }
 6926:             }
 6927:         }
 6928:     }
 6929:     return;
 6930: }
 6931: 
 6932: sub delete_env_groupprivs {
 6933:     my ($where,$courseroles,$possroles) = @_;
 6934:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6935:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6936:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6937:         %{$courseroles->{$udom}} =
 6938:             &get_my_roles('','','userroles',['active'],
 6939:                           $possroles,[$udom],1);
 6940:     }
 6941:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6942:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6943:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6944:             my $area = '/'.$cdom.'/'.$cnum;
 6945:             my $privkey = "user.priv.$crsrole.$area";
 6946:             if ($crssec ne '') {
 6947:                 $privkey .= '/'.$crssec;
 6948:             }
 6949:             $privkey .= ".$area/$group";
 6950:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6951:         }
 6952:     }
 6953:     return;
 6954: }
 6955: 
 6956: sub check_adhoc_privs {
 6957:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6958:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6959:     if ($sec) {
 6960:         $cckey .= '/'.$sec;
 6961:     } 
 6962:     my $setprivs;
 6963:     if ($env{$cckey}) {
 6964:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6965:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6966:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6967:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6968:             $setprivs = 1;
 6969:         }
 6970:     } else {
 6971:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6972:         $setprivs = 1;
 6973:     }
 6974:     return $setprivs;
 6975: }
 6976: 
 6977: sub set_adhoc_privileges {
 6978: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6979:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6980:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6981:     if ($sec ne '') {
 6982:         $area .= '/'.$sec;
 6983:     }
 6984:     my $spec = $role.'.'.$area;
 6985:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6986:                                   $env{'user.name'},1);
 6987:     my %rolehash = ();
 6988:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6989:         my $rolename = $1;
 6990:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6991:         my %domdef = &get_domain_defaults($dcdom);
 6992:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6993:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6994:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6995:             }
 6996:         }
 6997:     } else {
 6998:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6999:     }
 7000:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7001:     &appenv(\%userroles,[$role,'cm']);
 7002:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7003:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7004:             ($caller eq 'tiny')) {
 7005:         &appenv( {'request.role'        => $spec,
 7006:                   'request.role.domain' => $dcdom,
 7007:                   'request.course.sec'  => $sec,
 7008:                  }
 7009:                );
 7010:         my $tadv=0;
 7011:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7012:         &appenv({'request.role.adv'    => $tadv});
 7013:     }
 7014: }
 7015: 
 7016: # --------------------------------------------------------------- get interface
 7017: 
 7018: sub get {
 7019:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7020:    my $items='';
 7021:    foreach my $item (@$storearr) {
 7022:        $items.=&escape($item).'&';
 7023:    }
 7024:    $items=~s/\&$//;
 7025:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7026:    if (!$uname) { $uname=$env{'user.name'}; }
 7027:    my $uhome=&homeserver($uname,$udomain);
 7028: 
 7029:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7030:    my @pairs=split(/\&/,$rep);
 7031:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7032:      return @pairs;
 7033:    }
 7034:    my %returnhash=();
 7035:    my $i=0;
 7036:    foreach my $item (@$storearr) {
 7037:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7038:       $i++;
 7039:    }
 7040:    return %returnhash;
 7041: }
 7042: 
 7043: # --------------------------------------------------------------- del interface
 7044: 
 7045: sub del {
 7046:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7047:    my $items='';
 7048:    foreach my $item (@$storearr) {
 7049:        $items.=&escape($item).'&';
 7050:    }
 7051: 
 7052:    $items=~s/\&$//;
 7053:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7054:    if (!$uname) { $uname=$env{'user.name'}; }
 7055:    my $uhome=&homeserver($uname,$udomain);
 7056:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7057: }
 7058: 
 7059: # -------------------------------------------------------------- dump interface
 7060: 
 7061: sub unserialize {
 7062:     my ($rep, $escapedkeys) = @_;
 7063: 
 7064:     return {} if $rep =~ /^error/;
 7065: 
 7066:     my %returnhash=();
 7067: 	foreach my $item (split(/\&/,$rep)) {
 7068: 	    my ($key, $value) = split(/=/, $item, 2);
 7069: 	    $key = unescape($key) unless $escapedkeys;
 7070: 	    next if $key =~ /^error: 2 /;
 7071: 	    $returnhash{$key} = &thaw_unescape($value);
 7072: 	}
 7073:     #return %returnhash;
 7074:     return \%returnhash;
 7075: }        
 7076: 
 7077: # see Lond::dump_with_regexp
 7078: # if $escapedkeys hash keys won't get unescaped.
 7079: sub dump {
 7080:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 7081:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7082:     if (!$uname) { $uname=$env{'user.name'}; }
 7083:     my $uhome=&homeserver($uname,$udomain);
 7084: 
 7085:     if ($regexp) {
 7086:         $regexp=&escape($regexp);
 7087:     } else {
 7088:         $regexp='.';
 7089:     }
 7090:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7091:         # user is hosted on this machine
 7092:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7093:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7094:         return %{unserialize($reply, $escapedkeys)};
 7095:     }
 7096:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7097:     my @pairs=split(/\&/,$rep);
 7098:     my %returnhash=();
 7099:     if (!($rep =~ /^error/ )) {
 7100: 	foreach my $item (@pairs) {
 7101: 	    my ($key,$value)=split(/=/,$item,2);
 7102:         $key = unescape($key) unless $escapedkeys;
 7103:         #$key = &unescape($key);
 7104: 	    next if ($key =~ /^error: 2 /);
 7105: 	    $returnhash{$key}=&thaw_unescape($value);
 7106: 	}
 7107:     }
 7108:     return %returnhash;
 7109: }
 7110: 
 7111: 
 7112: # --------------------------------------------------------- dumpstore interface
 7113: 
 7114: sub dumpstore {
 7115:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7116:    # same as dump but keys must be escaped. They may contain colon separated
 7117:    # lists of values that may themself contain colons (e.g. symbs).
 7118:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7119: }
 7120: 
 7121: # -------------------------------------------------------------- keys interface
 7122: 
 7123: sub getkeys {
 7124:    my ($namespace,$udomain,$uname)=@_;
 7125:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7126:    if (!$uname) { $uname=$env{'user.name'}; }
 7127:    my $uhome=&homeserver($uname,$udomain);
 7128:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7129:    my @keyarray=();
 7130:    foreach my $key (split(/\&/,$rep)) {
 7131:       next if ($key =~ /^error: 2 /);
 7132:       push(@keyarray,&unescape($key));
 7133:    }
 7134:    return @keyarray;
 7135: }
 7136: 
 7137: # --------------------------------------------------------------- currentdump
 7138: sub currentdump {
 7139:    my ($courseid,$sdom,$sname)=@_;
 7140:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7141:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7142:    $sname    = $env{'user.name'}         if (! defined($sname));
 7143:    my $uhome = &homeserver($sname,$sdom);
 7144:    my $rep;
 7145: 
 7146:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7147:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7148:                    $courseid)));
 7149:    } else {
 7150:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7151:    }
 7152: 
 7153:    return if ($rep =~ /^(error:|no_such_host)/);
 7154:    #
 7155:    my %returnhash=();
 7156:    #
 7157:    if ($rep eq 'unknown_cmd') {
 7158:        # an old lond will not know currentdump
 7159:        # Do a dump and make it look like a currentdump
 7160:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7161:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7162:        my %hash = @tmp;
 7163:        @tmp=();
 7164:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7165:    } else {
 7166:        my @pairs=split(/\&/,$rep);
 7167:        foreach my $pair (@pairs) {
 7168:            my ($key,$value)=split(/=/,$pair,2);
 7169:            my ($symb,$param) = split(/:/,$key);
 7170:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7171:                                                         &thaw_unescape($value);
 7172:        }
 7173:    }
 7174:    return %returnhash;
 7175: }
 7176: 
 7177: sub convert_dump_to_currentdump{
 7178:     my %hash = %{shift()};
 7179:     my %returnhash;
 7180:     # Code ripped from lond, essentially.  The only difference
 7181:     # here is the unescaping done by lonnet::dump().  Conceivably
 7182:     # we might run in to problems with parameter names =~ /^v\./
 7183:     while (my ($key,$value) = each(%hash)) {
 7184:         my ($v,$symb,$param) = split(/:/,$key);
 7185: 	$symb  = &unescape($symb);
 7186: 	$param = &unescape($param);
 7187:         next if ($v eq 'version' || $symb eq 'keys');
 7188:         next if (exists($returnhash{$symb}) &&
 7189:                  exists($returnhash{$symb}->{$param}) &&
 7190:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7191:         $returnhash{$symb}->{$param}=$value;
 7192:         $returnhash{$symb}->{'v.'.$param}=$v;
 7193:     }
 7194:     #
 7195:     # Remove all of the keys in the hashes which keep track of
 7196:     # the version of the parameter.
 7197:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7198:         # use a foreach because we are going to delete from the hash.
 7199:         foreach my $key (keys(%$param_hash)) {
 7200:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7201:         }
 7202:     }
 7203:     return \%returnhash;
 7204: }
 7205: 
 7206: # ------------------------------------------------------ critical inc interface
 7207: 
 7208: sub cinc {
 7209:     return &inc(@_,'critical');
 7210: }
 7211: 
 7212: # --------------------------------------------------------------- inc interface
 7213: 
 7214: sub inc {
 7215:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7216:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7217:     if (!$uname) { $uname=$env{'user.name'}; }
 7218:     my $uhome=&homeserver($uname,$udomain);
 7219:     my $items='';
 7220:     if (! ref($store)) {
 7221:         # got a single value, so use that instead
 7222:         $items = &escape($store).'=&';
 7223:     } elsif (ref($store) eq 'SCALAR') {
 7224:         $items = &escape($$store).'=&';        
 7225:     } elsif (ref($store) eq 'ARRAY') {
 7226:         $items = join('=&',map {&escape($_);} @{$store});
 7227:     } elsif (ref($store) eq 'HASH') {
 7228:         while (my($key,$value) = each(%{$store})) {
 7229:             $items.= &escape($key).'='.&escape($value).'&';
 7230:         }
 7231:     }
 7232:     $items=~s/\&$//;
 7233:     if ($critical) {
 7234: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7235:     } else {
 7236: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7237:     }
 7238: }
 7239: 
 7240: # --------------------------------------------------------------- put interface
 7241: 
 7242: sub put {
 7243:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7244:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7245:    if (!$uname) { $uname=$env{'user.name'}; }
 7246:    my $uhome=&homeserver($uname,$udomain);
 7247:    my $items='';
 7248:    foreach my $item (keys(%$storehash)) {
 7249:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7250:    }
 7251:    $items=~s/\&$//;
 7252:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7253: }
 7254: 
 7255: # ------------------------------------------------------------ newput interface
 7256: 
 7257: sub newput {
 7258:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7259:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7260:    if (!$uname) { $uname=$env{'user.name'}; }
 7261:    my $uhome=&homeserver($uname,$udomain);
 7262:    my $items='';
 7263:    foreach my $key (keys(%$storehash)) {
 7264:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7265:    }
 7266:    $items=~s/\&$//;
 7267:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7268: }
 7269: 
 7270: # ---------------------------------------------------------  putstore interface
 7271: 
 7272: sub putstore {
 7273:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7274:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7275:    if (!$uname) { $uname=$env{'user.name'}; }
 7276:    my $uhome=&homeserver($uname,$udomain);
 7277:    my $items='';
 7278:    foreach my $key (keys(%$storehash)) {
 7279:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7280:    }
 7281:    $items=~s/\&$//;
 7282:    my $esc_symb=&escape($symb);
 7283:    my $esc_v=&escape($version);
 7284:    my $reply =
 7285:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7286: 	      $uhome);
 7287:    if (($tolog) && ($reply eq 'ok')) {
 7288:        my $namevalue='';
 7289:        foreach my $key (keys(%{$storehash})) {
 7290:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7291:        }
 7292:        my $ip = &get_requestor_ip();
 7293:        $namevalue .= 'ip='.&escape($ip).
 7294:                      '&host='.&escape($perlvar{'lonHostID'}).
 7295:                      '&version='.$esc_v.
 7296:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7297:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7298:    }
 7299:    if ($reply eq 'unknown_cmd') {
 7300:        # gfall back to way things use to be done
 7301:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7302: 			    $uname);
 7303:    }
 7304:    return $reply;
 7305: }
 7306: 
 7307: sub old_putstore {
 7308:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7309:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7310:     if (!$uname) { $uname=$env{'user.name'}; }
 7311:     my $uhome=&homeserver($uname,$udomain);
 7312:     my %newstorehash;
 7313:     foreach my $item (keys(%$storehash)) {
 7314: 	my $key = $version.':'.&escape($symb).':'.$item;
 7315: 	$newstorehash{$key} = $storehash->{$item};
 7316:     }
 7317:     my $items='';
 7318:     my %allitems = ();
 7319:     foreach my $item (keys(%newstorehash)) {
 7320: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7321: 	    my $key = $1.':keys:'.$2;
 7322: 	    $allitems{$key} .= $3.':';
 7323: 	}
 7324: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7325:     }
 7326:     foreach my $item (keys(%allitems)) {
 7327: 	$allitems{$item} =~ s/\:$//;
 7328: 	$items.= $item.'='.$allitems{$item}.'&';
 7329:     }
 7330:     $items=~s/\&$//;
 7331:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7332: }
 7333: 
 7334: # ------------------------------------------------------ critical put interface
 7335: 
 7336: sub cput {
 7337:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7338:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7339:    if (!$uname) { $uname=$env{'user.name'}; }
 7340:    my $uhome=&homeserver($uname,$udomain);
 7341:    my $items='';
 7342:    foreach my $item (keys(%$storehash)) {
 7343:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7344:    }
 7345:    $items=~s/\&$//;
 7346:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7347: }
 7348: 
 7349: # -------------------------------------------------------------- eget interface
 7350: 
 7351: sub eget {
 7352:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7353:    my $items='';
 7354:    foreach my $item (@$storearr) {
 7355:        $items.=&escape($item).'&';
 7356:    }
 7357:    $items=~s/\&$//;
 7358:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7359:    if (!$uname) { $uname=$env{'user.name'}; }
 7360:    my $uhome=&homeserver($uname,$udomain);
 7361:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7362:    my @pairs=split(/\&/,$rep);
 7363:    my %returnhash=();
 7364:    my $i=0;
 7365:    foreach my $item (@$storearr) {
 7366:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7367:       $i++;
 7368:    }
 7369:    return %returnhash;
 7370: }
 7371: 
 7372: # ------------------------------------------------------------ tmpput interface
 7373: sub tmpput {
 7374:     my ($storehash,$server,$context)=@_;
 7375:     my $items='';
 7376:     foreach my $item (keys(%$storehash)) {
 7377: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7378:     }
 7379:     $items=~s/\&$//;
 7380:     if (defined($context)) {
 7381:         $items .= ':'.&escape($context);
 7382:     }
 7383:     return &reply("tmpput:$items",$server);
 7384: }
 7385: 
 7386: # ------------------------------------------------------------ tmpget interface
 7387: sub tmpget {
 7388:     my ($token,$server)=@_;
 7389:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7390:     my $rep=&reply("tmpget:$token",$server);
 7391:     my %returnhash;
 7392:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7393:         return %returnhash;
 7394:     }
 7395:     foreach my $item (split(/\&/,$rep)) {
 7396: 	my ($key,$value)=split(/=/,$item);
 7397: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7398:     }
 7399:     return %returnhash;
 7400: }
 7401: 
 7402: # ------------------------------------------------------------ tmpdel interface
 7403: sub tmpdel {
 7404:     my ($token,$server)=@_;
 7405:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7406:     return &reply("tmpdel:$token",$server);
 7407: }
 7408: 
 7409: # ------------------------------------------------------------ get_timebased_id 
 7410: 
 7411: sub get_timebased_id {
 7412:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7413:         $maxtries) = @_;
 7414:     my ($newid,$error,$dellock);
 7415:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7416:         return ('','ok','invalid call to get suffix');
 7417:     }
 7418: 
 7419: # set defaults for any optional args for which values were not supplied
 7420:     if ($who eq '') {
 7421:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7422:     }
 7423:     if (!$locktries) {
 7424:         $locktries = 3;
 7425:     }
 7426:     if (!$maxtries) {
 7427:         $maxtries = 10;
 7428:     }
 7429:     
 7430:     if (($cdom eq '') || ($cnum eq '')) {
 7431:         if ($env{'request.course.id'}) {
 7432:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7433:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7434:         }
 7435:         if (($cdom eq '') || ($cnum eq '')) {
 7436:             return ('','ok','call to get suffix not in course context');
 7437:         }
 7438:     }
 7439: 
 7440: # construct locking item
 7441:     my $lockhash = {
 7442:                       $prefix."\0".'locked_'.$keyid => $who,
 7443:                    };
 7444:     my $tries = 0;
 7445: 
 7446: # attempt to get lock on nohist_$namespace file
 7447:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7448:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7449:         $tries ++;
 7450:         sleep 1;
 7451:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7452:     }
 7453: 
 7454: # attempt to get unique identifier, based on current timestamp
 7455:     if ($gotlock eq 'ok') {
 7456:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7457:         my $id = time;
 7458:         $newid = $id;
 7459:         if ($idtype eq 'addcode') {
 7460:             $newid .= &sixnum_code();
 7461:         }
 7462:         my $idtries = 0;
 7463:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7464:             if ($idtype eq 'concat') {
 7465:                 $newid = $id.$idtries;
 7466:             } elsif ($idtype eq 'addcode') {
 7467:                 $newid = $newid.&sixnum_code();
 7468:             } else {
 7469:                 $newid ++;
 7470:             }
 7471:             $idtries ++;
 7472:         }
 7473:         if (!exists($inuse{$prefix."\0".$newid})) {
 7474:             my %new_item =  (
 7475:                               $prefix."\0".$newid => $who,
 7476:                             );
 7477:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7478:                                                  $cdom,$cnum);
 7479:             if ($putresult ne 'ok') {
 7480:                 undef($newid);
 7481:                 $error = 'error saving new item: '.$putresult;
 7482:             }
 7483:         } else {
 7484:              undef($newid);
 7485:              $error = ('error: no unique suffix available for the new item ');
 7486:         }
 7487: #  remove lock
 7488:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7489:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7490:     } else {
 7491:         $error = "error: could not obtain lockfile\n";
 7492:         $dellock = 'ok';
 7493:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7494:             $dellock = 'nolock';
 7495:         }
 7496:     }
 7497:     return ($newid,$dellock,$error);
 7498: }
 7499: 
 7500: sub sixnum_code {
 7501:     my $code;
 7502:     for (0..6) {
 7503:         $code .= int( rand(9) );
 7504:     }
 7505:     return $code;
 7506: }
 7507: 
 7508: # -------------------------------------------------- portfolio access checking
 7509: 
 7510: sub portfolio_access {
 7511:     my ($requrl,$clientip) = @_;
 7512:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7513:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7514:     if ($result) {
 7515:         my %setters;
 7516:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7517:             my ($startblock,$endblock) =
 7518:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7519:             if ($startblock && $endblock) {
 7520:                 return 'B';
 7521:             }
 7522:         } else {
 7523:             my ($startblock,$endblock) =
 7524:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7525:             if ($startblock && $endblock) {
 7526:                 return 'B';
 7527:             }
 7528:         }
 7529:     }
 7530:     if ($result eq 'ok') {
 7531:        return 'F';
 7532:     } elsif ($result =~ /^[^:]+:guest_/) {
 7533:        return 'A';
 7534:     }
 7535:     return '';
 7536: }
 7537: 
 7538: sub get_portfolio_access {
 7539:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7540: 
 7541:     if (!ref($access_hash)) {
 7542: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7543: 	my %access_controls = &get_access_controls($current_perms,$group,
 7544: 						   $file_name);
 7545: 	$access_hash = $access_controls{$file_name};
 7546:     }
 7547: 
 7548:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7549:     my $now = time;
 7550:     if (ref($access_hash) eq 'HASH') {
 7551:         foreach my $key (keys(%{$access_hash})) {
 7552:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7553:             if ($start > $now) {
 7554:                 next;
 7555:             }
 7556:             if ($end && $end<$now) {
 7557:                 next;
 7558:             }
 7559:             if ($scope eq 'public') {
 7560:                 $public = $key;
 7561:                 last;
 7562:             } elsif ($scope eq 'guest') {
 7563:                 $guest = $key;
 7564:             } elsif ($scope eq 'domains') {
 7565:                 push(@domains,$key);
 7566:             } elsif ($scope eq 'users') {
 7567:                 push(@users,$key);
 7568:             } elsif ($scope eq 'course') {
 7569:                 push(@courses,$key);
 7570:             } elsif ($scope eq 'group') {
 7571:                 push(@groups,$key);
 7572:             } elsif ($scope eq 'ip') {
 7573:                 push(@ips,$key);
 7574:             }
 7575:         }
 7576:         if ($public) {
 7577:             return 'ok';
 7578:         } elsif (@ips > 0) {
 7579:             my $allowed;
 7580:             foreach my $ipkey (@ips) {
 7581:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7582:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7583:                         $allowed = 1;
 7584:                         last; 
 7585:                     }
 7586:                 }
 7587:             }
 7588:             if ($allowed) {
 7589:                 return 'ok';
 7590:             }
 7591:         }
 7592:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7593:             if ($guest) {
 7594:                 return $guest;
 7595:             }
 7596:         } else {
 7597:             if (@domains > 0) {
 7598:                 foreach my $domkey (@domains) {
 7599:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7600:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7601:                             return 'ok';
 7602:                         }
 7603:                     }
 7604:                 }
 7605:             }
 7606:             if (@users > 0) {
 7607:                 foreach my $userkey (@users) {
 7608:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7609:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7610:                             if (ref($item) eq 'HASH') {
 7611:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7612:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7613:                                     return 'ok';
 7614:                                 }
 7615:                             }
 7616:                         }
 7617:                     } 
 7618:                 }
 7619:             }
 7620:             my %roleshash;
 7621:             my @courses_and_groups = @courses;
 7622:             push(@courses_and_groups,@groups); 
 7623:             if (@courses_and_groups > 0) {
 7624:                 my (%allgroups,%allroles); 
 7625:                 my ($start,$end,$role,$sec,$group);
 7626:                 foreach my $envkey (%env) {
 7627:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7628:                         my $cid = $2.'_'.$3; 
 7629:                         if ($1 eq 'gr') {
 7630:                             $group = $4;
 7631:                             $allgroups{$cid}{$group} = $env{$envkey};
 7632:                         } else {
 7633:                             if ($4 eq '') {
 7634:                                 $sec = 'none';
 7635:                             } else {
 7636:                                 $sec = $4;
 7637:                             }
 7638:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7639:                         }
 7640:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7641:                         my $cid = $2.'_'.$3;
 7642:                         if ($4 eq '') {
 7643:                             $sec = 'none';
 7644:                         } else {
 7645:                             $sec = $4;
 7646:                         }
 7647:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7648:                     }
 7649:                 }
 7650:                 if (keys(%allroles) == 0) {
 7651:                     return;
 7652:                 }
 7653:                 foreach my $key (@courses_and_groups) {
 7654:                     my %content = %{$$access_hash{$key}};
 7655:                     my $cnum = $content{'number'};
 7656:                     my $cdom = $content{'domain'};
 7657:                     my $cid = $cdom.'_'.$cnum;
 7658:                     if (!exists($allroles{$cid})) {
 7659:                         next;
 7660:                     }    
 7661:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7662:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7663:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7664:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7665:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7666:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7667:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7668:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7669:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7670:                                         if (grep/^all$/,@sections) {
 7671:                                             return 'ok';
 7672:                                         } else {
 7673:                                             if (grep/^$sec$/,@sections) {
 7674:                                                 return 'ok';
 7675:                                             }
 7676:                                         }
 7677:                                     }
 7678:                                 }
 7679:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7680:                                     if (grep/^none$/,@groups) {
 7681:                                         return 'ok';
 7682:                                     }
 7683:                                 } else {
 7684:                                     if (grep/^all$/,@groups) {
 7685:                                         return 'ok';
 7686:                                     } 
 7687:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7688:                                         if (grep/^$group$/,@groups) {
 7689:                                             return 'ok';
 7690:                                         }
 7691:                                     }
 7692:                                 } 
 7693:                             }
 7694:                         }
 7695:                     }
 7696:                 }
 7697:             }
 7698:             if ($guest) {
 7699:                 return $guest;
 7700:             }
 7701:         }
 7702:     }
 7703:     return;
 7704: }
 7705: 
 7706: sub course_group_datechecker {
 7707:     my ($dates,$now,$status) = @_;
 7708:     my ($start,$end) = split(/\./,$dates);
 7709:     if (!$start && !$end) {
 7710:         return 'ok';
 7711:     }
 7712:     if (grep/^active$/,@{$status}) {
 7713:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7714:             return 'ok';
 7715:         }
 7716:     }
 7717:     if (grep/^previous$/,@{$status}) {
 7718:         if ($end > $now ) {
 7719:             return 'ok';
 7720:         }
 7721:     }
 7722:     if (grep/^future$/,@{$status}) {
 7723:         if ($start > $now) {
 7724:             return 'ok';
 7725:         }
 7726:     }
 7727:     return; 
 7728: }
 7729: 
 7730: sub parse_portfolio_url {
 7731:     my ($url) = @_;
 7732: 
 7733:     my ($type,$udom,$unum,$group,$file_name);
 7734:     
 7735:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7736: 	$type = 1;
 7737:         $udom = $1;
 7738:         $unum = $2;
 7739:         $file_name = $3;
 7740:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7741: 	$type = 2;
 7742:         $udom = $1;
 7743:         $unum = $2;
 7744:         $group = $3;
 7745:         $file_name = $3.'/'.$4;
 7746:     }
 7747:     if (wantarray) {
 7748: 	return ($type,$udom,$unum,$file_name,$group);
 7749:     }
 7750:     return $type;
 7751: }
 7752: 
 7753: sub is_portfolio_url {
 7754:     my ($url) = @_;
 7755:     return scalar(&parse_portfolio_url($url));
 7756: }
 7757: 
 7758: sub is_portfolio_file {
 7759:     my ($file) = @_;
 7760:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7761:         return 1;
 7762:     }
 7763:     return;
 7764: }
 7765: 
 7766: sub usertools_access {
 7767:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7768:     my ($access,%tools);
 7769:     if ($context eq '') {
 7770:         $context = 'tools';
 7771:     }
 7772:     if ($context eq 'requestcourses') {
 7773:         %tools = (
 7774:                       official   => 1,
 7775:                       unofficial => 1,
 7776:                       community  => 1,
 7777:                       textbook   => 1,
 7778:                       placement  => 1,
 7779:                       lti        => 1,
 7780:                  );
 7781:     } elsif ($context eq 'requestauthor') {
 7782:         %tools = (
 7783:                       requestauthor => 1,
 7784:                  );
 7785:     } else {
 7786:         %tools = (
 7787:                       aboutme   => 1,
 7788:                       blog      => 1,
 7789:                       webdav    => 1,
 7790:                       portfolio => 1,
 7791:                  );
 7792:     }
 7793:     return if (!defined($tools{$tool}));
 7794: 
 7795:     if (($udom eq '') || ($uname eq '')) {
 7796:         $udom = $env{'user.domain'};
 7797:         $uname = $env{'user.name'};
 7798:     }
 7799: 
 7800:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7801:         if ($action ne 'reload') {
 7802:             if ($context eq 'requestcourses') {
 7803:                 return $env{'environment.canrequest.'.$tool};
 7804:             } elsif ($context eq 'requestauthor') {
 7805:                 return $env{'environment.canrequest.author'};
 7806:             } else {
 7807:                 return $env{'environment.availabletools.'.$tool};
 7808:             }
 7809:         }
 7810:     }
 7811: 
 7812:     my ($toolstatus,$inststatus,$envkey);
 7813:     if ($context eq 'requestauthor') {
 7814:         $envkey = $context; 
 7815:     } else {
 7816:         $envkey = $context.'.'.$tool;
 7817:     }
 7818: 
 7819:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7820:          ($action ne 'reload')) {
 7821:         $toolstatus = $env{'environment.'.$envkey};
 7822:         $inststatus = $env{'environment.inststatus'};
 7823:     } else {
 7824:         if (ref($userenvref) eq 'HASH') {
 7825:             $toolstatus = $userenvref->{$envkey};
 7826:             $inststatus = $userenvref->{'inststatus'};
 7827:         } else {
 7828:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7829:             $toolstatus = $userenv{$envkey};
 7830:             $inststatus = $userenv{'inststatus'};
 7831:         }
 7832:     }
 7833: 
 7834:     if ($toolstatus ne '') {
 7835:         if ($toolstatus) {
 7836:             $access = 1;
 7837:         } else {
 7838:             $access = 0;
 7839:         }
 7840:         return $access;
 7841:     }
 7842: 
 7843:     my ($is_adv,%domdef);
 7844:     if (ref($is_advref) eq 'HASH') {
 7845:         $is_adv = $is_advref->{'is_adv'};
 7846:     } else {
 7847:         $is_adv = &is_advanced_user($udom,$uname);
 7848:     }
 7849:     if (ref($domdefref) eq 'HASH') {
 7850:         %domdef = %{$domdefref};
 7851:     } else {
 7852:         %domdef = &get_domain_defaults($udom);
 7853:     }
 7854:     if (ref($domdef{$tool}) eq 'HASH') {
 7855:         if ($is_adv) {
 7856:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7857:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7858:                     $access = 1;
 7859:                 } else {
 7860:                     $access = 0;
 7861:                 }
 7862:                 return $access;
 7863:             }
 7864:         }
 7865:         if ($inststatus ne '') {
 7866:             my ($hasaccess,$hasnoaccess);
 7867:             foreach my $affiliation (split(/:/,$inststatus)) {
 7868:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7869:                     if ($domdef{$tool}{$affiliation}) {
 7870:                         $hasaccess = 1;
 7871:                     } else {
 7872:                         $hasnoaccess = 1;
 7873:                     }
 7874:                 }
 7875:             }
 7876:             if ($hasaccess || $hasnoaccess) {
 7877:                 if ($hasaccess) {
 7878:                     $access = 1;
 7879:                 } elsif ($hasnoaccess) {
 7880:                     $access = 0; 
 7881:                 }
 7882:                 return $access;
 7883:             }
 7884:         } else {
 7885:             if ($domdef{$tool}{'default'} ne '') {
 7886:                 if ($domdef{$tool}{'default'}) {
 7887:                     $access = 1;
 7888:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7889:                     $access = 0;
 7890:                 }
 7891:                 return $access;
 7892:             }
 7893:         }
 7894:     } else {
 7895:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7896:             $access = 1;
 7897:         } else {
 7898:             $access = 0;
 7899:         }
 7900:         return $access;
 7901:     }
 7902: }
 7903: 
 7904: sub is_course_owner {
 7905:     my ($cdom,$cnum,$udom,$uname) = @_;
 7906:     if (($udom eq '') || ($uname eq '')) {
 7907:         $udom = $env{'user.domain'};
 7908:         $uname = $env{'user.name'};
 7909:     }
 7910:     unless (($udom eq '') || ($uname eq '')) {
 7911:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7912:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7913:                 return 1;
 7914:             } else {
 7915:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7916:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7917:                     return 1;
 7918:                 }
 7919:             }
 7920:         }
 7921:     }
 7922:     return;
 7923: }
 7924: 
 7925: sub is_advanced_user {
 7926:     my ($udom,$uname) = @_;
 7927:     if ($udom ne '' && $uname ne '') {
 7928:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7929:             if (wantarray) {
 7930:                 return ($env{'user.adv'},$env{'user.author'});
 7931:             } else {
 7932:                 return $env{'user.adv'};
 7933:             }
 7934:         }
 7935:     }
 7936:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7937:     my %allroles;
 7938:     my ($is_adv,$is_author);
 7939:     foreach my $role (keys(%roleshash)) {
 7940:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7941:         my $area = '/'.$tdomain.'/'.$trest;
 7942:         if ($sec ne '') {
 7943:             $area .= '/'.$sec;
 7944:         }
 7945:         if (($area ne '') && ($trole ne '')) {
 7946:             my $spec=$trole.'.'.$area;
 7947:             if ($trole =~ /^cr\//) {
 7948:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7949:             } elsif ($trole ne 'gr') {
 7950:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7951:             }
 7952:             if ($trole eq 'au') {
 7953:                 $is_author = 1;
 7954:             }
 7955:         }
 7956:     }
 7957:     foreach my $role (keys(%allroles)) {
 7958:         last if ($is_adv);
 7959:         foreach my $item (split(/:/,$allroles{$role})) {
 7960:             if ($item ne '') {
 7961:                 my ($privilege,$restrictions)=split(/&/,$item);
 7962:                 if ($privilege eq 'adv') {
 7963:                     $is_adv = 1;
 7964:                     last;
 7965:                 }
 7966:             }
 7967:         }
 7968:     }
 7969:     if (wantarray) {
 7970:         return ($is_adv,$is_author);
 7971:     }
 7972:     return $is_adv;
 7973: }
 7974: 
 7975: sub check_can_request {
 7976:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7977:     my $canreq = 0;
 7978:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7979:         $uname = $env{'user.name'};
 7980:         $udom = $env{'user.domain'};
 7981:     }
 7982:     my ($types,$typename) = &Apache::loncommon::course_types();
 7983:     my @options = ('approval','validate','autolimit');
 7984:     my $optregex = join('|',@options);
 7985:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7986:         foreach my $type (@{$types}) {
 7987:             if (&usertools_access($uname,$udom,$type,undef,
 7988:                                   'requestcourses')) {
 7989:                 $canreq ++;
 7990:                 if (ref($request_domains) eq 'HASH') {
 7991:                     push(@{$request_domains->{$type}},$udom);
 7992:                 }
 7993:                 if ($dom eq $udom) {
 7994:                     $can_request->{$type} = 1;
 7995:                 }
 7996:             }
 7997:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7998:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7999:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8000:                 if (@curr > 0) {
 8001:                     foreach my $item (@curr) {
 8002:                         if (ref($request_domains) eq 'HASH') {
 8003:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8004:                             if ($otherdom ne '') {
 8005:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 8006:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8007:                                         push(@{$request_domains->{$type}},$otherdom);
 8008:                                     }
 8009:                                 } else {
 8010:                                     push(@{$request_domains->{$type}},$otherdom);
 8011:                                 }
 8012:                             }
 8013:                         }
 8014:                     }
 8015:                     unless ($dom eq $env{'user.domain'}) {
 8016:                         $canreq ++;
 8017:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8018:                             $can_request->{$type} = 1;
 8019:                         }
 8020:                     }
 8021:                 }
 8022:             }
 8023:         }
 8024:     }
 8025:     return $canreq;
 8026: }
 8027: 
 8028: # ---------------------------------------------- Custom access rule evaluation
 8029: 
 8030: sub customaccess {
 8031:     my ($priv,$uri)=@_;
 8032:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8033:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8034:     $udom = &LONCAPA::clean_domain($udom);
 8035:     $ucrs = &LONCAPA::clean_username($ucrs);
 8036:     my $access=0;
 8037:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8038: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8039: 	if ($type eq 'user') {
 8040: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8041: 		my ($tdom,$tuname)=split(m{/},$scope);
 8042: 		if ($tdom) {
 8043: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8044: 		}
 8045: 		if ($tuname) {
 8046: 		    if ($tuname ne $env{'user.name'}) { next; }
 8047: 		}
 8048: 		$access=($effect eq 'allow');
 8049: 		last;
 8050: 	    }
 8051: 	} else {
 8052: 	    if ($role) {
 8053: 		if ($role ne $urole) { next; }
 8054: 	    }
 8055: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8056: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8057: 		if ($tdom) {
 8058: 		    if ($tdom ne $udom) { next; }
 8059: 		}
 8060: 		if ($tcrs) {
 8061: 		    if ($tcrs ne $ucrs) { next; }
 8062: 		}
 8063: 		if ($tsec) {
 8064: 		    if ($tsec ne $usec) { next; }
 8065: 		}
 8066: 		$access=($effect eq 'allow');
 8067: 		last;
 8068: 	    }
 8069: 	    if ($realm eq '' && $role eq '') {
 8070: 		$access=($effect eq 'allow');
 8071: 	    }
 8072: 	}
 8073:     }
 8074:     return $access;
 8075: }
 8076: 
 8077: # ------------------------------------------------- Check for a user privilege
 8078: 
 8079: sub allowed {
 8080:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
 8081:     my $ver_orguri=$uri;
 8082:     $uri=&deversion($uri);
 8083:     my $orguri=$uri;
 8084:     $uri=&declutter($uri);
 8085: 
 8086:     if ($priv eq 'evb') {
 8087: # Evade communication block restrictions for specified role in a course
 8088:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8089:             return $1;
 8090:         } else {
 8091:             return;
 8092:         }
 8093:     }
 8094: 
 8095:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8096: # Free bre access to adm and meta resources
 8097:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8098: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8099: 	&& ($priv eq 'bre')) {
 8100: 	return 'F';
 8101:     }
 8102: 
 8103: # Free bre access to user's own portfolio contents
 8104:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8105:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8106: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8107:         my %setters;
 8108:         my ($startblock,$endblock) = 
 8109:             &Apache::loncommon::blockcheck(\%setters,'port');
 8110:         if ($startblock && $endblock) {
 8111:             return 'B';
 8112:         } else {
 8113:             return 'F';
 8114:         }
 8115:     }
 8116: 
 8117: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8118:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8119:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8120:         if (exists($env{'request.course.id'})) {
 8121:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8122:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8123:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8124:                 my $courseprivid=$env{'request.course.id'};
 8125:                 $courseprivid=~s/\_/\//;
 8126:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8127:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8128:                     return $1; 
 8129:                 } else {
 8130:                     if ($env{'request.course.sec'}) {
 8131:                         $courseprivid.='/'.$env{'request.course.sec'};
 8132:                     }
 8133:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8134:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8135:                         return $2;
 8136:                     }
 8137:                 }
 8138:             }
 8139:         }
 8140:     }
 8141: 
 8142: # Free bre to public access
 8143: 
 8144:     if ($priv eq 'bre') {
 8145:         my $copyright;
 8146:         unless ($uri =~ /ext\.tool/) {
 8147:             $copyright=&metadata($uri,'copyright');
 8148:         }
 8149: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8150:            return 'F'; 
 8151:         }
 8152:         if ($copyright eq 'priv') {
 8153:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8154: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8155: 		return '';
 8156:             }
 8157:         }
 8158:         if ($copyright eq 'domain') {
 8159:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8160: 	    unless (($env{'user.domain'} eq $1) ||
 8161:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8162: 		return '';
 8163:             }
 8164:         }
 8165:         if ($env{'request.role'}=~ /li\.\//) {
 8166:             # Library role, so allow browsing of resources in this domain.
 8167:             return 'F';
 8168:         }
 8169:         if ($copyright eq 'custom') {
 8170: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8171:         }
 8172:     }
 8173:     # Domain coordinator is trying to create a course
 8174:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8175:         # uri is the requested domain in this case.
 8176:         # comparison to 'request.role.domain' shows if the user has selected
 8177:         # a role of dc for the domain in question.
 8178:         return 'F' if ($uri eq $env{'request.role.domain'});
 8179:     }
 8180: 
 8181:     my $thisallowed='';
 8182:     my $statecond=0;
 8183:     my $courseprivid='';
 8184: 
 8185:     my $ownaccess;
 8186:     # Community Coordinator or Assistant Co-author browsing resource space.
 8187:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8188:         if ($uri eq '') {
 8189:             $ownaccess = 1;
 8190:         } else {
 8191:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8192:                 my $udom = $env{'user.domain'};
 8193:                 my $uname = $env{'user.name'};
 8194:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8195:                     $ownaccess = 1;
 8196:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8197:                     unless ($uri =~ m{\.\./}) {
 8198:                         $ownaccess = 1;
 8199:                     }
 8200:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8201:                     my $now = time;
 8202:                     if ($uri =~ m{^([^/]+)/?$}) {
 8203:                         my $adom = $1;
 8204:                         foreach my $key (keys(%env)) {
 8205:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8206:                                 my ($start,$end) = split('.',$env{$key});
 8207:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8208:                                     $ownaccess = 1;
 8209:                                     last;
 8210:                                 }
 8211:                             }
 8212:                         }
 8213:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8214:                         my $adom = $1;
 8215:                         my $aname = $2;
 8216:                         foreach my $role ('ca','aa') { 
 8217:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8218:                                 my ($start,$end) =
 8219:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8220:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8221:                                     $ownaccess = 1;
 8222:                                     last;
 8223:                                 }
 8224:                             }
 8225:                         }
 8226:                     }
 8227:                 }
 8228:             }
 8229:         }
 8230:     }
 8231: 
 8232: # Course
 8233: 
 8234:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8235:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8236:             $thisallowed.=$1;
 8237:         }
 8238:     }
 8239: 
 8240: # Domain
 8241: 
 8242:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8243:        =~/\Q$priv\E\&([^\:]*)/) {
 8244:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8245:             $thisallowed.=$1;
 8246:         }
 8247:     }
 8248: 
 8249: # User who is not author or co-author might still be able to edit
 8250: # resource of an author in the domain (e.g., if Domain Coordinator).
 8251:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8252:         (&allowed('mdc',$env{'request.course.id'}))) {
 8253:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8254:             $thisallowed.=$1;
 8255:         }
 8256:     }
 8257: 
 8258: # Course: uri itself is a course
 8259:     my $courseuri=$uri;
 8260:     $courseuri=~s/\_(\d)/\/$1/;
 8261:     $courseuri=~s/^([^\/])/\/$1/;
 8262: 
 8263:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8264:        =~/\Q$priv\E\&([^\:]*)/) {
 8265:         if ($priv eq 'mip') {
 8266:             my $rem = $1;
 8267:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8268:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8269:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8270:                 if ($cdom ne '') {
 8271:                     my %passwdconf = &get_passwdconf($cdom);
 8272:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8273:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8274:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8275:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8276:                                 unless (@inststatuses) {
 8277:                                     @inststatuses = ('default');
 8278:                                 }
 8279:                                 foreach my $status (@inststatuses) {
 8280:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8281:                                         $thisallowed.=$rem;
 8282:                                     }
 8283:                                 }
 8284:                             }
 8285:                         }
 8286:                     }
 8287:                 }
 8288:             }
 8289:         } else {
 8290:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8291:                 $thisallowed.=$1;
 8292:             }
 8293:         }
 8294:     }
 8295: 
 8296: # URI is an uploaded document for this course, default permissions don't matter
 8297: # not allowing 'edit' access (editupload) to uploaded course docs
 8298:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8299: 	$thisallowed='';
 8300:         my ($match)=&is_on_map($uri);
 8301:         if ($match) {
 8302:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8303:                   =~/\Q$priv\E\&([^\:]*)/) {
 8304:                 my $value = $1;
 8305:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8306:                 if ($deeplinkblock) {
 8307:                     $thisallowed='D';
 8308:                 } elsif ($noblockcheck) {
 8309:                     $thisallowed.=$value;
 8310:                 } else {
 8311:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8312:                     if (@blockers > 0) {
 8313:                         $thisallowed = 'B';
 8314:                     } else {
 8315:                         $thisallowed.=$value;
 8316:                     }
 8317:                 }
 8318:             }
 8319:         } else {
 8320:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8321:             if ($refuri) {
 8322:                 if ($refuri =~ m|^/adm/|) {
 8323:                     $thisallowed='F';
 8324:                 } else {
 8325:                     $refuri=&declutter($refuri);
 8326:                     my ($match) = &is_on_map($refuri);
 8327:                     if ($match) {
 8328:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8329:                         if ($deeplinkblock) {
 8330:                             $thisallowed='D';
 8331:                         } elsif ($noblockcheck) {
 8332:                             $thisallowed='F';
 8333:                         } else {
 8334:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8335:                             if (@blockers > 0) {
 8336:                                 $thisallowed = 'B';
 8337:                             } else {
 8338:                                 $thisallowed='F';
 8339:                             }
 8340:                         }
 8341:                     }
 8342:                 }
 8343:             }
 8344:         }
 8345:     }
 8346: 
 8347:     if ($priv eq 'bre'
 8348: 	&& $thisallowed ne 'F' 
 8349: 	&& $thisallowed ne '2'
 8350: 	&& &is_portfolio_url($uri)) {
 8351: 	$thisallowed = &portfolio_access($uri,$clientip);
 8352:     }
 8353: 
 8354: # Full access at system, domain or course-wide level? Exit.
 8355:     if ($thisallowed=~/F/) {
 8356: 	return 'F';
 8357:     }
 8358: 
 8359: # If this is generating or modifying users, exit with special codes
 8360: 
 8361:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8362: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8363: 	    my ($audom,$auname)=split('/',$uri);
 8364: # no author name given, so this just checks on the general right to make a co-author in this domain
 8365: 	    unless ($auname) { return $thisallowed; }
 8366: # an author name is given, so we are about to actually make a co-author for a certain account
 8367: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8368: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8369: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8370: 	}
 8371: 	return $thisallowed;
 8372:     }
 8373: #
 8374: # Gathered so far: system, domain and course wide privileges
 8375: #
 8376: # Course: See if uri or referer is an individual resource that is part of 
 8377: # the course
 8378: 
 8379:     if ($env{'request.course.id'}) {
 8380: 
 8381: # If this is modifying password (internal auth) domains must match for user and user's role.
 8382: 
 8383:         if ($priv eq 'mip') {
 8384:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8385:                 return $thisallowed;
 8386:             } else {
 8387:                 return '';
 8388:             }
 8389:         }
 8390: 
 8391:        $courseprivid=$env{'request.course.id'};
 8392:        if ($env{'request.course.sec'}) {
 8393:           $courseprivid.='/'.$env{'request.course.sec'};
 8394:        }
 8395:        $courseprivid=~s/\_/\//;
 8396:        my $checkreferer=1;
 8397:        my ($match,$cond)=&is_on_map($uri);
 8398:        if ($match) {
 8399:            $statecond=$cond;
 8400:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8401:                =~/\Q$priv\E\&([^\:]*)/) {
 8402:                my $value = $1;
 8403:                if ($priv eq 'bre') {
 8404:                    if ($noblockcheck) {
 8405:                        $thisallowed.=$value;
 8406:                    } else {
 8407:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8408:                        if (@blockers > 0) {
 8409:                            $thisallowed = 'B';
 8410:                        } else {
 8411:                            $thisallowed.=$value;
 8412:                        }
 8413:                    }
 8414:                } else {
 8415:                    $thisallowed.=$value;
 8416:                }
 8417:                $checkreferer=0;
 8418:            }
 8419:        }
 8420: 
 8421:        if ($checkreferer) {
 8422: 	  my $refuri=$env{'httpref.'.$orguri};
 8423:             unless ($refuri) {
 8424:                 foreach my $key (keys(%env)) {
 8425: 		    if ($key=~/^httpref\..*\*/) {
 8426: 			my $pattern=$key;
 8427:                         $pattern=~s/^httpref\.\/res\///;
 8428:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8429:                         $pattern=~s/\//\\\//g;
 8430:                         if ($orguri=~/$pattern/) {
 8431: 			    $refuri=$env{$key};
 8432:                         }
 8433:                     }
 8434:                 }
 8435:             }
 8436: 
 8437:          if ($refuri) { 
 8438: 	  $refuri=&declutter($refuri);
 8439:           my ($match,$cond)=&is_on_map($refuri);
 8440:             if ($match) {
 8441:               my $refstatecond=$cond;
 8442:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8443:                   =~/\Q$priv\E\&([^\:]*)/) {
 8444:                   my $value = $1;
 8445:                   if ($priv eq 'bre') {
 8446:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8447:                       if ($deeplinkblock) {
 8448:                           $thisallowed = 'D';
 8449:                       } elsif ($noblockcheck) {
 8450:                           $thisallowed.=$value;
 8451:                       } else {
 8452:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8453:                           if (@blockers > 0) {
 8454:                               $thisallowed = 'B';
 8455:                           } else {
 8456:                               $thisallowed.=$value;
 8457:                           }
 8458:                       }
 8459:                   } else {
 8460:                       $thisallowed.=$value;
 8461:                   }
 8462:                   $uri=$refuri;
 8463:                   $statecond=$refstatecond;
 8464:               }
 8465:           }
 8466:         }
 8467:        }
 8468:    }
 8469: 
 8470: #
 8471: # Gathered now: all privileges that could apply, and condition number
 8472: # 
 8473: #
 8474: # Full or no access?
 8475: #
 8476: 
 8477:     if ($thisallowed=~/F/) {
 8478: 	return 'F';
 8479:     }
 8480: 
 8481:     unless ($thisallowed) {
 8482:         return '';
 8483:     }
 8484: 
 8485: # Restrictions exist, deal with them
 8486: #
 8487: #   C:according to course preferences
 8488: #   R:according to resource settings
 8489: #   L:unless locked
 8490: #   X:according to user session state
 8491: #
 8492: 
 8493: # Possibly locked functionality, check all courses
 8494: # Locks might take effect only after 10 minutes cache expiration for other
 8495: # courses, and 2 minutes for current course
 8496: 
 8497:     my $envkey;
 8498:     if ($thisallowed=~/L/) {
 8499:         foreach $envkey (keys(%env)) {
 8500:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8501:                my $courseid=$2;
 8502:                my $roleid=$1.'.'.$2;
 8503:                $courseid=~s/^\///;
 8504:                my $expiretime=600;
 8505:                if ($env{'request.role'} eq $roleid) {
 8506: 		  $expiretime=120;
 8507:                }
 8508: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8509:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8510:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8511: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8512:                }
 8513:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8514:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8515: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8516:                        &log($env{'user.domain'},$env{'user.name'},
 8517:                             $env{'user.home'},
 8518:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8519:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8520:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8521: 		       return '';
 8522:                    }
 8523:                }
 8524:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8525:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8526: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8527:                        &log($env{'user.domain'},$env{'user.name'},
 8528:                             $env{'user.home'},
 8529:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8530:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8531:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8532: 		       return '';
 8533:                    }
 8534:                }
 8535: 	   }
 8536:        }
 8537:     }
 8538: 
 8539: #
 8540: # Rest of the restrictions depend on selected course
 8541: #
 8542: 
 8543:     unless ($env{'request.course.id'}) {
 8544: 	if ($thisallowed eq 'A') {
 8545: 	    return 'A';
 8546:         } elsif ($thisallowed eq 'B') {
 8547:             return 'B';
 8548: 	} else {
 8549: 	    return '1';
 8550: 	}
 8551:     }
 8552: 
 8553: #
 8554: # Now user is definitely in a course
 8555: #
 8556: 
 8557: 
 8558: # Course preferences
 8559: 
 8560:    if ($thisallowed=~/C/) {
 8561:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8562:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8563:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8564: 	   =~/\Q$rolecode\E/) {
 8565: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8566: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8567: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8568: 			$env{'request.course.id'});
 8569: 	   }
 8570:            return '';
 8571:        }
 8572: 
 8573:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8574: 	   =~/\Q$unamedom\E/) {
 8575: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8576: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8577: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8578: 			$env{'request.course.id'});
 8579: 	   }
 8580:            return '';
 8581:        }
 8582:    }
 8583: 
 8584: # Resource preferences
 8585: 
 8586:    if ($thisallowed=~/R/) {
 8587:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8588:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8589: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8590: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8591: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8592: 	   }
 8593: 	   return '';
 8594:        }
 8595:    }
 8596: 
 8597: # Restricted by state or randomout?
 8598: 
 8599:    if ($thisallowed=~/X/) {
 8600:       if ($env{'acc.randomout'}) {
 8601: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8602:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8603:             return ''; 
 8604:          }
 8605:       }
 8606:       if (&condval($statecond)) {
 8607: 	 return '2';
 8608:       } else {
 8609:          return '';
 8610:       }
 8611:    }
 8612: 
 8613:     if ($thisallowed eq 'A') {
 8614: 	return 'A';
 8615:     } elsif ($thisallowed eq 'B') {
 8616:         return 'B';
 8617:     } elsif ($thisallowed eq 'D') {
 8618:         return 'D';
 8619:     }
 8620:    return 'F';
 8621: }
 8622: 
 8623: # ------------------------------------------- Check construction space access
 8624: 
 8625: sub constructaccess {
 8626:     my ($url,$setpriv)=@_;
 8627: 
 8628: # We do not allow editing of previous versions of files
 8629:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8630: 
 8631: # Get username and domain from URL
 8632:     my ($ownername,$ownerdomain,$ownerhome);
 8633: 
 8634:     ($ownerdomain,$ownername) =
 8635:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8636: 
 8637: # The URL does not really point to any authorspace, forget it
 8638:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8639: 
 8640: # Now we need to see if the user has access to the authorspace of
 8641: # $ownername at $ownerdomain
 8642: 
 8643:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8644: # Real author for this?
 8645:        $ownerhome = $env{'user.home'};
 8646:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8647:           return ($ownername,$ownerdomain,$ownerhome);
 8648:        }
 8649:     } else {
 8650: # Co-author for this?
 8651:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8652:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8653:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8654:             return ($ownername,$ownerdomain,$ownerhome);
 8655:         }
 8656:         if ($env{'request.course.id'}) {
 8657:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8658:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8659:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8660:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8661:                     return ($ownername,$ownerdomain,$ownerhome);
 8662:                 }
 8663:             }
 8664:         }
 8665:     }
 8666: 
 8667: # We don't have any access right now. If we are not possibly going to do anything about this,
 8668: # we might as well leave
 8669:    unless ($setpriv) { return ''; }
 8670: 
 8671: # Backdoor access?
 8672:     my $allowed=&allowed('eco',$ownerdomain);
 8673: # Nope
 8674:     unless ($allowed) { return ''; }
 8675: # Looks like we may have access, but could be locked by the owner of the construction space
 8676:     if ($allowed eq 'U') {
 8677:         my %blocked=&get('environment',['domcoord.author'],
 8678:                          $ownerdomain,$ownername);
 8679: # Is blocked by owner
 8680:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8681:     }
 8682:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8683: # Grant temporary access
 8684:         my $then=$env{'user.login.time'};
 8685:         my $update=$env{'user.update.time'};
 8686:         if (!$update) { $update = $then; }
 8687:         my $refresh=$env{'user.refresh.time'};
 8688:         if (!$refresh) { $refresh = $update; }
 8689:         my $now = time;
 8690:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8691:                            $now,'ca','constructaccess');
 8692:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8693:         return($ownername,$ownerdomain,$ownerhome);
 8694:     }
 8695: # No business here
 8696:     return '';
 8697: }
 8698: 
 8699: # ----------------------------------------------------------- Content Blocking
 8700: 
 8701: {
 8702: # Caches for faster Course Contents display where content blocking
 8703: # is in operation (i.e., interval param set) for timed quiz.
 8704: #
 8705: # User for whom data are being temporarily cached.
 8706: my $cacheduser='';
 8707: # Course for which data are being temporarily cached.
 8708: my $cachedcid='';
 8709: # Cached blockers for this user (a hash of blocking items). 
 8710: my %cachedblockers=();
 8711: # When the data were last cached.
 8712: my $cachedlast='';
 8713: 
 8714: sub load_all_blockers {
 8715:     my ($uname,$udom)=@_;
 8716:     if (($uname ne '') && ($udom ne '')) { 
 8717:         if (($cacheduser eq $uname.':'.$udom) &&
 8718:             ($cachedcid eq $env{'request.course.id'}) &&
 8719:             (abs($cachedlast-time)<5)) {
 8720:             return;
 8721:         }
 8722:     }
 8723:     $cachedlast=time;
 8724:     $cacheduser=$uname.':'.$udom;
 8725:     $cachedcid=$env{'request.course.id'};
 8726:     %cachedblockers = &get_commblock_resources();
 8727:     return;
 8728: }
 8729: 
 8730: sub get_comm_blocks {
 8731:     my ($cdom,$cnum) = @_;
 8732:     if ($cdom eq '' || $cnum eq '') {
 8733:         return unless ($env{'request.course.id'});
 8734:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8735:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8736:     }
 8737:     my %commblocks;
 8738:     my $hashid=$cdom.'_'.$cnum;
 8739:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8740:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8741:         %commblocks = %{$blocksref};
 8742:     } else {
 8743:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8744:         my $cachetime = 600;
 8745:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8746:     }
 8747:     return %commblocks;
 8748: }
 8749: 
 8750: sub get_commblock_resources {
 8751:     my ($blocks) = @_;
 8752:     my %blockers = ();
 8753:     return %blockers unless ($env{'request.course.id'});
 8754:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8755:     my %commblocks;
 8756:     if (ref($blocks) eq 'HASH') {
 8757:         %commblocks = %{$blocks};
 8758:     } else {
 8759:         %commblocks = &get_comm_blocks();
 8760:     }
 8761:     return %blockers unless (keys(%commblocks) > 0); 
 8762:     my $navmap = Apache::lonnavmaps::navmap->new();
 8763:     return %blockers unless (ref($navmap));
 8764:     my $now = time;
 8765:     foreach my $block (keys(%commblocks)) {
 8766:         if ($block =~ /^(\d+)____(\d+)$/) {
 8767:             my ($start,$end) = ($1,$2);
 8768:             if ($start <= $now && $end >= $now) {
 8769:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8770:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8771:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8772:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8773:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8774:                             }
 8775:                         }
 8776:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8777:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8778:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8779:                             }
 8780:                         }
 8781:                     }
 8782:                 }
 8783:             }
 8784:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8785:             my $item = $1;
 8786:             my @to_test;
 8787:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8788:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8789:                     my @interval;
 8790:                     my $type = 'map';
 8791:                     if ($item eq 'course') {
 8792:                         $type = 'course';
 8793:                         @interval=&EXT("resource.0.interval");
 8794:                     } else {
 8795:                         if ($item =~ /___\d+___/) {
 8796:                             $type = 'resource';
 8797:                             @interval=&EXT("resource.0.interval",$item);
 8798:                             if (ref($navmap)) {                        
 8799:                                 my $res = $navmap->getBySymb($item); 
 8800:                                 push(@to_test,$res);
 8801:                             }
 8802:                         } else {
 8803:                             my $mapsymb = &symbread($item,1);
 8804:                             if ($mapsymb) {
 8805:                                 if (ref($navmap)) {
 8806:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8807:                                     if (ref($mapres)) {
 8808:                                         my $first = $mapres->map_start();
 8809:                                         my $finish = $mapres->map_finish();
 8810:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
 8811:                                         if (ref($it)) {
 8812:                                             my $res;
 8813:                                             while ($res = $it->next(undef,1)) {
 8814:                                                 next unless (ref($res));
 8815:                                                 my $symb = $res->symb();
 8816:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
 8817:                                                 @interval=&EXT("resource.0.interval",$symb);
 8818:                                                 if ($interval[1] eq 'map') {
 8819:                                                     if ($res->answerable()) {
 8820:                                                         push(@to_test,$res);
 8821:                                                         last;
 8822:                                                     }
 8823:                                                 }
 8824:                                             }
 8825:                                         }
 8826:                                     }
 8827:                                 }
 8828:                             }
 8829:                         }
 8830:                     }
 8831:                     if ($interval[0] =~ /^(\d+)/) {
 8832:                         my $timelimit = $1; 
 8833:                         my $first_access;
 8834:                         if ($type eq 'resource') {
 8835:                             $first_access=&get_first_access($interval[1],$item);
 8836:                         } elsif ($type eq 'map') {
 8837:                             $first_access=&get_first_access($interval[1],undef,$item);
 8838:                         } else {
 8839:                             $first_access=&get_first_access($interval[1]);
 8840:                         }
 8841:                         if ($first_access) {
 8842:                             my $timesup = $first_access+$timelimit;
 8843:                             if ($timesup > $now) {
 8844:                                 my $activeblock;
 8845:                                 foreach my $res (@to_test) {
 8846:                                     if ($res->answerable()) {
 8847:                                         $activeblock = 1;
 8848:                                         last;
 8849:                                     }
 8850:                                 }
 8851:                                 if ($activeblock) {
 8852:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8853:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8854:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8855:                                          }
 8856:                                     }
 8857:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8858:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8859:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8860:                                         }
 8861:                                     }
 8862:                                 }
 8863:                             }
 8864:                         }
 8865:                     }
 8866:                 }
 8867:             }
 8868:         }
 8869:     }
 8870:     return %blockers;
 8871: }
 8872: 
 8873: sub has_comm_blocking {
 8874:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 8875:     my @blockers;
 8876:     return unless ($env{'request.course.id'});
 8877:     return unless ($priv eq 'bre');
 8878:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8879:     return if ($env{'request.state'} eq 'construct');
 8880:     my %blockinfo;
 8881:     if (ref($blocks) eq 'HASH') {
 8882:         %blockinfo = &get_commblock_resources($blocks);
 8883:     } else {
 8884:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 8885:         %blockinfo = %cachedblockers;
 8886:     }
 8887:     return unless (keys(%blockinfo) > 0);
 8888:     my (%possibles,@symbs);
 8889:     if (!$symb) {
 8890:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 8891:     }
 8892:     if ($symb) {
 8893:         @symbs = ($symb);
 8894:     } elsif (keys(%possibles)) { 
 8895:         @symbs = keys(%possibles);
 8896:     }
 8897:     my $noblock;
 8898:     foreach my $symb (@symbs) {
 8899:         last if ($noblock);
 8900:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8901:         foreach my $block (keys(%blockinfo)) {
 8902:             if ($block =~ /^firstaccess____(.+)$/) {
 8903:                 my $item = $1;
 8904:                 unless ($blocked) {
 8905:                     if (($item eq $map) || ($item eq $symb)) {
 8906:                         $noblock = 1;
 8907:                         last;
 8908:                     }
 8909:                 }
 8910:             }
 8911:             if (ref($blockinfo{$block}) eq 'HASH') {
 8912:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 8913:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 8914:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8915:                             push(@blockers,$block);
 8916:                         }
 8917:                     }
 8918:                 }
 8919:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 8920:                     if ($blockinfo{$block}{'maps'}{$map}) {
 8921:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8922:                             push(@blockers,$block);
 8923:                         }
 8924:                     }
 8925:                 }
 8926:             }
 8927:         }
 8928:     }
 8929:     unless ($noblock) { 
 8930:         return @blockers;
 8931:     }
 8932:     return;
 8933: }
 8934: }
 8935: 
 8936: sub deeplink_check {
 8937:     my ($priv,$symb,$uri) = @_;
 8938:     return unless ($env{'request.course.id'});
 8939:     return unless ($priv eq 'bre');
 8940:     return if ($env{'request.state'} eq 'construct');
 8941:     return if ($env{'request.role.adv'});
 8942:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8943:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8944:     my (%possibles,@symbs);
 8945:     if (!$symb) {
 8946:         $symb = &symbread($uri,1,1,1,\%possibles);
 8947:     }
 8948:     if ($symb) {
 8949:         @symbs = ($symb);
 8950:     } elsif (keys(%possibles)) {
 8951:         @symbs = keys(%possibles);
 8952:     }
 8953: 
 8954:     my ($login,$switchrole,$allow);
 8955:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8956:         my $key = $1;
 8957:         my $tinyurl;
 8958:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8959:         if (defined($cached)) {
 8960:              $tinyurl = $result;
 8961:         } else {
 8962:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8963:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8964:              if ($currtiny{$key} ne '') {
 8965:                  $tinyurl = $currtiny{$key};
 8966:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8967:              }
 8968:         }
 8969:         if ($tinyurl ne '') {
 8970:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 8971:             if ($cnumreq eq $cnum) {
 8972:                 $login = $posslogin;
 8973:             } else {
 8974:                 $switchrole = 1;
 8975:             }
 8976:         }
 8977:     }
 8978:     foreach my $symb (@symbs) {
 8979:         last if ($allow);
 8980:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8981:         if ($deeplink eq '') {
 8982:             $allow = 1;
 8983:         } else {
 8984:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 8985:             if ($access eq 'any') {
 8986:                 $allow = 1;
 8987:             } elsif ($login) {
 8988:                 if ($access eq 'only') {
 8989:                     if ($scope eq 'res') {
 8990:                         if ($symb eq $login) {
 8991:                             $allow = 1;
 8992:                         }
 8993:                     } elsif ($scope eq 'map') {
 8994: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 8995:                     } elsif ($scope eq 'rec') {
 8996: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 8997:                     }
 8998:                 } else {
 8999:                     my ($acctype,$item) = split(/:/,$access);
 9000:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 9001:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 9002:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 9003:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 9004:                                 $allow = 1;
 9005:                             }
 9006:                         }
 9007:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9008:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9009:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 9010:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 9011:                                 $allow = 1;
 9012:                             }
 9013:                         }
 9014:                     }
 9015:                 }
 9016:             }
 9017:         }
 9018:     }
 9019:     return if ($allow);
 9020:     return 1;
 9021: }
 9022: 
 9023: # -------------------------------- Deversion and split uri into path an filename   
 9024: 
 9025: #
 9026: #   Removes the version from a URI and
 9027: #   splits it in to its filename and path to the filename.
 9028: #   Seems like File::Basename could have done this more clearly.
 9029: #   Parameters:
 9030: #      $uri   - input URI
 9031: #   Returns:
 9032: #     Two element list consisting of 
 9033: #     $pathname  - the URI up to and excluding the trailing /
 9034: #     $filename  - The part of the URI following the last /
 9035: #  NOTE:
 9036: #    Another realization of this is simply:
 9037: #    use File::Basename;
 9038: #    ...
 9039: #    $uri = shift;
 9040: #    $filename = basename($uri);
 9041: #    $path     = dirname($uri);
 9042: #    return ($filename, $path);
 9043: #
 9044: #     The implementation below is probably faster however.
 9045: #
 9046: sub split_uri_for_cond {
 9047:     my $uri=&deversion(&declutter(shift));
 9048:     my @uriparts=split(/\//,$uri);
 9049:     my $filename=pop(@uriparts);
 9050:     my $pathname=join('/',@uriparts);
 9051:     return ($pathname,$filename);
 9052: }
 9053: # --------------------------------------------------- Is a resource on the map?
 9054: 
 9055: sub is_on_map {
 9056:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9057:     #Trying to find the conditional for the file
 9058:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9059: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9060:     if ($match) {
 9061: 	return (1,$1);
 9062:     } else {
 9063: 	return (0,0);
 9064:     }
 9065: }
 9066: 
 9067: # --------------------------------------------------------- Get symb from alias
 9068: 
 9069: sub get_symb_from_alias {
 9070:     my $symb=shift;
 9071:     my ($map,$resid,$url)=&decode_symb($symb);
 9072: # Already is a symb
 9073:     if ($url) { return $symb; }
 9074: # Must be an alias
 9075:     my $aliassymb='';
 9076:     my %bighash;
 9077:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9078:                             &GDBM_READER(),0640)) {
 9079:         my $rid=$bighash{'mapalias_'.$symb};
 9080: 	if ($rid) {
 9081: 	    my ($mapid,$resid)=split(/\./,$rid);
 9082: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9083: 				    $resid,$bighash{'src_'.$rid});
 9084: 	}
 9085:         untie %bighash;
 9086:     }
 9087:     return $aliassymb;
 9088: }
 9089: 
 9090: # ----------------------------------------------------------------- Define Role
 9091: 
 9092: sub definerole {
 9093:   if (allowed('mcr','/')) {
 9094:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9095:     foreach my $role (split(':',$sysrole)) {
 9096: 	my ($crole,$cqual)=split(/\&/,$role);
 9097:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9098:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9099: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9100:                return "refused:s:$crole&$cqual"; 
 9101:             }
 9102:         }
 9103:     }
 9104:     foreach my $role (split(':',$domrole)) {
 9105: 	my ($crole,$cqual)=split(/\&/,$role);
 9106:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9107:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9108: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9109:                return "refused:d:$crole&$cqual"; 
 9110:             }
 9111:         }
 9112:     }
 9113:     foreach my $role (split(':',$courole)) {
 9114: 	my ($crole,$cqual)=split(/\&/,$role);
 9115:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9116:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9117: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9118:                return "refused:c:$crole&$cqual"; 
 9119:             }
 9120:         }
 9121:     }
 9122:     my $uhome;
 9123:     if (($uname ne '') && ($udom ne '')) {
 9124:         $uhome = &homeserver($uname,$udom);
 9125:         return $uhome if ($uhome eq 'no_host');
 9126:     } else {
 9127:         $uname = $env{'user.name'};
 9128:         $udom = $env{'user.domain'};
 9129:         $uhome = $env{'user.home'};
 9130:     }
 9131:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9132:                 "$udom:$uname:rolesdef_$rolename=".
 9133:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9134:     return reply($command,$uhome);
 9135:   } else {
 9136:     return 'refused';
 9137:   }
 9138: }
 9139: 
 9140: # ---------------- Make a metadata query against the network of library servers
 9141: 
 9142: sub metadata_query {
 9143:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9144:     my %rhash;
 9145:     my %libserv = &all_library();
 9146:     my @server_list = (defined($server_array) ? @$server_array
 9147:                                               : keys(%libserv) );
 9148:     for my $server (@server_list) {
 9149:         my $domains = ''; 
 9150:         if (ref($domains_hash) eq 'HASH') {
 9151:             $domains = $domains_hash->{$server}; 
 9152:         }
 9153: 	unless ($custom or $customshow) {
 9154: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9155: 	    $rhash{$server}=$reply;
 9156: 	}
 9157: 	else {
 9158: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9159: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9160: 			     $server);
 9161: 	    $rhash{$server}=$reply;
 9162: 	}
 9163:     }
 9164:     return \%rhash;
 9165: }
 9166: 
 9167: # ----------------------------------------- Send log queries and wait for reply
 9168: 
 9169: sub log_query {
 9170:     my ($uname,$udom,$query,%filters)=@_;
 9171:     my $uhome=&homeserver($uname,$udom);
 9172:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9173:     my $uhost=&hostname($uhome);
 9174:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9175:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9176:                        $uhome);
 9177:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9178:     return get_query_reply($queryid);
 9179: }
 9180: 
 9181: # -------------------------- Update MySQL table for portfolio file
 9182: 
 9183: sub update_portfolio_table {
 9184:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9185:     if ($group ne '') {
 9186:         $file_name =~s /^\Q$group\E//;
 9187:     }
 9188:     my $homeserver = &homeserver($uname,$udom);
 9189:     my $queryid=
 9190:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9191:                ':'.&escape($file_name).':'.$action,$homeserver);
 9192:     my $reply = &get_query_reply($queryid);
 9193:     return $reply;
 9194: }
 9195: 
 9196: # -------------------------- Update MySQL allusers table
 9197: 
 9198: sub update_allusers_table {
 9199:     my ($uname,$udom,$names) = @_;
 9200:     my $homeserver = &homeserver($uname,$udom);
 9201:     my $queryid=
 9202:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9203:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9204:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9205:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9206:                'generation='.&escape($names->{'generation'}).'%%'.
 9207:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9208:                'id='.&escape($names->{'id'}),$homeserver);
 9209:     return;
 9210: }
 9211: 
 9212: # ------- Request retrieval of institutional classlists for course(s)
 9213: 
 9214: sub fetch_enrollment_query {
 9215:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9216:     my ($homeserver,$sleep,$loopmax);
 9217:     my $maxtries = 1;
 9218:     if ($context eq 'automated') {
 9219:         $homeserver = $perlvar{'lonHostID'};
 9220:         $sleep = 2;
 9221:         $loopmax = 100;
 9222:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9223:     } else {
 9224:         $homeserver = &homeserver($cnum,$dom);
 9225:     }
 9226:     my $host=&hostname($homeserver);
 9227:     my $cmd = '';
 9228:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9229:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9230:     }
 9231:     $cmd =~ s/%%$//;
 9232:     $cmd = &escape($cmd);
 9233:     my $query = 'fetchenrollment';
 9234:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9235:     unless ($queryid=~/^\Q$host\E\_/) { 
 9236:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9237:         return 'error: '.$queryid;
 9238:     }
 9239:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9240:     my $tries = 1;
 9241:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9242:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9243:         $tries ++;
 9244:     }
 9245:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9246:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9247:     } else {
 9248:         my @responses = split(/:/,$reply);
 9249:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9250:             foreach my $line (@responses) {
 9251:                 my ($key,$value) = split(/=/,$line,2);
 9252:                 $$replyref{$key} = $value;
 9253:             }
 9254:         } else {
 9255:             my $pathname = LONCAPA::tempdir();
 9256:             foreach my $line (@responses) {
 9257:                 my ($key,$value) = split(/=/,$line);
 9258:                 $$replyref{$key} = $value;
 9259:                 if ($value > 0) {
 9260:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9261:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9262:                         my $destname = $pathname.'/'.$filename;
 9263:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9264:                         if ($xml_classlist =~ /^error/) {
 9265:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9266:                         } else {
 9267:                             if ( open(FILE,">",$destname) ) {
 9268:                                 print FILE &unescape($xml_classlist);
 9269:                                 close(FILE);
 9270:                             } else {
 9271:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9272:                             }
 9273:                         }
 9274:                     }
 9275:                 }
 9276:             }
 9277:         }
 9278:         return 'ok';
 9279:     }
 9280:     return 'error';
 9281: }
 9282: 
 9283: sub get_query_reply {
 9284:     my ($queryid,$sleep,$loopmax) = @_;;
 9285:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9286:         $sleep = 0.2;
 9287:     }
 9288:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9289:         $loopmax = 100;
 9290:     }
 9291:     my $replyfile=LONCAPA::tempdir().$queryid;
 9292:     my $reply='';
 9293:     for (1..$loopmax) {
 9294: 	sleep($sleep);
 9295:         if (-e $replyfile.'.end') {
 9296: 	    if (open(my $fh,"<",$replyfile)) {
 9297: 		$reply = join('',<$fh>);
 9298: 		close($fh);
 9299: 	   } else { return 'error: reply_file_error'; }
 9300:            return &unescape($reply);
 9301: 	}
 9302:     }
 9303:     return 'timeout:'.$queryid;
 9304: }
 9305: 
 9306: sub courselog_query {
 9307: #
 9308: # possible filters:
 9309: # url: url or symb
 9310: # username
 9311: # domain
 9312: # action: view, submit, grade
 9313: # start: timestamp
 9314: # end: timestamp
 9315: #
 9316:     my (%filters)=@_;
 9317:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9318:     if ($filters{'url'}) {
 9319: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9320:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9321:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9322:     }
 9323:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9324:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9325:     return &log_query($cname,$cdom,'courselog',%filters);
 9326: }
 9327: 
 9328: sub userlog_query {
 9329: #
 9330: # possible filters:
 9331: # action: log check role
 9332: # start: timestamp
 9333: # end: timestamp
 9334: #
 9335:     my ($uname,$udom,%filters)=@_;
 9336:     return &log_query($uname,$udom,'userlog',%filters);
 9337: }
 9338: 
 9339: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9340: 
 9341: sub auto_run {
 9342:     my ($cnum,$cdom) = @_;
 9343:     my $response = 0;
 9344:     my $settings;
 9345:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9346:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9347:         $settings = $domconfig{'autoenroll'};
 9348:         if ($settings->{'run'} eq '1') {
 9349:             $response = 1;
 9350:         }
 9351:     } else {
 9352:         my $homeserver;
 9353:         if (&is_course($cdom,$cnum)) {
 9354:             $homeserver = &homeserver($cnum,$cdom);
 9355:         } else {
 9356:             $homeserver = &domain($cdom,'primary');
 9357:         }
 9358:         if ($homeserver ne 'no_host') {
 9359:             $response = &reply('autorun:'.$cdom,$homeserver);
 9360:         }
 9361:     }
 9362:     return $response;
 9363: }
 9364: 
 9365: sub auto_get_sections {
 9366:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9367:     my $homeserver;
 9368:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9369:         $homeserver = &homeserver($cnum,$cdom);
 9370:     }
 9371:     if (!defined($homeserver)) { 
 9372:         if ($cdom =~ /^$match_domain$/) {
 9373:             $homeserver = &domain($cdom,'primary');
 9374:         }
 9375:     }
 9376:     my @secs;
 9377:     if (defined($homeserver)) {
 9378:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9379:         unless ($response eq 'refused') {
 9380:             @secs = split(/:/,$response);
 9381:         }
 9382:     }
 9383:     return @secs;
 9384: }
 9385: 
 9386: sub auto_new_course {
 9387:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9388:     my $homeserver = &homeserver($cnum,$cdom);
 9389:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9390:     return $response;
 9391: }
 9392: 
 9393: sub auto_validate_courseID {
 9394:     my ($cnum,$cdom,$inst_course_id) = @_;
 9395:     my $homeserver = &homeserver($cnum,$cdom);
 9396:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9397:     return $response;
 9398: }
 9399: 
 9400: sub auto_validate_instcode {
 9401:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9402:     my ($homeserver,$response);
 9403:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9404:         $homeserver = &homeserver($cnum,$cdom);
 9405:     }
 9406:     if (!defined($homeserver)) {
 9407:         if ($cdom =~ /^$match_domain$/) {
 9408:             $homeserver = &domain($cdom,'primary');
 9409:         }
 9410:     }
 9411:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9412:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9413:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9414:     return ($outcome,$description,$defaultcredits);
 9415: }
 9416: 
 9417: sub auto_create_password {
 9418:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9419:     my ($homeserver,$response);
 9420:     my $create_passwd = 0;
 9421:     my $authchk = '';
 9422:     if ($udom =~ /^$match_domain$/) {
 9423:         $homeserver = &domain($udom,'primary');
 9424:     }
 9425:     if ($homeserver eq '') {
 9426:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9427:             $homeserver = &homeserver($cnum,$cdom);
 9428:         }
 9429:     }
 9430:     if ($homeserver eq '') {
 9431:         $authchk = 'nodomain';
 9432:     } else {
 9433:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9434:         if ($response eq 'refused') {
 9435:             $authchk = 'refused';
 9436:         } else {
 9437:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9438:         }
 9439:     }
 9440:     return ($authparam,$create_passwd,$authchk);
 9441: }
 9442: 
 9443: sub auto_photo_permission {
 9444:     my ($cnum,$cdom,$students) = @_;
 9445:     my $homeserver = &homeserver($cnum,$cdom);
 9446:     my ($outcome,$perm_reqd,$conditions) = 
 9447: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9448:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9449: 	return (undef,undef);
 9450:     }
 9451:     return ($outcome,$perm_reqd,$conditions);
 9452: }
 9453: 
 9454: sub auto_checkphotos {
 9455:     my ($uname,$udom,$pid) = @_;
 9456:     my $homeserver = &homeserver($uname,$udom);
 9457:     my ($result,$resulttype);
 9458:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9459: 				   &escape($uname).':'.&escape($pid),
 9460: 				   $homeserver));
 9461:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9462: 	return (undef,undef);
 9463:     }
 9464:     if ($outcome) {
 9465:         ($result,$resulttype) = split(/:/,$outcome);
 9466:     } 
 9467:     return ($result,$resulttype);
 9468: }
 9469: 
 9470: sub auto_photochoice {
 9471:     my ($cnum,$cdom) = @_;
 9472:     my $homeserver = &homeserver($cnum,$cdom);
 9473:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9474: 						       &escape($cdom),
 9475: 						       $homeserver)));
 9476:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9477: 	return (undef,undef);
 9478:     }
 9479:     return ($update,$comment);
 9480: }
 9481: 
 9482: sub auto_photoupdate {
 9483:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9484:     my $homeserver = &homeserver($cnum,$dom);
 9485:     my $host=&hostname($homeserver);
 9486:     my $cmd = '';
 9487:     my $maxtries = 1;
 9488:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9489:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9490:     }
 9491:     $cmd =~ s/%%$//;
 9492:     $cmd = &escape($cmd);
 9493:     my $query = 'institutionalphotos';
 9494:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9495:     unless ($queryid=~/^\Q$host\E\_/) {
 9496:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9497:         return 'error: '.$queryid;
 9498:     }
 9499:     my $reply = &get_query_reply($queryid);
 9500:     my $tries = 1;
 9501:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9502:         $reply = &get_query_reply($queryid);
 9503:         $tries ++;
 9504:     }
 9505:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9506:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9507:     } else {
 9508:         my @responses = split(/:/,$reply);
 9509:         my $outcome = shift(@responses); 
 9510:         foreach my $item (@responses) {
 9511:             my ($key,$value) = split(/=/,$item);
 9512:             $$photo{$key} = $value;
 9513:         }
 9514:         return $outcome;
 9515:     }
 9516:     return 'error';
 9517: }
 9518: 
 9519: sub auto_instcode_format {
 9520:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9521: 	$cat_order) = @_;
 9522:     my $courses = '';
 9523:     my @homeservers;
 9524:     if ($caller eq 'global') {
 9525: 	my %servers = &get_servers($codedom,'library');
 9526: 	foreach my $tryserver (keys(%servers)) {
 9527: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9528: 		push(@homeservers,$tryserver);
 9529: 	    }
 9530:         }
 9531:     } elsif ($caller eq 'requests') {
 9532:         if ($codedom =~ /^$match_domain$/) {
 9533:             my $chome = &domain($codedom,'primary');
 9534:             unless ($chome eq 'no_host') {
 9535:                 push(@homeservers,$chome);
 9536:             }
 9537:         }
 9538:     } else {
 9539:         push(@homeservers,&homeserver($caller,$codedom));
 9540:     }
 9541:     foreach my $code (keys(%{$instcodes})) {
 9542:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9543:     }
 9544:     chop($courses);
 9545:     my $ok_response = 0;
 9546:     my $response;
 9547:     while (@homeservers > 0 && $ok_response == 0) {
 9548:         my $server = shift(@homeservers); 
 9549:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9550:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9551:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9552: 		split(/:/,$response);
 9553:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9554:             push(@{$codetitles},&str2array($codetitles_str));
 9555:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9556:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9557:             $ok_response = 1;
 9558:         }
 9559:     }
 9560:     if ($ok_response) {
 9561:         return 'ok';
 9562:     } else {
 9563:         return $response;
 9564:     }
 9565: }
 9566: 
 9567: sub auto_instcode_defaults {
 9568:     my ($domain,$returnhash,$code_order) = @_;
 9569:     my @homeservers;
 9570: 
 9571:     my %servers = &get_servers($domain,'library');
 9572:     foreach my $tryserver (keys(%servers)) {
 9573: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9574: 	    push(@homeservers,$tryserver);
 9575: 	}
 9576:     }
 9577: 
 9578:     my $response;
 9579:     foreach my $server (@homeservers) {
 9580:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9581:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9582: 	
 9583: 	foreach my $pair (split(/\&/,$response)) {
 9584: 	    my ($name,$value)=split(/\=/,$pair);
 9585: 	    if ($name eq 'code_order') {
 9586: 		@{$code_order} = split(/\&/,&unescape($value));
 9587: 	    } else {
 9588: 		$returnhash->{&unescape($name)}=&unescape($value);
 9589: 	    }
 9590: 	}
 9591: 	return 'ok';
 9592:     }
 9593: 
 9594:     return $response;
 9595: }
 9596: 
 9597: sub auto_possible_instcodes {
 9598:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9599:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9600:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9601:         return;
 9602:     }
 9603:     my (@homeservers,$uhome);
 9604:     if (defined(&domain($domain,'primary'))) {
 9605:         $uhome=&domain($domain,'primary');
 9606:         push(@homeservers,&domain($domain,'primary'));
 9607:     } else {
 9608:         my %servers = &get_servers($domain,'library');
 9609:         foreach my $tryserver (keys(%servers)) {
 9610:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9611:                 push(@homeservers,$tryserver);
 9612:             }
 9613:         }
 9614:     }
 9615:     my $response;
 9616:     foreach my $server (@homeservers) {
 9617:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9618:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9619:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9620:             split(':',$response);
 9621:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9622:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9623:         foreach my $item (split('&',$cat_title)) {   
 9624:             my ($name,$value)=split('=',$item);
 9625:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9626:         }
 9627:         foreach my $item (split('&',$cat_order)) {
 9628:             my ($name,$value)=split('=',$item);
 9629:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9630:         }
 9631:         return 'ok';
 9632:     }
 9633:     return $response;
 9634: }
 9635: 
 9636: sub auto_courserequest_checks {
 9637:     my ($dom) = @_;
 9638:     my ($homeserver,%validations);
 9639:     if ($dom =~ /^$match_domain$/) {
 9640:         $homeserver = &domain($dom,'primary');
 9641:     }
 9642:     unless ($homeserver eq 'no_host') {
 9643:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9644:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9645:             my @items = split(/&/,$response);
 9646:             foreach my $item (@items) {
 9647:                 my ($key,$value) = split('=',$item);
 9648:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9649:             }
 9650:         }
 9651:     }
 9652:     return %validations; 
 9653: }
 9654: 
 9655: sub auto_courserequest_validation {
 9656:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9657:     my ($homeserver,$response);
 9658:     if ($dom =~ /^$match_domain$/) {
 9659:         $homeserver = &domain($dom,'primary');
 9660:     }
 9661:     unless ($homeserver eq 'no_host') {
 9662:         my $customdata;
 9663:         if (ref($custominfo) eq 'HASH') {
 9664:             $customdata = &freeze_escape($custominfo);
 9665:         }
 9666:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9667:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9668:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9669:                                     $customdata,$homeserver));
 9670:     }
 9671:     return $response;
 9672: }
 9673: 
 9674: sub auto_validate_class_sec {
 9675:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9676:     my $homeserver = &homeserver($cnum,$cdom);
 9677:     my $ownerlist;
 9678:     if (ref($owners) eq 'ARRAY') {
 9679:         $ownerlist = join(',',@{$owners});
 9680:     } else {
 9681:         $ownerlist = $owners;
 9682:     }
 9683:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9684:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9685:     return $response;
 9686: }
 9687: 
 9688: sub auto_validate_instclasses {
 9689:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9690:     my ($homeserver,%validations);
 9691:     $homeserver = &homeserver($cnum,$cdom);
 9692:     unless ($homeserver eq 'no_host') {
 9693:         my $ownerlist;
 9694:         if (ref($owners) eq 'ARRAY') {
 9695:             $ownerlist = join(',',@{$owners});
 9696:         } else {
 9697:             $ownerlist = $owners;
 9698:         }
 9699:         if (ref($classesref) eq 'HASH') {
 9700:             my $classes = &freeze_escape($classesref);
 9701:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9702:                                 ':'.$cdom.':'.$classes,$homeserver);
 9703:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9704:                 my @items = split(/&/,$response);
 9705:                 foreach my $item (@items) {
 9706:                     my ($key,$value) = split('=',$item);
 9707:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9708:                 }
 9709:             }
 9710:         }
 9711:     }
 9712:     return %validations;
 9713: }
 9714: 
 9715: sub auto_crsreq_update {
 9716:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9717:         $code,$accessstart,$accessend,$inbound) = @_;
 9718:     my ($homeserver,%crsreqresponse);
 9719:     if ($cdom =~ /^$match_domain$/) {
 9720:         $homeserver = &domain($cdom,'primary');
 9721:     }
 9722:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9723:         my $info;
 9724:         if (ref($inbound) eq 'HASH') {
 9725:             $info = &freeze_escape($inbound);
 9726:         }
 9727:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9728:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9729:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9730:                             &escape($title).':'.&escape($code).':'.
 9731:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9732:                             $homeserver);
 9733:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9734:             my @items = split(/&/,$response);
 9735:             foreach my $item (@items) {
 9736:                 my ($key,$value) = split('=',$item);
 9737:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9738:             }
 9739:         }
 9740:     }
 9741:     return \%crsreqresponse;
 9742: }
 9743: 
 9744: sub auto_export_grades {
 9745:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9746:     my ($homeserver,%exportresponse);
 9747:     if ($cdom =~ /^$match_domain$/) {
 9748:         $homeserver = &domain($cdom,'primary');
 9749:     }
 9750:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9751:         my $info;
 9752:         if (ref($inforef) eq 'HASH') {
 9753:             $info = &freeze_escape($inforef);
 9754:         }
 9755:         if (ref($gradesref) eq 'HASH') {
 9756:             my $grades = &freeze_escape($gradesref);
 9757:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9758:                                 $info.':'.$grades,$homeserver);
 9759:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9760:                 my @items = split(/&/,$response);
 9761:                 foreach my $item (@items) {
 9762:                     my ($key,$value) = split('=',$item);
 9763:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9764:                 }
 9765:             }
 9766:         }
 9767:     }
 9768:     return \%exportresponse;
 9769: }
 9770: 
 9771: sub check_instcode_cloning {
 9772:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9773:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9774:         return;
 9775:     }
 9776:     my $canclone;
 9777:     if (@{$code_order} > 0) {
 9778:         my $instcoderegexp ='^';
 9779:         my @clonecodes = split(/\&/,$cloner);
 9780:         foreach my $item (@{$code_order}) {
 9781:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9782:                 foreach my $pair (@clonecodes) {
 9783:                     my ($key,$val) = split(/\=/,$pair,2);
 9784:                     $val = &unescape($val);
 9785:                     if ($key eq $item) {
 9786:                         $instcoderegexp .= '('.$val.')';
 9787:                         last;
 9788:                     }
 9789:                 }
 9790:             } else {
 9791:                 $instcoderegexp .= $codedefaults->{$item};
 9792:             }
 9793:         }
 9794:         $instcoderegexp .= '$';
 9795:         my (@from,@to);
 9796:         eval {
 9797:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9798:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9799:         };
 9800:         if ((@from > 0) && (@to > 0)) {
 9801:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9802:             if (!@diffs) {
 9803:                 $canclone = 1;
 9804:             }
 9805:         }
 9806:     }
 9807:     return $canclone;
 9808: }
 9809: 
 9810: sub default_instcode_cloning {
 9811:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9812:     my (%codedefaults,@code_order,$canclone);
 9813:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9814:         %codedefaults = %{$codedefaultsref};
 9815:         @code_order = @{$codeorderref};
 9816:     } elsif ($clonedom) {
 9817:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9818:     }
 9819:     if (($domdefclone) && (@code_order)) {
 9820:         my @clonecodes = split(/\+/,$domdefclone);
 9821:         my $instcoderegexp ='^';
 9822:         foreach my $item (@code_order) {
 9823:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9824:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9825:             } else {
 9826:                 $instcoderegexp .= $codedefaults{$item};
 9827:             }
 9828:         }
 9829:         $instcoderegexp .= '$';
 9830:         my (@from,@to);
 9831:         eval {
 9832:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9833:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9834:         };
 9835:         if ((@from > 0) && (@to > 0)) {
 9836:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9837:             if (!@diffs) {
 9838:                 $canclone = 1;
 9839:             }
 9840:         }
 9841:     }
 9842:     return $canclone;
 9843: }
 9844: 
 9845: # ------------------------------------------------------- Course Group routines
 9846: 
 9847: sub get_coursegroups {
 9848:     my ($cdom,$cnum,$group,$namespace) = @_;
 9849:     return(&dump($namespace,$cdom,$cnum,$group));
 9850: }
 9851: 
 9852: sub modify_coursegroup {
 9853:     my ($cdom,$cnum,$groupsettings) = @_;
 9854:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9855: }
 9856: 
 9857: sub toggle_coursegroup_status {
 9858:     my ($cdom,$cnum,$group,$action) = @_;
 9859:     my ($from_namespace,$to_namespace);
 9860:     if ($action eq 'delete') {
 9861:         $from_namespace = 'coursegroups';
 9862:         $to_namespace = 'deleted_groups';
 9863:     } else {
 9864:         $from_namespace = 'deleted_groups';
 9865:         $to_namespace = 'coursegroups';
 9866:     }
 9867:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9868:     if (my $tmp = &error(%curr_group)) {
 9869:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9870:         return ('read error',$tmp);
 9871:     } else {
 9872:         my %savedsettings = %curr_group; 
 9873:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9874:         my $deloutcome;
 9875:         if ($result eq 'ok') {
 9876:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9877:         } else {
 9878:             return ('write error',$result);
 9879:         }
 9880:         if ($deloutcome eq 'ok') {
 9881:             return 'ok';
 9882:         } else {
 9883:             return ('delete error',$deloutcome);
 9884:         }
 9885:     }
 9886: }
 9887: 
 9888: sub modify_group_roles {
 9889:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9890:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9891:     my $role = 'gr/'.&escape($userprivs);
 9892:     my ($uname,$udom) = split(/:/,$user);
 9893:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9894:     if ($result eq 'ok') {
 9895:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9896:     }
 9897:     return $result;
 9898: }
 9899: 
 9900: sub modify_coursegroup_membership {
 9901:     my ($cdom,$cnum,$membership) = @_;
 9902:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9903:     return $result;
 9904: }
 9905: 
 9906: sub get_active_groups {
 9907:     my ($udom,$uname,$cdom,$cnum) = @_;
 9908:     my $now = time;
 9909:     my %groups = ();
 9910:     foreach my $key (keys(%env)) {
 9911:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9912:             my ($start,$end) = split(/\./,$env{$key});
 9913:             if (($end!=0) && ($end<$now)) { next; }
 9914:             if (($start!=0) && ($start>$now)) { next; }
 9915:             if ($1 eq $cdom && $2 eq $cnum) {
 9916:                 $groups{$3} = $env{$key} ;
 9917:             }
 9918:         }
 9919:     }
 9920:     return %groups;
 9921: }
 9922: 
 9923: sub get_group_membership {
 9924:     my ($cdom,$cnum,$group) = @_;
 9925:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9926: }
 9927: 
 9928: sub get_users_groups {
 9929:     my ($udom,$uname,$courseid) = @_;
 9930:     my @usersgroups;
 9931:     my $cachetime=1800;
 9932: 
 9933:     my $hashid="$udom:$uname:$courseid";
 9934:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9935:     if (defined($cached)) {
 9936:         @usersgroups = split(/:/,$grouplist);
 9937:     } else {  
 9938:         $grouplist = '';
 9939:         my $courseurl = &courseid_to_courseurl($courseid);
 9940:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9941:         my $access_end = $env{'course.'.$courseid.
 9942:                               '.default_enrollment_end_date'};
 9943:         my $now = time;
 9944:         foreach my $key (keys(%roleshash)) {
 9945:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9946:                 my $group = $1;
 9947:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9948:                     my $start = $2;
 9949:                     my $end = $1;
 9950:                     if ($start == -1) { next; } # deleted from group
 9951:                     if (($start!=0) && ($start>$now)) { next; }
 9952:                     if (($end!=0) && ($end<$now)) {
 9953:                         if ($access_end && $access_end < $now) {
 9954:                             if ($access_end - $end < 86400) {
 9955:                                 push(@usersgroups,$group);
 9956:                             }
 9957:                         }
 9958:                         next;
 9959:                     }
 9960:                     push(@usersgroups,$group);
 9961:                 }
 9962:             }
 9963:         }
 9964:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9965:         $grouplist = join(':',@usersgroups);
 9966:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9967:     }
 9968:     return @usersgroups;
 9969: }
 9970: 
 9971: sub devalidate_getgroups_cache {
 9972:     my ($udom,$uname,$cdom,$cnum)=@_;
 9973:     my $courseid = $cdom.'_'.$cnum;
 9974: 
 9975:     my $hashid="$udom:$uname:$courseid";
 9976:     &devalidate_cache_new('getgroups',$hashid);
 9977: }
 9978: 
 9979: # ------------------------------------------------------------------ Plain Text
 9980: 
 9981: sub plaintext {
 9982:     my ($short,$type,$cid,$forcedefault) = @_;
 9983:     if ($short =~ m{^cr/}) {
 9984: 	return (split('/',$short))[-1];
 9985:     }
 9986:     if (!defined($cid)) {
 9987:         $cid = $env{'request.course.id'};
 9988:     }
 9989:     my %rolenames = (
 9990:                       Course    => 'std',
 9991:                       Community => 'alt1',
 9992:                       Placement => 'std',
 9993:                     );
 9994:     if ($cid ne '') {
 9995:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9996:             unless ($forcedefault) {
 9997:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9998:                 &Apache::lonlocal::mt_escape(\$roletext);
 9999:                 return &Apache::lonlocal::mt($roletext);
10000:             }
10001:         }
10002:     }
10003:     if ((defined($type)) && (defined($rolenames{$type})) &&
10004:         (defined($rolenames{$type})) && 
10005:         (defined($prp{$short}{$rolenames{$type}}))) {
10006:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10007:     } elsif ($cid ne '') {
10008:         my $crstype = $env{'course.'.$cid.'.type'};
10009:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10010:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10011:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10012:         }
10013:     }
10014:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10015: }
10016: 
10017: # ----------------------------------------------------------------- Assign Role
10018: 
10019: sub assignrole {
10020:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10021:         $context)=@_;
10022:     my $mrole;
10023:     if ($role =~ /^cr\//) {
10024:         my $cwosec=$url;
10025:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10026: 	unless (&allowed('ccr',$cwosec)) {
10027:            my $refused = 1;
10028:            if ($context eq 'requestcourses') {
10029:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10030:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10031:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10032:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10033:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10034:                            if ($crsenv{'internal.courseowner'} eq
10035:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10036:                                $refused = '';
10037:                            }
10038:                        }
10039:                    }
10040:                }
10041:            }
10042:            if ($refused) {
10043:                &logthis('Refused custom assignrole: '.
10044:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10045:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10046:                return 'refused';
10047:            }
10048:         }
10049:         $mrole='cr';
10050:     } elsif ($role =~ /^gr\//) {
10051:         my $cwogrp=$url;
10052:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10053:         unless (&allowed('mdg',$cwogrp)) {
10054:             &logthis('Refused group assignrole: '.
10055:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10056:                     $env{'user.name'}.' at '.$env{'user.domain'});
10057:             return 'refused';
10058:         }
10059:         $mrole='gr';
10060:     } else {
10061:         my $cwosec=$url;
10062:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10063:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10064:             my $refused;
10065:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10066:                 if (!(&allowed('c'.$role,$url))) {
10067:                     $refused = 1;
10068:                 }
10069:             } else {
10070:                 $refused = 1;
10071:             }
10072:             if ($refused) {
10073:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10074:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10075:                     my %crsenv;
10076:                     if ($role eq 'cc' || $role eq 'co') {
10077:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10078:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10079:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10080:                                 if ($crsenv{'internal.courseowner'} eq 
10081:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10082:                                     $refused = '';
10083:                                 }
10084:                             }
10085:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10086:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10087:                                 if ($crsenv{'internal.courseowner'} eq 
10088:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10089:                                     $refused = '';
10090:                                 }
10091:                             }
10092:                         }
10093:                     }
10094:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10095:                     if ($role eq 'st') {
10096:                         $refused = '';
10097:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10098:                         $refused = '';
10099:                     }
10100:                 } elsif ($context eq 'requestcourses') {
10101:                     my @possroles = ('st','ta','ep','in','cc','co');
10102:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10103:                         my $wrongcc;
10104:                         if ($cnum =~ /^$match_community$/) {
10105:                             $wrongcc = 1 if ($role eq 'cc');
10106:                         } else {
10107:                             $wrongcc = 1 if ($role eq 'co');
10108:                         }
10109:                         unless ($wrongcc) {
10110:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10111:                             if ($crsenv{'internal.courseowner'} eq 
10112:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10113:                                 $refused = '';
10114:                             }
10115:                         }
10116:                     }
10117:                 } elsif ($context eq 'requestauthor') {
10118:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10119:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10120:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10121:                             $refused = '';
10122:                         } else {
10123:                             my %domdefaults = &get_domain_defaults($udom);
10124:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10125:                                 my $checkbystatus;
10126:                                 if ($env{'user.adv'}) { 
10127:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10128:                                     if ($disposition eq 'automatic') {
10129:                                         $refused = '';
10130:                                     } elsif ($disposition eq '') {
10131:                                         $checkbystatus = 1;
10132:                                     } 
10133:                                 } else {
10134:                                     $checkbystatus = 1;
10135:                                 }
10136:                                 if ($checkbystatus) {
10137:                                     if ($env{'environment.inststatus'}) {
10138:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10139:                                         foreach my $type (@inststatuses) {
10140:                                             if (($type ne '') &&
10141:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10142:                                                 $refused = '';
10143:                                             }
10144:                                         }
10145:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10146:                                         $refused = '';
10147:                                     }
10148:                                 }
10149:                             }
10150:                         }
10151:                     }
10152:                 }
10153:                 if ($refused) {
10154:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10155:                              ' '.$role.' '.$end.' '.$start.' by '.
10156: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10157:                     return 'refused';
10158:                 }
10159:             }
10160:         } elsif ($role eq 'au') {
10161:             if ($url ne '/'.$udom.'/') {
10162:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10163:                          ' to assign author role for '.$uname.':'.$udom.
10164:                          ' in domain: '.$url.' refused (wrong domain).');
10165:                 return 'refused';
10166:             }
10167:         }
10168:         $mrole=$role;
10169:     }
10170:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10171:                 "$udom:$uname:$url".'_'."$mrole=$role";
10172:     if ($end) { $command.='_'.$end; }
10173:     if ($start) {
10174: 	if ($end) { 
10175:            $command.='_'.$start; 
10176:         } else {
10177:            $command.='_0_'.$start;
10178:         }
10179:     }
10180:     my $origstart = $start;
10181:     my $origend = $end;
10182:     my $delflag;
10183: # actually delete
10184:     if ($deleteflag) {
10185: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10186: # modify command to delete the role
10187:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10188:                 "$udom:$uname:$url".'_'."$mrole";
10189: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10190: # set start and finish to negative values for userrolelog
10191:            $start=-1;
10192:            $end=-1;
10193:            $delflag = 1;
10194:         }
10195:     }
10196: # send command
10197:     my $answer=&reply($command,&homeserver($uname,$udom));
10198: # log new user role if status is ok
10199:     if ($answer eq 'ok') {
10200: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10201:         if (($role eq 'cc') || ($role eq 'in') ||
10202:             ($role eq 'ep') || ($role eq 'ad') ||
10203:             ($role eq 'ta') || ($role eq 'st') ||
10204:             ($role=~/^cr/) || ($role eq 'gr') ||
10205:             ($role eq 'co')) {
10206: # for course roles, perform group memberships changes triggered by role change.
10207:             unless ($role =~ /^gr/) {
10208:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10209:                                                  $origstart,$selfenroll,$context);
10210:             }
10211:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10212:                            $selfenroll,$context);
10213:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10214:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10215:                  ($role eq 'da')) {
10216:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10217:                            $context);
10218:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10219:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10220:                              $context); 
10221:         }
10222:         if ($role eq 'cc') {
10223:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10224:         }
10225:     }
10226:     return $answer;
10227: }
10228: 
10229: sub autoupdate_coowners {
10230:     my ($url,$end,$start,$uname,$udom) = @_;
10231:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10232:     if (($cdom ne '') && ($cnum ne '')) {
10233:         my $now = time;
10234:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10235:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10236:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10237:             my $instcode = $coursehash{'internal.coursecode'};
10238:             if ($instcode ne '') {
10239:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10240:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10241:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10242:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10243:                         if ($result eq 'valid') {
10244:                             if ($coursehash{'internal.co-owners'}) {
10245:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10246:                                     push(@newcoowners,$coowner);
10247:                                 }
10248:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10249:                                     push(@newcoowners,$uname.':'.$udom);
10250:                                 }
10251:                                 @newcoowners = sort(@newcoowners);
10252:                             } else {
10253:                                 push(@newcoowners,$uname.':'.$udom);
10254:                             }
10255:                         } else {
10256:                             if ($coursehash{'internal.co-owners'}) {
10257:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10258:                                     unless ($coowner eq $uname.':'.$udom) {
10259:                                         push(@newcoowners,$coowner);
10260:                                     }
10261:                                 }
10262:                                 unless (@newcoowners > 0) {
10263:                                     $delcoowners = 1;
10264:                                     $coowners = '';
10265:                                 }
10266:                             }
10267:                         }
10268:                         if (@newcoowners || $delcoowners) {
10269:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10270:                                             $delcoowners,@newcoowners);
10271:                         }
10272:                     }
10273:                 }
10274:             }
10275:         }
10276:     }
10277: }
10278: 
10279: sub store_coowners {
10280:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10281:     my $cid = $cdom.'_'.$cnum;
10282:     my ($coowners,$delresult,$putresult);
10283:     if (@newcoowners) {
10284:         $coowners = join(',',@newcoowners);
10285:         my %coownershash = (
10286:                             'internal.co-owners' => $coowners,
10287:                            );
10288:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10289:         if ($putresult eq 'ok') {
10290:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10291:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10292:             }
10293:         }
10294:     }
10295:     if ($delcoowners) {
10296:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10297:         if ($delresult eq 'ok') {
10298:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10299:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10300:             }
10301:         }
10302:     }
10303:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10304:         my %crsinfo =
10305:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10306:         if (ref($crsinfo{$cid}) eq 'HASH') {
10307:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10308:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10309:         }
10310:     }
10311: }
10312: 
10313: # -------------------------------------------------- Modify user authentication
10314: # Overrides without validation
10315: 
10316: sub modifyuserauth {
10317:     my ($udom,$uname,$umode,$upass)=@_;
10318:     my $uhome=&homeserver($uname,$udom);
10319:     my $allowed;
10320:     if (&allowed('mau',$udom)) {
10321:         $allowed = 1;
10322:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10323:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10324:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10325:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10326:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10327:         if (($cdom ne '') && ($cnum ne '')) {
10328:             my $is_owner = &is_course_owner($cdom,$cnum);
10329:             if ($is_owner) {
10330:                 $allowed = 1;
10331:             }
10332:         }
10333:     }
10334:     unless ($allowed) { return 'refused'; }
10335:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10336:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10337:              ' in domain '.$env{'request.role.domain'});  
10338:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10339: 		     &escape($upass),$uhome);
10340:     my $ip = &get_requestor_ip();
10341:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10342:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10343:          '(Remote '.$ip.'): '.$reply);
10344:     &log($udom,,$uname,$uhome,
10345:         'Authentication changed by '.$env{'user.domain'}.', '.
10346:                                      $env{'user.name'}.', '.$umode.
10347:          '(Remote '.$ip.'): '.$reply);
10348:     unless ($reply eq 'ok') {
10349:         &logthis('Authentication mode error: '.$reply);
10350: 	return 'error: '.$reply;
10351:     }   
10352:     return 'ok';
10353: }
10354: 
10355: # --------------------------------------------------------------- Modify a user
10356: 
10357: sub modifyuser {
10358:     my ($udom,    $uname, $uid,
10359:         $umode,   $upass, $first,
10360:         $middle,  $last,  $gene,
10361:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10362:     $udom= &LONCAPA::clean_domain($udom);
10363:     $uname=&LONCAPA::clean_username($uname);
10364:     my $showcandelete = 'none';
10365:     if (ref($candelete) eq 'ARRAY') {
10366:         if (@{$candelete} > 0) {
10367:             $showcandelete = join(', ',@{$candelete});
10368:         }
10369:     }
10370:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10371:              $umode.', '.$first.', '.$middle.', '.
10372: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10373:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10374:                                      ' desiredhome not specified'). 
10375:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10376:              ' in domain '.$env{'request.role.domain'});
10377:     my $uhome=&homeserver($uname,$udom,'true');
10378:     my $newuser;
10379:     if ($uhome eq 'no_host') {
10380:         $newuser = 1;
10381:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10382:                 ($umode eq 'lti')) {
10383:             return 'error: more information needed to create new user';
10384:         }
10385:     }
10386: # ----------------------------------------------------------------- Create User
10387:     if (($uhome eq 'no_host') && 
10388: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10389:         my $unhome='';
10390:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10391:             $unhome = $desiredhome;
10392: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10393: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10394:         } else { # load balancing routine for determining $unhome
10395:             my $loadm=10000000;
10396: 	    my %servers = &get_servers($udom,'library');
10397: 	    foreach my $tryserver (keys(%servers)) {
10398: 		my $answer=reply('load',$tryserver);
10399: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10400: 		    $loadm=$answer;
10401: 		    $unhome=$tryserver;
10402: 		}
10403: 	    }
10404:         }
10405:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10406: 	    return 'error: unable to find a home server for '.$uname.
10407:                    ' in domain '.$udom;
10408:         }
10409:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10410:                          &escape($upass),$unhome);
10411: 	unless ($reply eq 'ok') {
10412:             return 'error: '.$reply;
10413:         }   
10414:         $uhome=&homeserver($uname,$udom,'true');
10415:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10416: 	    return 'error: unable verify users home machine.';
10417:         }
10418:     }   # End of creation of new user
10419: # ---------------------------------------------------------------------- Add ID
10420:     if ($uid) {
10421:        $uid=~tr/A-Z/a-z/;
10422:        my %uidhash=&idrget($udom,$uname);
10423:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10424:          && (!$forceid)) {
10425: 	  unless ($uid eq $uidhash{$uname}) {
10426: 	      return 'error: user id "'.$uid.'" does not match '.
10427:                   'current user id "'.$uidhash{$uname}.'".';
10428:           }
10429:        } else {
10430: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10431:        }
10432:     }
10433: # -------------------------------------------------------------- Add names, etc
10434:     my @tmp=&get('environment',
10435: 		   ['firstname','middlename','lastname','generation','id',
10436:                     'permanentemail','inststatus'],
10437: 		   $udom,$uname);
10438:     my (%names,%oldnames);
10439:     if ($tmp[0] =~ m/^error:.*/) { 
10440:         %names=(); 
10441:     } else {
10442:         %names = @tmp;
10443:         %oldnames = %names;
10444:     }
10445: #
10446: # If name, email and/or uid are blank (e.g., because an uploaded file
10447: # of users did not contain them), do not overwrite existing values
10448: # unless field is in $candelete array ref.  
10449: #
10450: 
10451:     my @fields = ('firstname','middlename','lastname','generation',
10452:                   'permanentemail','id');
10453:     my %newvalues;
10454:     if (ref($candelete) eq 'ARRAY') {
10455:         foreach my $field (@fields) {
10456:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10457:                 if ($field eq 'firstname') {
10458:                     $names{$field} = $first;
10459:                 } elsif ($field eq 'middlename') {
10460:                     $names{$field} = $middle;
10461:                 } elsif ($field eq 'lastname') {
10462:                     $names{$field} = $last;
10463:                 } elsif ($field eq 'generation') { 
10464:                     $names{$field} = $gene;
10465:                 } elsif ($field eq 'permanentemail') {
10466:                     $names{$field} = $email;
10467:                 } elsif ($field eq 'id') {
10468:                     $names{$field}  = $uid;
10469:                 }
10470:             }
10471:         }
10472:     }
10473:     if ($first)  { $names{'firstname'}  = $first; }
10474:     if (defined($middle)) { $names{'middlename'} = $middle; }
10475:     if ($last)   { $names{'lastname'}   = $last; }
10476:     if (defined($gene))   { $names{'generation'} = $gene; }
10477:     if ($email) {
10478:        $email=~s/[^\w\@\.\-\,]//gs;
10479:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10480:     }
10481:     if ($uid) { $names{'id'}  = $uid; }
10482:     if (defined($inststatus)) {
10483:         $names{'inststatus'} = '';
10484:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10485:         if (ref($usertypes) eq 'HASH') {
10486:             my @okstatuses; 
10487:             foreach my $item (split(/:/,$inststatus)) {
10488:                 if (defined($usertypes->{$item})) {
10489:                     push(@okstatuses,$item);  
10490:                 }
10491:             }
10492:             if (@okstatuses) {
10493:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10494:             }
10495:         }
10496:     }
10497:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10498:                  $umode.', '.$first.', '.$middle.', '.
10499:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10500:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10501:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10502:     } else {
10503:         $logmsg .= ' during self creation';
10504:     }
10505:     my $changed;
10506:     if ($newuser) {
10507:         $changed = 1;
10508:     } else {
10509:         foreach my $field (@fields) {
10510:             if ($names{$field} ne $oldnames{$field}) {
10511:                 $changed = 1;
10512:                 last;
10513:             }
10514:         }
10515:     }
10516:     unless ($changed) {
10517:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10518:         &logthis($logmsg);
10519:         return 'ok';
10520:     }
10521:     my $reply = &put('environment', \%names, $udom,$uname);
10522:     if ($reply ne 'ok') { 
10523:         return 'error: '.$reply;
10524:     }
10525:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10526:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10527:     }
10528:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10529:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10530:     $logmsg = 'Success modifying user '.$logmsg;
10531:     &logthis($logmsg);
10532:     return 'ok';
10533: }
10534: 
10535: # -------------------------------------------------------------- Modify student
10536: 
10537: sub modifystudent {
10538:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10539:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10540:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10541:     if (!$cid) {
10542: 	unless ($cid=$env{'request.course.id'}) {
10543: 	    return 'not_in_class';
10544: 	}
10545:     }
10546: # --------------------------------------------------------------- Make the user
10547:     my $reply=&modifyuser
10548: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10549:          $desiredhome,$email,$inststatus);
10550:     unless ($reply eq 'ok') { return $reply; }
10551:     # This will cause &modify_student_enrollment to get the uid from the
10552:     # student's environment
10553:     $uid = undef if (!$forceid);
10554:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10555:                                         $gene,$usec,$end,$start,$type,$locktype,
10556:                                         $cid,$selfenroll,$context,$credits,$instsec);
10557:     return $reply;
10558: }
10559: 
10560: sub modify_student_enrollment {
10561:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10562:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10563:     my ($cdom,$cnum,$chome);
10564:     if (!$cid) {
10565: 	unless ($cid=$env{'request.course.id'}) {
10566: 	    return 'not_in_class';
10567: 	}
10568: 	$cdom=$env{'course.'.$cid.'.domain'};
10569: 	$cnum=$env{'course.'.$cid.'.num'};
10570:     } else {
10571: 	($cdom,$cnum)=split(/_/,$cid);
10572:     }
10573:     $chome=$env{'course.'.$cid.'.home'};
10574:     if (!$chome) {
10575: 	$chome=&homeserver($cnum,$cdom);
10576:     }
10577:     if (!$chome) { return 'unknown_course'; }
10578:     # Make sure the user exists
10579:     my $uhome=&homeserver($uname,$udom);
10580:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10581: 	return 'error: no such user';
10582:     }
10583:     # Get student data if we were not given enough information
10584:     if (!defined($first)  || $first  eq '' || 
10585:         !defined($last)   || $last   eq '' || 
10586:         !defined($uid)    || $uid    eq '' || 
10587:         !defined($middle) || $middle eq '' || 
10588:         !defined($gene)   || $gene   eq '') {
10589:         # They did not supply us with enough data to enroll the student, so
10590:         # we need to pick up more information.
10591:         my %tmp = &get('environment',
10592:                        ['firstname','middlename','lastname', 'generation','id']
10593:                        ,$udom,$uname);
10594: 
10595:         #foreach my $key (keys(%tmp)) {
10596:         #    &logthis("key $key = ".$tmp{$key});
10597:         #}
10598:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10599:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10600:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10601:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10602:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10603:     }
10604:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10605:     my $user = "$uname:$udom";
10606:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10607:     my $reply=cput('classlist',
10608: 		   {$user => 
10609: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10610: 		   $cdom,$cnum);
10611:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10612:         &devalidate_getsection_cache($udom,$uname,$cid);
10613:     } else { 
10614: 	return 'error: '.$reply;
10615:     }
10616:     # Add student role to user
10617:     my $uurl='/'.$cid;
10618:     $uurl=~s/\_/\//g;
10619:     if ($usec) {
10620: 	$uurl.='/'.$usec;
10621:     }
10622:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10623:                              $selfenroll,$context);
10624:     if ($result ne 'ok') {
10625:         if ($old_entry{$user} ne '') {
10626:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10627:         } else {
10628:             $reply = &del('classlist',[$user],$cdom,$cnum);
10629:         }
10630:     }
10631:     return $result; 
10632: }
10633: 
10634: sub format_name {
10635:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10636:     my $name;
10637:     if ($first ne 'lastname') {
10638: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10639:     } else {
10640: 	if ($lastname=~/\S/) {
10641: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10642: 	    $name=~s/\s+,/,/;
10643: 	} else {
10644: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10645: 	}
10646:     }
10647:     $name=~s/^\s+//;
10648:     $name=~s/\s+$//;
10649:     $name=~s/\s+/ /g;
10650:     return $name;
10651: }
10652: 
10653: # ------------------------------------------------- Write to course preferences
10654: 
10655: sub writecoursepref {
10656:     my ($courseid,%prefs)=@_;
10657:     $courseid=~s/^\///;
10658:     $courseid=~s/\_/\//g;
10659:     my ($cdomain,$cnum)=split(/\//,$courseid);
10660:     my $chome=homeserver($cnum,$cdomain);
10661:     if (($chome eq '') || ($chome eq 'no_host')) { 
10662: 	return 'error: no such course';
10663:     }
10664:     my $cstring='';
10665:     foreach my $pref (keys(%prefs)) {
10666: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10667:     }
10668:     $cstring=~s/\&$//;
10669:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10670: }
10671: 
10672: # ---------------------------------------------------------- Make/modify course
10673: 
10674: sub createcourse {
10675:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10676:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10677:     $url=&declutter($url);
10678:     my $cid='';
10679:     if ($context eq 'requestcourses') {
10680:         my $can_create = 0;
10681:         my ($ownername,$ownerdom) = split(':',$course_owner);
10682:         if ($udom eq $ownerdom) {
10683:             my $reload;
10684:             if (($callercontext eq 'auto') &&
10685:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10686:                 $reload = 'reload';
10687:             }
10688:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10689:                                   $context)) {
10690:                 $can_create = 1;
10691:             }
10692:         } else {
10693:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10694:                                            $category);
10695:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10696:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10697:                 if (@curr > 0) {
10698:                     my @options = qw(approval validate autolimit);
10699:                     my $optregex = join('|',@options);
10700:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10701:                         $can_create = 1;
10702:                     }
10703:                 }
10704:             }
10705:         }
10706:         if ($can_create) {
10707:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10708:                 unless (&allowed('ccc',$udom)) {
10709:                     return 'refused'; 
10710:                 }
10711:             }
10712:         } else {
10713:             return 'refused';
10714:         }
10715:     } elsif (!&allowed('ccc',$udom)) {
10716:         return 'refused';
10717:     }
10718: # --------------------------------------------------------------- Get Unique ID
10719:     my $uname;
10720:     if ($cnum =~ /^$match_courseid$/) {
10721:         my $chome=&homeserver($cnum,$udom,'true');
10722:         if (($chome eq '') || ($chome eq 'no_host')) {
10723:             $uname = $cnum;
10724:         } else {
10725:             $uname = &generate_coursenum($udom,$crstype);
10726:         }
10727:     } else {
10728:         $uname = &generate_coursenum($udom,$crstype);
10729:     }
10730:     return $uname if ($uname =~ /^error/);
10731: # -------------------------------------------------- Check supplied server name
10732:     if (!defined($course_server)) {
10733:         if (defined(&domain($udom,'primary'))) {
10734:             $course_server = &domain($udom,'primary');
10735:         } else {
10736:             $course_server = $env{'user.home'}; 
10737:         }
10738:     }
10739:     my %host_servers =
10740:         &Apache::lonnet::get_servers($udom,'library');
10741:     unless ($host_servers{$course_server}) {
10742:         return 'error: invalid home server for course: '.$course_server;
10743:     }
10744: # ------------------------------------------------------------- Make the course
10745:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10746:                       $course_server);
10747:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10748:     my $uhome=&homeserver($uname,$udom,'true');
10749:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10750: 	return 'error: no such course';
10751:     }
10752: # ----------------------------------------------------------------- Course made
10753: # log existence
10754:     my $now = time;
10755:     my $newcourse = {
10756:                     $udom.'_'.$uname => {
10757:                                      description => $description,
10758:                                      inst_code   => $inst_code,
10759:                                      owner       => $course_owner,
10760:                                      type        => $crstype,
10761:                                      creator     => $env{'user.name'}.':'.
10762:                                                     $env{'user.domain'},
10763:                                      created     => $now,
10764:                                      context     => $context,
10765:                                                 },
10766:                     };
10767:     &courseidput($udom,$newcourse,$uhome,'notime');
10768: # set toplevel url
10769:     my $topurl=$url;
10770:     unless ($nonstandard) {
10771: # ------------------------------------------ For standard courses, make top url
10772:         my $mapurl=&clutter($url);
10773:         if ($mapurl eq '/res/') { $mapurl=''; }
10774:         $env{'form.initmap'}=(<<ENDINITMAP);
10775: <map>
10776: <resource id="1" type="start"></resource>
10777: <resource id="2" src="$mapurl"></resource>
10778: <resource id="3" type="finish"></resource>
10779: <link index="1" from="1" to="2"></link>
10780: <link index="2" from="2" to="3"></link>
10781: </map>
10782: ENDINITMAP
10783:         $topurl=&declutter(
10784:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10785:                           );
10786:     }
10787: # ----------------------------------------------------------- Write preferences
10788:     &writecoursepref($udom.'_'.$uname,
10789:                      ('description'              => $description,
10790:                       'url'                      => $topurl,
10791:                       'internal.creator'         => $env{'user.name'}.':'.
10792:                                                     $env{'user.domain'},
10793:                       'internal.created'         => $now,
10794:                       'internal.creationcontext' => $context)
10795:                     );
10796:     return '/'.$udom.'/'.$uname;
10797: }
10798: 
10799: # ------------------------------------------------------------------- Create ID
10800: sub generate_coursenum {
10801:     my ($udom,$crstype) = @_;
10802:     my $domdesc = &domain($udom);
10803:     return 'error: invalid domain' if ($domdesc eq '');
10804:     my $first;
10805:     if ($crstype eq 'Community') {
10806:         $first = '0';
10807:     } else {
10808:         $first = int(1+rand(9)); 
10809:     } 
10810:     my $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: # ----------------------------------------------- Make sure that does not exist
10815:     my $uhome=&homeserver($uname,$udom,'true');
10816:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10817:         if ($crstype eq 'Community') {
10818:             $first = '0';
10819:         } else {
10820:             $first = int(1+rand(9));
10821:         }
10822:         $uname=$first.
10823:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10824:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10825:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10826:         $uhome=&homeserver($uname,$udom,'true');
10827:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10828:             return 'error: unable to generate unique course-ID';
10829:         }
10830:     }
10831:     return $uname;
10832: }
10833: 
10834: sub is_course {
10835:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10836:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10837: 
10838:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10839:     my $uhome=&homeserver($cnum,$cdom);
10840:     my $iscourse;
10841:     if (grep { $_ eq $uhome } current_machine_ids()) {
10842:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10843:     } else {
10844:         my $hashid = $cdom.':'.$cnum;
10845:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10846:         unless (defined($cached)) {
10847:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10848:                                         $cnum,undef,undef,'.');
10849:             $iscourse = 0;
10850:             if (exists($courses{$cdom.'_'.$cnum})) {
10851:                 $iscourse = 1;
10852:             }
10853:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10854:         }
10855:     }
10856:     return unless ($iscourse);
10857:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10858: }
10859: 
10860: sub store_userdata {
10861:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10862:     my $result;
10863:     if ($datakey ne '') {
10864:         if (ref($storehash) eq 'HASH') {
10865:             if ($udom eq '' || $uname eq '') {
10866:                 $udom = $env{'user.domain'};
10867:                 $uname = $env{'user.name'};
10868:             }
10869:             my $uhome=&homeserver($uname,$udom);
10870:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10871:                 $result = 'error: no_host';
10872:             } else {
10873:                 $storehash->{'ip'} = &get_requestor_ip();
10874:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10875: 
10876:                 my $namevalue='';
10877:                 foreach my $key (keys(%{$storehash})) {
10878:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10879:                 }
10880:                 $namevalue=~s/\&$//;
10881:                 unless ($namespace eq 'courserequests') {
10882:                     $datakey = &escape($datakey);
10883:                 }
10884:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10885:                                   $namevalue,$uhome);
10886:             }
10887:         } else {
10888:             $result = 'error: data to store was not a hash reference'; 
10889:         }
10890:     } else {
10891:         $result= 'error: invalid requestkey'; 
10892:     }
10893:     return $result;
10894: }
10895: 
10896: # ---------------------------------------------------------- Assign Custom Role
10897: 
10898: sub assigncustomrole {
10899:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10900:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10901:                        $end,$start,$deleteflag,$selfenroll,$context);
10902: }
10903: 
10904: # ----------------------------------------------------------------- Revoke Role
10905: 
10906: sub revokerole {
10907:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10908:     my $now=time;
10909:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10910: }
10911: 
10912: # ---------------------------------------------------------- Revoke Custom Role
10913: 
10914: sub revokecustomrole {
10915:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10916:     my $now=time;
10917:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10918:            $deleteflag,$selfenroll,$context);
10919: }
10920: 
10921: # ------------------------------------------------------------ Disk usage
10922: sub diskusage {
10923:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10924:     $directorypath =~ s/\/$//;
10925:     my $listing=&reply('du2:'.&escape($directorypath).':'
10926:                        .&escape($getpropath).':'.&escape($uname).':'
10927:                        .&escape($udom),homeserver($uname,$udom));
10928:     if ($listing eq 'unknown_cmd') {
10929:         if ($getpropath) {
10930:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10931:         }
10932:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10933:     }
10934:     return $listing;
10935: }
10936: 
10937: sub is_locked {
10938:     my ($file_name, $domain, $user, $which) = @_;
10939:     my @check;
10940:     my $is_locked;
10941:     push (@check,$file_name);
10942:     my %locked = &get('file_permissions',\@check,
10943: 		      $env{'user.domain'},$env{'user.name'});
10944:     my ($tmp)=keys(%locked);
10945:     if ($tmp=~/^error:/) { undef(%locked); }
10946:     
10947:     if (ref($locked{$file_name}) eq 'ARRAY') {
10948:         $is_locked = 'false';
10949:         foreach my $entry (@{$locked{$file_name}}) {
10950:            if (ref($entry) eq 'ARRAY') {
10951:                $is_locked = 'true';
10952:                if (ref($which) eq 'ARRAY') {
10953:                    push(@{$which},$entry);
10954:                } else {
10955:                    last;
10956:                }
10957:            }
10958:        }
10959:     } else {
10960:         $is_locked = 'false';
10961:     }
10962:     return $is_locked;
10963: }
10964: 
10965: sub declutter_portfile {
10966:     my ($file) = @_;
10967:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10968:     return $file;
10969: }
10970: 
10971: # ------------------------------------------------------------- Mark as Read Only
10972: 
10973: sub mark_as_readonly {
10974:     my ($domain,$user,$files,$what) = @_;
10975:     my %current_permissions = &dump('file_permissions',$domain,$user);
10976:     my ($tmp)=keys(%current_permissions);
10977:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10978:     foreach my $file (@{$files}) {
10979: 	$file = &declutter_portfile($file);
10980:         push(@{$current_permissions{$file}},$what);
10981:     }
10982:     &put('file_permissions',\%current_permissions,$domain,$user);
10983:     return;
10984: }
10985: 
10986: # ------------------------------------------------------------Save Selected Files
10987: 
10988: sub save_selected_files {
10989:     my ($user, $path, @files) = @_;
10990:     my $filename = $user."savedfiles";
10991:     my @other_files = &files_not_in_path($user, $path);
10992:     open (OUT,'>',LONCAPA::tempdir().$filename);
10993:     foreach my $file (@files) {
10994:         print (OUT $env{'form.currentpath'}.$file."\n");
10995:     }
10996:     foreach my $file (@other_files) {
10997:         print (OUT $file."\n");
10998:     }
10999:     close (OUT);
11000:     return 'ok';
11001: }
11002: 
11003: sub clear_selected_files {
11004:     my ($user) = @_;
11005:     my $filename = $user."savedfiles";
11006:     open (OUT,'>',LONCAPA::tempdir().$filename);
11007:     print (OUT undef);
11008:     close (OUT);
11009:     return ("ok");    
11010: }
11011: 
11012: sub files_in_path {
11013:     my ($user, $path) = @_;
11014:     my $filename = $user."savedfiles";
11015:     my %return_files;
11016:     open (IN,'<',LONCAPA::tempdir().$filename);
11017:     while (my $line_in = <IN>) {
11018:         chomp ($line_in);
11019:         my @paths_and_file = split (m!/!, $line_in);
11020:         my $file_part = pop (@paths_and_file);
11021:         my $path_part = join ('/', @paths_and_file);
11022:         $path_part.='/';
11023:         my $path_and_file = $path_part.$file_part;
11024:         if ($path_part eq $path) {
11025:             $return_files{$file_part}= 'selected';
11026:         }
11027:     }
11028:     close (IN);
11029:     return (\%return_files);
11030: }
11031: 
11032: # called in portfolio select mode, to show files selected NOT in current directory
11033: sub files_not_in_path {
11034:     my ($user, $path) = @_;
11035:     my $filename = $user."savedfiles";
11036:     my @return_files;
11037:     my $path_part;
11038:     open(IN, '<',LONCAPA::tempdir().$filename);
11039:     while (my $line = <IN>) {
11040:         #ok, I know it's clunky, but I want it to work
11041:         my @paths_and_file = split(m|/|, $line);
11042:         my $file_part = pop(@paths_and_file);
11043:         chomp($file_part);
11044:         my $path_part = join('/', @paths_and_file);
11045:         $path_part .= '/';
11046:         my $path_and_file = $path_part.$file_part;
11047:         if ($path_part ne $path) {
11048:             push(@return_files, ($path_and_file));
11049:         }
11050:     }
11051:     close(OUT);
11052:     return (@return_files);
11053: }
11054: 
11055: #------------------------------Submitted/Handedback Portfolio Files Versioning
11056:  
11057: sub portfiles_versioning {
11058:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11059:     my $portfolio_root = '/userfiles/portfolio';
11060:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11061:     foreach my $file (@{$portfiles}) {
11062:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11063:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11064:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11065:         my $getpropath = 1;
11066:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11067:                                              $stu_name,$getpropath);
11068:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11069:         my $new_answer = 
11070:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11071:         if ($new_answer ne 'problem getting file') {
11072:             push(@{$versioned_portfiles}, $directory.$new_answer);
11073:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11074:                               [$symb,$env{'request.course.id'},'graded']);
11075:         }
11076:     }
11077: }
11078: 
11079: sub get_next_version {
11080:     my ($answer_name, $answer_ext, $dir_list) = @_;
11081:     my $version;
11082:     if (ref($dir_list) eq 'ARRAY') {
11083:         foreach my $row (@{$dir_list}) {
11084:             my ($file) = split(/\&/,$row,2);
11085:             my ($file_name,$file_version,$file_ext) =
11086:                 &file_name_version_ext($file);
11087:             if (($file_name eq $answer_name) &&
11088:                 ($file_ext eq $answer_ext)) {
11089:                      # gets here if filename and extension match,
11090:                      # regardless of version
11091:                 if ($file_version ne '') {
11092:                     # a versioned file is found  so save it for later
11093:                     if ($file_version > $version) {
11094:                         $version = $file_version;
11095:                     }
11096:                 }
11097:             }
11098:         }
11099:     }
11100:     $version ++;
11101:     return($version);
11102: }
11103: 
11104: sub version_selected_portfile {
11105:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11106:     my ($answer_name,$answer_ver,$answer_ext) =
11107:         &file_name_version_ext($file_name);
11108:     my $new_answer;
11109:     $env{'form.copy'} =
11110:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11111:     if($env{'form.copy'} eq '-1') {
11112:         $new_answer = 'problem getting file';
11113:     } else {
11114:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11115:         my $copy_result = 
11116:             &finishuserfileupload($stu_name,$domain,'copy',
11117:                                   '/portfolio'.$directory.$new_answer);
11118:     }
11119:     undef($env{'form.copy'});
11120:     return ($new_answer);
11121: }
11122: 
11123: sub file_name_version_ext {
11124:     my ($file)=@_;
11125:     my @file_parts = split(/\./, $file);
11126:     my ($name,$version,$ext);
11127:     if (@file_parts > 1) {
11128:         $ext=pop(@file_parts);
11129:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11130:             $version=pop(@file_parts);
11131:         }
11132:         $name=join('.',@file_parts);
11133:     } else {
11134:         $name=join('.',@file_parts);
11135:     }
11136:     return($name,$version,$ext);
11137: }
11138: 
11139: #----------------------------------------------Get portfolio file permissions
11140: 
11141: sub get_portfile_permissions {
11142:     my ($domain,$user) = @_;
11143:     my %current_permissions = &dump('file_permissions',$domain,$user);
11144:     my ($tmp)=keys(%current_permissions);
11145:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11146:     return \%current_permissions;
11147: }
11148: 
11149: #---------------------------------------------Get portfolio file access controls
11150: 
11151: sub get_access_controls {
11152:     my ($current_permissions,$group,$file) = @_;
11153:     my %access;
11154:     my $real_file = $file;
11155:     $file =~ s/\.meta$//;
11156:     if (defined($file)) {
11157:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11158:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11159:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11160:             }
11161:         }
11162:     } else {
11163:         foreach my $key (keys(%{$current_permissions})) {
11164:             if ($key =~ /\0accesscontrol$/) {
11165:                 if (defined($group)) {
11166:                     if ($key !~ m-^\Q$group\E/-) {
11167:                         next;
11168:                     }
11169:                 }
11170:                 my ($fullpath) = split(/\0/,$key);
11171:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11172:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11173:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11174:                     }
11175:                 }
11176:             }
11177:         }
11178:     }
11179:     return %access;
11180: }
11181: 
11182: sub modify_access_controls {
11183:     my ($file_name,$changes,$domain,$user)=@_;
11184:     my ($outcome,$deloutcome);
11185:     my %store_permissions;
11186:     my %new_values;
11187:     my %new_control;
11188:     my %translation;
11189:     my @deletions = ();
11190:     my $now = time;
11191:     if (exists($$changes{'activate'})) {
11192:         if (ref($$changes{'activate'}) eq 'HASH') {
11193:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11194:             my $numnew = scalar(@newitems);
11195:             for (my $i=0; $i<$numnew; $i++) {
11196:                 my $newkey = $newitems[$i];
11197:                 my $newid = &Apache::loncommon::get_cgi_id();
11198:                 if ($newkey =~ /^\d+:/) { 
11199:                     $newkey =~ s/^(\d+)/$newid/;
11200:                     $translation{$1} = $newid;
11201:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11202:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11203:                     $translation{$1} = $newid;
11204:                 }
11205:                 $new_values{$file_name."\0".$newkey} = 
11206:                                           $$changes{'activate'}{$newitems[$i]};
11207:                 $new_control{$newkey} = $now;
11208:             }
11209:         }
11210:     }
11211:     my %todelete;
11212:     my %changed_items;
11213:     foreach my $action ('delete','update') {
11214:         if (exists($$changes{$action})) {
11215:             if (ref($$changes{$action}) eq 'HASH') {
11216:                 foreach my $key (keys(%{$$changes{$action}})) {
11217:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11218:                     if ($action eq 'delete') { 
11219:                         $todelete{$itemnum} = 1;
11220:                     } else {
11221:                         $changed_items{$itemnum} = $key;
11222:                     }
11223:                 }
11224:             }
11225:         }
11226:     }
11227:     # get lock on access controls for file.
11228:     my $lockhash = {
11229:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11230:                                                        ':'.$env{'user.domain'},
11231:                    }; 
11232:     my $tries = 0;
11233:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11234:    
11235:     while (($gotlock ne 'ok') && $tries < 10) {
11236:         $tries ++;
11237:         sleep(0.1);
11238:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11239:     }
11240:     if ($gotlock eq 'ok') {
11241:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11242:         my ($tmp)=keys(%curr_permissions);
11243:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11244:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11245:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11246:             if (ref($curr_controls) eq 'HASH') {
11247:                 foreach my $control_item (keys(%{$curr_controls})) {
11248:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11249:                     if (defined($todelete{$itemnum})) {
11250:                         push(@deletions,$file_name."\0".$control_item);
11251:                     } else {
11252:                         if (defined($changed_items{$itemnum})) {
11253:                             $new_control{$changed_items{$itemnum}} = $now;
11254:                             push(@deletions,$file_name."\0".$control_item);
11255:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11256:                         } else {
11257:                             $new_control{$control_item} = $$curr_controls{$control_item};
11258:                         }
11259:                     }
11260:                 }
11261:             }
11262:         }
11263:         my ($group);
11264:         if (&is_course($domain,$user)) {
11265:             ($group,my $file) = split(/\//,$file_name,2);
11266:         }
11267:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11268:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11269:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11270:         #  remove lock
11271:         my @del_lock = ($file_name."\0".'locked_access_records');
11272:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11273:         my $sqlresult =
11274:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11275:                                     $group);
11276:     } else {
11277:         $outcome = "error: could not obtain lockfile\n";  
11278:     }
11279:     return ($outcome,$deloutcome,\%new_values,\%translation);
11280: }
11281: 
11282: sub make_public_indefinitely {
11283:     my (@requrl) = @_;
11284:     return &automated_portfile_access('public',\@requrl);
11285: }
11286: 
11287: sub automated_portfile_access {
11288:     my ($accesstype,$addsref,$delsref,$info) = @_;
11289:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11290:         return 'invalid';
11291:     }
11292:     my %urls;
11293:     if (ref($addsref) eq 'ARRAY') {
11294:         foreach my $requrl (@{$addsref}) {
11295:             if (&is_portfolio_url($requrl)) {
11296:                 unless (exists($urls{$requrl})) {
11297:                     $urls{$requrl} = 'add';
11298:                 }
11299:             }
11300:         }
11301:     }
11302:     if (ref($delsref) eq 'ARRAY') {
11303:         foreach my $requrl (@{$delsref}) { 
11304:             if (&is_portfolio_url($requrl)) {
11305:                 unless (exists($urls{$requrl})) {
11306:                     $urls{$requrl} = 'delete'; 
11307:                 }
11308:             }
11309:         }
11310:     }
11311:     unless (keys(%urls)) {
11312:         return 'invalid';
11313:     }
11314:     my $ip;
11315:     if ($accesstype eq 'ip') {
11316:         if (ref($info) eq 'HASH') {
11317:             if ($info->{'ip'} ne '') {
11318:                 $ip = $info->{'ip'};
11319:             }
11320:         }
11321:         if ($ip eq '') {
11322:             return 'invalid';
11323:         }
11324:     }
11325:     my $errors;
11326:     my $now = time;
11327:     my %current_perms;
11328:     foreach my $requrl (sort(keys(%urls))) {
11329:         my $action;
11330:         if ($urls{$requrl} eq 'add') {
11331:             $action = 'activate';
11332:         } else {
11333:             $action = 'none';
11334:         }
11335:         my $aclnum = 0;
11336:         my (undef,$udom,$unum,$file_name,$group) =
11337:             &parse_portfolio_url($requrl);
11338:         unless (exists($current_perms{$unum.':'.$udom})) {
11339:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11340:         }
11341:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11342:                                                    $group,$file_name);
11343:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11344:             my ($num,$scope,$end,$start) = 
11345:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11346:             if ($scope eq $accesstype) {
11347:                 if (($start <= $now) && ($end == 0)) {
11348:                     if ($accesstype eq 'ip') {
11349:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11350:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11351:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11352:                                     if ($urls{$requrl} eq 'add') {
11353:                                         $action = 'none';
11354:                                         last;
11355:                                     } else {
11356:                                         $action = 'delete';
11357:                                         $aclnum = $num;
11358:                                         last;
11359:                                     }
11360:                                 }
11361:                             }
11362:                         }
11363:                     } elsif ($accesstype eq 'public') {
11364:                         if ($urls{$requrl} eq 'add') {
11365:                             $action = 'none';
11366:                             last;
11367:                         } else {
11368:                             $action = 'delete';
11369:                             $aclnum = $num;
11370:                             last;
11371:                         }
11372:                     }
11373:                 } elsif ($accesstype eq 'public') {
11374:                     $action = 'update';
11375:                     $aclnum = $num;
11376:                     last;
11377:                 }
11378:             }
11379:         }
11380:         if ($action eq 'none') {
11381:             next;
11382:         } else {
11383:             my %changes;
11384:             my $newend = 0;
11385:             my $newstart = $now;
11386:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11387:             $changes{$action}{$newkey} = {
11388:                 type => $accesstype,
11389:                 time => {
11390:                     start => $newstart,
11391:                     end   => $newend,
11392:                 },
11393:             };
11394:             if ($accesstype eq 'ip') {
11395:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11396:             }
11397:             my ($outcome,$deloutcome,$new_values,$translation) =
11398:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11399:             unless ($outcome eq 'ok') {
11400:                 $errors .= $outcome.' ';
11401:             }
11402:         }
11403:     }
11404:     if ($errors) {
11405:         $errors =~ s/\s$//;
11406:         return $errors;
11407:     } else {
11408:         return 'ok';
11409:     }
11410: }
11411: 
11412: #------------------------------------------------------Get Marked as Read Only
11413: 
11414: sub get_marked_as_readonly {
11415:     my ($domain,$user,$what,$group) = @_;
11416:     my $current_permissions = &get_portfile_permissions($domain,$user);
11417:     my @readonly_files;
11418:     my $cmp1=$what;
11419:     if (ref($what)) { $cmp1=join('',@{$what}) };
11420:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11421:         if (defined($group)) {
11422:             if ($file_name !~ m-^\Q$group\E/-) {
11423:                 next;
11424:             }
11425:         }
11426:         if (ref($value) eq "ARRAY"){
11427:             foreach my $stored_what (@{$value}) {
11428:                 my $cmp2=$stored_what;
11429:                 if (ref($stored_what) eq 'ARRAY') {
11430:                     $cmp2=join('',@{$stored_what});
11431:                 }
11432:                 if ($cmp1 eq $cmp2) {
11433:                     push(@readonly_files, $file_name);
11434:                     last;
11435:                 } elsif (!defined($what)) {
11436:                     push(@readonly_files, $file_name);
11437:                     last;
11438:                 }
11439:             }
11440:         }
11441:     }
11442:     return @readonly_files;
11443: }
11444: #-----------------------------------------------------------Get Marked as Read Only Hash
11445: 
11446: sub get_marked_as_readonly_hash {
11447:     my ($current_permissions,$group,$what) = @_;
11448:     my %readonly_files;
11449:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11450:         if (defined($group)) {
11451:             if ($file_name !~ m-^\Q$group\E/-) {
11452:                 next;
11453:             }
11454:         }
11455:         if (ref($value) eq "ARRAY"){
11456:             foreach my $stored_what (@{$value}) {
11457:                 if (ref($stored_what) eq 'ARRAY') {
11458:                     foreach my $lock_descriptor(@{$stored_what}) {
11459:                         if ($lock_descriptor eq 'graded') {
11460:                             $readonly_files{$file_name} = 'graded';
11461:                         } elsif ($lock_descriptor eq 'handback') {
11462:                             $readonly_files{$file_name} = 'handback';
11463:                         } else {
11464:                             if (!exists($readonly_files{$file_name})) {
11465:                                 $readonly_files{$file_name} = 'locked';
11466:                             }
11467:                         }
11468:                     }
11469:                 } 
11470:             }
11471:         } 
11472:     }
11473:     return %readonly_files;
11474: }
11475: # ------------------------------------------------------------ Unmark as Read Only
11476: 
11477: sub unmark_as_readonly {
11478:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11479:     # for portfolio submissions, $what contains [$symb,$crsid] 
11480:     my ($domain,$user,$what,$file_name,$group) = @_;
11481:     $file_name = &declutter_portfile($file_name);
11482:     my $symb_crs = $what;
11483:     if (ref($what)) { $symb_crs=join('',@$what); }
11484:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11485:     my ($tmp)=keys(%current_permissions);
11486:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11487:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11488:     foreach my $file (@readonly_files) {
11489: 	my $clean_file = &declutter_portfile($file);
11490: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11491: 	my $current_locks = $current_permissions{$file};
11492:         my @new_locks;
11493:         my @del_keys;
11494:         if (ref($current_locks) eq "ARRAY"){
11495:             foreach my $locker (@{$current_locks}) {
11496:                 my $compare=$locker;
11497:                 if (ref($locker) eq 'ARRAY') {
11498:                     $compare=join('',@{$locker});
11499:                     if ($compare ne $symb_crs) {
11500:                         push(@new_locks, $locker);
11501:                     }
11502:                 }
11503:             }
11504:             if (scalar(@new_locks) > 0) {
11505:                 $current_permissions{$file} = \@new_locks;
11506:             } else {
11507:                 push(@del_keys, $file);
11508:                 &del('file_permissions',\@del_keys, $domain, $user);
11509:                 delete($current_permissions{$file});
11510:             }
11511:         }
11512:     }
11513:     &put('file_permissions',\%current_permissions,$domain,$user);
11514:     return;
11515: }
11516: 
11517: # ------------------------------------------------------------ Directory lister
11518: 
11519: sub dirlist {
11520:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11521:     $uri=~s/^\///;
11522:     $uri=~s/\/$//;
11523:     my ($udom, $uname);
11524:     if ($getuserdir) {
11525:         $udom = $userdomain;
11526:         $uname = $username;
11527:     } else {
11528:         (undef,$udom,$uname)=split(/\//,$uri);
11529:         if(defined($userdomain)) {
11530:             $udom = $userdomain;
11531:         }
11532:         if(defined($username)) {
11533:             $uname = $username;
11534:         }
11535:     }
11536:     my ($dirRoot,$listing,@listing_results);
11537: 
11538:     $dirRoot = $perlvar{'lonDocRoot'};
11539:     if (defined($getpropath)) {
11540:         $dirRoot = &propath($udom,$uname);
11541:         $dirRoot =~ s/\/$//;
11542:     } elsif (defined($getuserdir)) {
11543:         my $subdir=$uname.'__';
11544:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11545:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11546:                    ."/$udom/$subdir/$uname";
11547:     } elsif (defined($alternateRoot)) {
11548:         $dirRoot = $alternateRoot;
11549:     }
11550: 
11551:     if($udom) {
11552:         if($uname) {
11553:             my $uhome = &homeserver($uname,$udom);
11554:             if ($uhome eq 'no_host') {
11555:                 return ([],'no_host');
11556:             }
11557:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11558:                               .$getuserdir.':'.&escape($dirRoot)
11559:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11560:             if ($listing eq 'unknown_cmd') {
11561:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11562:             } else {
11563:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11564:             }
11565:             if ($listing eq 'unknown_cmd') {
11566:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11567:                 @listing_results = split(/:/,$listing);
11568:             } else {
11569:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11570:             }
11571:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11572:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11573:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11574:                 return ([],$listing);
11575:             } else {
11576:                 return (\@listing_results);
11577:             }
11578:         } elsif(!$alternateRoot) {
11579:             my (%allusers,%listerror);
11580: 	    my %servers = &get_servers($udom,'library');
11581:  	    foreach my $tryserver (keys(%servers)) {
11582:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11583:                                   &escape($udom),$tryserver);
11584:                 if ($listing eq 'unknown_cmd') {
11585: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11586: 				      $udom, $tryserver);
11587:                 } else {
11588:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11589:                 }
11590: 		if ($listing eq 'unknown_cmd') {
11591: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11592: 				      $udom, $tryserver);
11593: 		    @listing_results = split(/:/,$listing);
11594: 		} else {
11595: 		    @listing_results =
11596: 			map { &unescape($_); } split(/:/,$listing);
11597: 		}
11598:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11599:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11600:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11601:                     $listerror{$tryserver} = $listing;
11602:                 } else {
11603: 		    foreach my $line (@listing_results) {
11604: 			my ($entry) = split(/&/,$line,2);
11605: 			$allusers{$entry} = 1;
11606: 		    }
11607: 		}
11608:             }
11609:             my @alluserslist=();
11610:             foreach my $user (sort(keys(%allusers))) {
11611:                 push(@alluserslist,$user.'&user');
11612:             }
11613: 
11614:             if (!%listerror) {
11615:                 # no errors
11616:                 return (\@alluserslist);
11617:             } elsif (scalar(keys(%servers)) == 1) {
11618:                 # one library server, one error 
11619:                 my ($key) = keys(%listerror);
11620:                 return (\@alluserslist, $listerror{$key});
11621:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11622:                 # con_lost indicates that we might miss data from at least one
11623:                 # library server
11624:                 return (\@alluserslist, 'con_lost');
11625:             } else {
11626:                 # multiple library servers and no con_lost -> data should be
11627:                 # complete. 
11628:                 return (\@alluserslist);
11629:             }
11630: 
11631:         } else {
11632:             return ([],'missing username');
11633:         }
11634:     } elsif(!defined($getpropath)) {
11635:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11636:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11637:         return (\@all_domains);
11638:     } else {
11639:         return ([],'missing domain');
11640:     }
11641: }
11642: 
11643: # --------------------------------------------- GetFileTimestamp
11644: # This function utilizes dirlist and returns the date stamp for
11645: # when it was last modified.  It will also return an error of -1
11646: # if an error occurs
11647: 
11648: sub GetFileTimestamp {
11649:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11650:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11651:     $studentName   = &LONCAPA::clean_username($studentName);
11652:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11653:                                     undef,$getuserdir);
11654:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11655:         return -1;
11656:     }
11657:     if (ref($fileref) eq 'ARRAY') {
11658:         my @stats = split('&',$fileref->[0]);
11659:         # @stats contains first the filename, then the stat output
11660:         return $stats[10]; # so this is 10 instead of 9.
11661:     } else {
11662:         return -1;
11663:     }
11664: }
11665: 
11666: sub stat_file {
11667:     my ($uri) = @_;
11668:     $uri = &clutter_with_no_wrapper($uri);
11669: 
11670:     my ($udom,$uname,$file);
11671:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11672: 	($udom,$uname,$file) =
11673: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11674: 	$file = 'userfiles/'.$file;
11675:     }
11676:     if ($uri =~ m-^/res/-) {
11677: 	($udom,$uname) = 
11678: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11679: 	$file = $uri;
11680:     }
11681: 
11682:     if (!$udom || !$uname || !$file) {
11683: 	# unable to handle the uri
11684: 	return ();
11685:     }
11686:     my $getpropath;
11687:     if ($file =~ /^userfiles\//) {
11688:         $getpropath = 1;
11689:     }
11690:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11691:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11692:         return ();
11693:     } else {
11694:         if (ref($listref) eq 'ARRAY') {
11695:             my @stats = split('&',$listref->[0]);
11696: 	    shift(@stats); #filename is first
11697: 	    return @stats;
11698:         }
11699:     }
11700:     return ();
11701: }
11702: 
11703: # --------------------------------------------------------- recursedirs
11704: # Recursive function to traverse either a specific user's Authoring Space
11705: # or corresponding Published Resource Space, and populate the hash ref:
11706: # $dirhashref with URLs of all directories, and if $filehashref hash
11707: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11708: # or .rights files in resource space, and .meta, .save, .log, and .bak
11709: # files in Authoring Space.
11710: #
11711: # Inputs:
11712: #
11713: # $is_home - true if current server is home server for user's space
11714: # $context - either: priv, or res respectively for Authoring or Resource Space.
11715: # $docroot - Document root (i.e., /home/httpd/html
11716: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11717: # $relpath - Current path (relative to top level).
11718: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11719: # $filehashref - reference to hash to populate with URLs of files (Optional)
11720: #
11721: # Returns: nothing
11722: #
11723: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11724: #
11725: # Currently used by interface/londocs.pm to create linked select boxes for
11726: # directory and filename to import a Course "Author" resource into a course, and
11727: # also to create linked select boxes for Authoring Space and Directory to choose
11728: # save location for creation of a new "standard" problem from the Course Editor.
11729: #
11730: 
11731: sub recursedirs {
11732:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11733:     return unless (ref($dirhashref) eq 'HASH');
11734:     my $currpath = $docroot.$toppath;
11735:     if ($relpath) {
11736:         $currpath .= "/$relpath";
11737:     }
11738:     my $savefile;
11739:     if (ref($filehashref)) {
11740:         $savefile = 1;
11741:     }
11742:     if ($is_home) {
11743:         if (opendir(my $dirh,$currpath)) {
11744:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11745:                 next if ($item eq '');
11746:                 if (-d "$currpath/$item") {
11747:                     my $newpath;
11748:                     if ($relpath) {
11749:                         $newpath = "$relpath/$item";
11750:                     } else {
11751:                         $newpath = $item;
11752:                     }
11753:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11754:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11755:                 } elsif ($savefile) {
11756:                     if ($context eq 'priv') {
11757:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11758:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11759:                         }
11760:                     } else {
11761:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11762:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11763:                         }
11764:                     }
11765:                 }
11766:             }
11767:             closedir($dirh);
11768:         }
11769:     } else {
11770:         my ($dirlistref,$listerror) =
11771:             &dirlist($toppath.$relpath);
11772:         my @dir_lines;
11773:         my $dirptr=16384;
11774:         if (ref($dirlistref) eq 'ARRAY') {
11775:             foreach my $dir_line (sort
11776:                               {
11777:                                   my ($afile)=split('&',$a,2);
11778:                                   my ($bfile)=split('&',$b,2);
11779:                                   return (lc($afile) cmp lc($bfile));
11780:                               } (@{$dirlistref})) {
11781:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11782:                     split(/\&/,$dir_line,16);
11783:                 $item =~ s/\s+$//;
11784:                 next if (($item =~ /^\.\.?$/) || ($obs));
11785:                 if ($dirptr&$testdir) {
11786:                     my $newpath;
11787:                     if ($relpath) {
11788:                         $newpath = "$relpath/$item";
11789:                     } else {
11790:                         $relpath = '/';
11791:                         $newpath = $item;
11792:                     }
11793:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11794:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11795:                 } elsif ($savefile) {
11796:                     if ($context eq 'priv') {
11797:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11798:                             $filehashref->{$relpath}{$item} = 1;
11799:                         }
11800:                     } else {
11801:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11802:                             $filehashref->{$relpath}{$item} = 1;
11803:                         }
11804:                     }
11805:                 }
11806:             }
11807:         }
11808:     }
11809:     return;
11810: }
11811: 
11812: # -------------------------------------------------------- Value of a Condition
11813: 
11814: # gets the value of a specific preevaluated condition
11815: #    stored in the string  $env{user.state.<cid>}
11816: # or looks up a condition reference in the bighash and if if hasn't
11817: # already been evaluated recurses into docondval to get the value of
11818: # the condition, then memoizing it to 
11819: #   $env{user.state.<cid>.<condition>}
11820: sub directcondval {
11821:     my $number=shift;
11822:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11823: 	&Apache::lonuserstate::evalstate();
11824:     }
11825:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11826: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11827:     } elsif ($number =~ /^_/) {
11828: 	my $sub_condition;
11829: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11830: 		&GDBM_READER(),0640)) {
11831: 	    $sub_condition=$bighash{'conditions'.$number};
11832: 	    untie(%bighash);
11833: 	}
11834: 	my $value = &docondval($sub_condition);
11835: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11836: 	return $value;
11837:     }
11838:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11839:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11840:     } else {
11841:        return 2;
11842:     }
11843: }
11844: 
11845: # get the collection of conditions for this resource
11846: sub condval {
11847:     my $condidx=shift;
11848:     my $allpathcond='';
11849:     foreach my $cond (split(/\|/,$condidx)) {
11850: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11851: 	    $allpathcond.=
11852: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11853: 	}
11854:     }
11855:     $allpathcond=~s/\|$//;
11856:     return &docondval($allpathcond);
11857: }
11858: 
11859: #evaluates an expression of conditions
11860: sub docondval {
11861:     my ($allpathcond) = @_;
11862:     my $result=0;
11863:     if ($env{'request.course.id'}
11864: 	&& defined($allpathcond)) {
11865: 	my $operand='|';
11866: 	my @stack;
11867: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11868: 	    if ($chunk eq '(') {
11869: 		push @stack,($operand,$result);
11870: 	    } elsif ($chunk eq ')') {
11871: 		my $before=pop @stack;
11872: 		if (pop @stack eq '&') {
11873: 		    $result=$result>$before?$before:$result;
11874: 		} else {
11875: 		    $result=$result>$before?$result:$before;
11876: 		}
11877: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11878: 		$operand=$chunk;
11879: 	    } else {
11880: 		my $new=directcondval($chunk);
11881: 		if ($operand eq '&') {
11882: 		    $result=$result>$new?$new:$result;
11883: 		} else {
11884: 		    $result=$result>$new?$result:$new;
11885: 		}
11886: 	    }
11887: 	}
11888:     }
11889:     return $result;
11890: }
11891: 
11892: # ---------------------------------------------------- Devalidate courseresdata
11893: 
11894: sub devalidatecourseresdata {
11895:     my ($coursenum,$coursedomain)=@_;
11896:     my $hashid=$coursenum.':'.$coursedomain;
11897:     &devalidate_cache_new('courseres',$hashid);
11898: }
11899: 
11900: 
11901: # --------------------------------------------------- Course Resourcedata Query
11902: #
11903: #  Parameters:
11904: #      $coursenum    - Number of the course.
11905: #      $coursedomain - Domain at which the course was created.
11906: #  Returns:
11907: #     A hash of the course parameters along (I think) with timestamps
11908: #     and version info.
11909: 
11910: sub get_courseresdata {
11911:     my ($coursenum,$coursedomain)=@_;
11912:     my $coursehom=&homeserver($coursenum,$coursedomain);
11913:     my $hashid=$coursenum.':'.$coursedomain;
11914:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11915:     my %dumpreply;
11916:     unless (defined($cached)) {
11917: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11918: 	$result=\%dumpreply;
11919: 	my ($tmp) = keys(%dumpreply);
11920: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11921: 	    &do_cache_new('courseres',$hashid,$result,600);
11922: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11923: 	    return $tmp;
11924: 	} elsif ($tmp =~ /^(error)/) {
11925: 	    $result=undef;
11926: 	    &do_cache_new('courseres',$hashid,$result,600);
11927: 	}
11928:     }
11929:     return $result;
11930: }
11931: 
11932: sub devalidateuserresdata {
11933:     my ($uname,$udom)=@_;
11934:     my $hashid="$udom:$uname";
11935:     &devalidate_cache_new('userres',$hashid);
11936: }
11937: 
11938: sub get_userresdata {
11939:     my ($uname,$udom)=@_;
11940:     #most student don\'t have any data set, check if there is some data
11941:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11942: 
11943:     my $hashid="$udom:$uname";
11944:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11945:     if (!defined($cached)) {
11946: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11947: 	$result=\%resourcedata;
11948: 	&do_cache_new('userres',$hashid,$result,600);
11949:     }
11950:     my ($tmp)=keys(%$result);
11951:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11952: 	return $result;
11953:     }
11954:     #error 2 occurs when the .db doesn't exist
11955:     if ($tmp!~/error: 2 /) {
11956:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11957: 	    &logthis("<font color=\"blue\">WARNING:".
11958: 		     " Trying to get resource data for ".
11959: 		     $uname." at ".$udom.": ".
11960: 		     $tmp."</font>");
11961:         }
11962:     } elsif ($tmp=~/error: 2 /) {
11963: 	#&EXT_cache_set($udom,$uname);
11964: 	&do_cache_new('userres',$hashid,undef,600);
11965: 	undef($tmp); # not really an error so don't send it back
11966:     }
11967:     return $tmp;
11968: }
11969: #----------------------------------------------- resdata - return resource data
11970: #  Purpose:
11971: #    Return resource data for either users or for a course.
11972: #  Parameters:
11973: #     $name      - Course/user name.
11974: #     $domain    - Name of the domain the user/course is registered on.
11975: #     $type      - Type of thing $name is (must be 'course' or 'user')
11976: #     $mapp      - decluttered URL of enclosing map  
11977: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11978: #     $recurseup - Ref to array of map URLs, starting with map containing
11979: #                  $mapp up through hierarchy of nested maps to top level map.  
11980: #     $courseid  - CourseID (first part of param identifier).
11981: #     $modifier  - Middle part of param identifier.
11982: #     $what      - Last part of param identifier.
11983: #     @which     - Array of names of resources desired.
11984: #  Returns:
11985: #     The value of the first reasource in @which that is found in the
11986: #     resource hash.
11987: #  Exceptional Conditions:
11988: #     If the $type passed in is not valid (not the string 'course' or 
11989: #     'user', an undefined  reference is returned.
11990: #     If none of the resources are found, an undef is returned
11991: sub resdata {
11992:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11993:         $modifier,$what,@which)=@_;
11994:     my $result;
11995:     if ($type eq 'course') {
11996: 	$result=&get_courseresdata($name,$domain);
11997:     } elsif ($type eq 'user') {
11998: 	$result=&get_userresdata($name,$domain);
11999:     }
12000:     if (!ref($result)) { return $result; }    
12001:     foreach my $item (@which) {
12002:         if ($item->[1] eq 'course') {
12003:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12004:                 unless ($$recursed) {
12005:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12006:                     $$recursed = 1;
12007:                 }
12008:                 foreach my $item (@${recurseup}) {
12009:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12010:                     last if (defined($result->{$norecursechk}));
12011:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12012:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12013:                 }
12014:             }
12015:         }
12016:         if (defined($result->{$item->[0]})) {
12017: 	    return [$result->{$item->[0]},$item->[1]];
12018: 	}
12019:     }
12020:     return undef;
12021: }
12022: 
12023: sub get_domain_lti {
12024:     my ($cdom,$context) = @_;
12025:     my ($name,%lti);
12026:     if ($context eq 'consumer') {
12027:         $name = 'ltitools';
12028:     } elsif ($context eq 'provider') {
12029:         $name = 'lti';
12030:     } else {
12031:         return %lti;
12032:     }
12033:     my ($result,$cached)=&is_cached_new($name,$cdom);
12034:     if (defined($cached)) {
12035:         if (ref($result) eq 'HASH') {
12036:             %lti = %{$result};
12037:         }
12038:     } else {
12039:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12040:         if (ref($domconfig{$name}) eq 'HASH') {
12041:             %lti = %{$domconfig{$name}};
12042:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
12043:             if (ref($encdomconfig{$name}) eq 'HASH') {
12044:                 foreach my $id (keys(%lti)) {
12045:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12046:                         foreach my $item ('key','secret') {
12047:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12048:                         }
12049:                     }
12050:                 }
12051:             }
12052:         }
12053:         my $cachetime = 24*60*60;
12054:         &do_cache_new($name,$cdom,\%lti,$cachetime);
12055:     }
12056:     return %lti;
12057: }
12058: 
12059: sub get_numsuppfiles {
12060:     my ($cnum,$cdom,$ignorecache)=@_;
12061:     my $hashid=$cnum.':'.$cdom;
12062:     my ($suppcount,$cached);
12063:     unless ($ignorecache) {
12064:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12065:     }
12066:     unless (defined($cached)) {
12067:         my $chome=&homeserver($cnum,$cdom);
12068:         unless ($chome eq 'no_host') {
12069:             ($suppcount,my $supptools,my $errors) = (0,0,0);
12070:             my $suppmap = 'supplemental.sequence';
12071:             ($suppcount,$supptools,$errors) =
12072:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12073:                                                          $supptools,$errors);
12074:         }
12075:         &do_cache_new('suppcount',$hashid,$suppcount,600);
12076:     }
12077:     return $suppcount;
12078: }
12079: 
12080: #
12081: # EXT resource caching routines
12082: #
12083: 
12084: {
12085: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12086: #
12087: # The course for which we cache
12088: my $cachedmapkey='';
12089: # The cached recursive maps for this course
12090: my %cachedmaps=();
12091: # When this was last done
12092: my $cachedmaptime='';
12093: 
12094: sub clear_EXT_cache_status {
12095:     &delenv('cache.EXT.');
12096: }
12097: 
12098: sub EXT_cache_status {
12099:     my ($target_domain,$target_user) = @_;
12100:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12101:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12102:         # We know already the user has no data
12103:         return 1;
12104:     } else {
12105:         return 0;
12106:     }
12107: }
12108: 
12109: sub EXT_cache_set {
12110:     my ($target_domain,$target_user) = @_;
12111:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12112:     #&appenv({$cachename => time});
12113: }
12114: 
12115: # --------------------------------------------------------- Value of a Variable
12116: sub EXT {
12117: 
12118:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
12119:     unless ($varname) { return ''; }
12120:     #get real user name/domain, courseid and symb
12121:     my $courseid;
12122:     my $publicuser;
12123:     if ($symbparm) {
12124: 	$symbparm=&get_symb_from_alias($symbparm);
12125:     }
12126:     if (!($uname && $udom)) {
12127:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12128:       if (!$symbparm) {	$symbparm=$cursymb; }
12129:     } else {
12130: 	$courseid=$env{'request.course.id'};
12131:     }
12132:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12133:     my $rest;
12134:     if (defined($therest[0])) {
12135:        $rest=join('.',@therest);
12136:     } else {
12137:        $rest='';
12138:     }
12139: 
12140:     my $qualifierrest=$qualifier;
12141:     if ($rest) { $qualifierrest.='.'.$rest; }
12142:     my $spacequalifierrest=$space;
12143:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12144:     if ($realm eq 'user') {
12145: # --------------------------------------------------------------- user.resource
12146: 	if ($space eq 'resource') {
12147: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12148: 		  || defined($Apache::lonhomework::parsing_a_task))
12149: 		 &&
12150: 		 ($symbparm eq &symbread()) ) {	
12151: 		# if we are in the middle of processing the resource the
12152: 		# get the value we are planning on committing
12153:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12154:                     return $Apache::lonhomework::results{$qualifierrest};
12155:                 } else {
12156:                     return $Apache::lonhomework::history{$qualifierrest};
12157:                 }
12158: 	    } else {
12159: 		my %restored;
12160: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12161: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12162: 		} else {
12163: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12164: 		}
12165: 		return $restored{$qualifierrest};
12166: 	    }
12167: # ----------------------------------------------------------------- user.access
12168:         } elsif ($space eq 'access') {
12169: 	    # FIXME - not supporting calls for a specific user
12170:             return &allowed($qualifier,$rest);
12171: # ------------------------------------------ user.preferences, user.environment
12172:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12173: 	    if (($uname eq $env{'user.name'}) &&
12174: 		($udom eq $env{'user.domain'})) {
12175: 		return $env{join('.',('environment',$qualifierrest))};
12176: 	    } else {
12177: 		my %returnhash;
12178: 		if (!$publicuser) {
12179: 		    %returnhash=&userenvironment($udom,$uname,
12180: 						 $qualifierrest);
12181: 		}
12182: 		return $returnhash{$qualifierrest};
12183: 	    }
12184: # ----------------------------------------------------------------- user.course
12185:         } elsif ($space eq 'course') {
12186: 	    # FIXME - not supporting calls for a specific user
12187:             return $env{join('.',('request.course',$qualifier))};
12188: # ------------------------------------------------------------------- user.role
12189:         } elsif ($space eq 'role') {
12190: 	    # FIXME - not supporting calls for a specific user
12191:             my ($role,$where)=split(/\./,$env{'request.role'});
12192:             if ($qualifier eq 'value') {
12193: 		return $role;
12194:             } elsif ($qualifier eq 'extent') {
12195:                 return $where;
12196:             }
12197: # ----------------------------------------------------------------- user.domain
12198:         } elsif ($space eq 'domain') {
12199:             return $udom;
12200: # ------------------------------------------------------------------- user.name
12201:         } elsif ($space eq 'name') {
12202:             return $uname;
12203: # ---------------------------------------------------- Any other user namespace
12204:         } else {
12205: 	    my %reply;
12206: 	    if (!$publicuser) {
12207: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12208: 	    }
12209: 	    return $reply{$qualifierrest};
12210:         }
12211:     } elsif ($realm eq 'query') {
12212: # ---------------------------------------------- pull stuff out of query string
12213:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12214: 						[$spacequalifierrest]);
12215: 	return $env{'form.'.$spacequalifierrest}; 
12216:    } elsif ($realm eq 'request') {
12217: # ------------------------------------------------------------- request.browser
12218:         if ($space eq 'browser') {
12219:             return $env{'browser.'.$qualifier};
12220: # ------------------------------------------------------------ request.filename
12221:         } else {
12222:             return $env{'request.'.$spacequalifierrest};
12223:         }
12224:     } elsif ($realm eq 'course') {
12225: # ---------------------------------------------------------- course.description
12226:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12227:     } elsif ($realm eq 'resource') {
12228: 
12229: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12230: 	    if (!$symbparm) { $symbparm=&symbread(); }
12231: 	}
12232: 
12233:         if ($qualifier eq '') {
12234: 	    if ($space eq 'title') {
12235: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12236: 	        return &gettitle($symbparm);
12237: 	    }
12238: 	
12239: 	    if ($space eq 'map') {
12240: 	        my ($map) = &decode_symb($symbparm);
12241: 	        return &symbread($map);
12242: 	    }
12243:             if ($space eq 'maptitle') {
12244:                 my ($map) = &decode_symb($symbparm);
12245:                 return &gettitle($map);
12246:             }
12247: 	    if ($space eq 'filename') {
12248: 	        if ($symbparm) {
12249: 		    return &clutter((&decode_symb($symbparm))[2]);
12250: 	        }
12251: 	        return &hreflocation('',$env{'request.filename'});
12252: 	    }
12253: 
12254:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12255:                 if ($space eq 'visibleparts') {
12256:                     my $navmap = Apache::lonnavmaps::navmap->new();
12257:                     my $item;
12258:                     if (ref($navmap)) {
12259:                         my $res = $navmap->getBySymb($symbparm);
12260:                         my $parts = $res->parts();
12261:                         if (ref($parts) eq 'ARRAY') {
12262:                             $item = join(',',@{$parts});
12263:                         }
12264:                         undef($navmap);
12265:                     }
12266:                     return $item;
12267:                 }
12268:             }
12269:         }
12270: 
12271: 	my ($section, $group, @groups, @recurseup, $recursed);
12272: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12273:         if (($courseid eq '') && ($cid)) {
12274:             $courseid = $cid;
12275:         }
12276: 	if (($symbparm && $courseid) && 
12277: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12278: 
12279: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12280: 
12281: # ----------------------------------------------------- Cascading lookup scheme
12282: 	    my $symbp=$symbparm;
12283: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12284: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12285:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12286: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12287: 	    if (($env{'user.name'} eq $uname) &&
12288: 		($env{'user.domain'} eq $udom)) {
12289: 		$section=$env{'request.course.sec'};
12290:                 @groups = split(/:/,$env{'request.course.groups'});  
12291:                 @groups=&sort_course_groups($courseid,@groups); 
12292: 	    } else {
12293: 		if (! defined($usection)) {
12294: 		    $section=&getsection($udom,$uname,$courseid);
12295: 		} else {
12296: 		    $section = $usection;
12297: 		}
12298:                 @groups = &get_users_groups($udom,$uname,$courseid);
12299: 	    }
12300: 
12301: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12302: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12303:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12304: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12305: 
12306: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12307: 	    my $courselevelr=$courseid.'.'.$symbparm;
12308:             $courseleveli=$courseid.'.'.$recurseparm;
12309: 	    $courselevelm=$courseid.'.'.$mapparm;
12310: 
12311: # ----------------------------------------------------------- first, check user
12312: 
12313: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12314:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12315: 				       ([$courselevelr,'resource'],
12316: 					[$courselevelm,'map'     ],
12317:                                         [$courseleveli,'map'     ],
12318: 					[$courselevel, 'course'  ]));
12319: 	    if (defined($userreply)) { return &get_reply($userreply); }
12320: 
12321: # ------------------------------------------------ second, check some of course
12322:             my $coursereply;
12323:             if (@groups > 0) {
12324:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12325:                                        $recurseparm,$mapparm,$spacequalifierrest,
12326:                                        $mapp,\$recursed,\@recurseup);
12327:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12328:             }
12329: 
12330: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12331: 				  $env{'course.'.$courseid.'.domain'},
12332: 				  'course',$mapp,\$recursed,\@recurseup,
12333:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12334: 				  ([$seclevelr,   'resource'],
12335: 				   [$seclevelm,   'map'     ],
12336:                                    [$secleveli,   'map'     ],
12337: 				   [$seclevel,    'course'  ],
12338: 				   [$courselevelr,'resource']));
12339: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12340: 
12341: # ------------------------------------------------------ third, check map parms
12342: 	    my %parmhash=();
12343: 	    my $thisparm='';
12344: 	    if (tie(%parmhash,'GDBM_File',
12345: 		    $env{'request.course.fn'}.'_parms.db',
12346: 		    &GDBM_READER(),0640)) {
12347: 		$thisparm=$parmhash{$symbparm};
12348: 		untie(%parmhash);
12349: 	    }
12350: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12351: 	}
12352: # ------------------------------------------ fourth, look in resource metadata
12353:  
12354:         my $what = $spacequalifierrest;
12355: 	$what=~s/\./\_/;
12356: 	my $filename;
12357: 	if (!$symbparm) { $symbparm=&symbread(); }
12358: 	if ($symbparm) {
12359: 	    $filename=(&decode_symb($symbparm))[2];
12360: 	} else {
12361: 	    $filename=$env{'request.filename'};
12362: 	}
12363:         my $toolsymb;
12364:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12365:             $toolsymb = $symbparm;
12366:         }
12367: 	my $metadata=&metadata($filename,$what,$toolsymb);
12368: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12369: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12370: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12371: 
12372: # ----------------------------------------------- fifth, look in rest of course
12373: 	if ($symbparm && defined($courseid) && 
12374: 	    $courseid eq $env{'request.course.id'}) {
12375: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12376: 				     $env{'course.'.$courseid.'.domain'},
12377: 				     'course',$mapp,\$recursed,\@recurseup,
12378:                                      $courseid,'.',$spacequalifierrest,
12379: 				     ([$courselevelm,'map'   ],
12380:                                       [$courseleveli,'map'   ],
12381: 				      [$courselevel, 'course']));
12382: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12383: 	}
12384: # ------------------------------------------------------------------ Cascade up
12385: 	unless ($space eq '0') {
12386: 	    my @parts=split(/_/,$space);
12387: 	    my $id=pop(@parts);
12388: 	    my $part=join('_',@parts);
12389: 	    if ($part eq '') { $part='0'; }
12390: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12391: 				 $symbparm,$udom,$uname,$section,1);
12392: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12393: 	}
12394: 	if ($recurse) { return undef; }
12395: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12396: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12397: # ---------------------------------------------------- Any other user namespace
12398:     } elsif ($realm eq 'environment') {
12399: # ----------------------------------------------------------------- environment
12400: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12401: 	    return $env{'environment.'.$spacequalifierrest};
12402: 	} else {
12403: 	    if ($uname eq 'anonymous' && $udom eq '') {
12404: 		return '';
12405: 	    }
12406: 	    my %returnhash=&userenvironment($udom,$uname,
12407: 					    $spacequalifierrest);
12408: 	    return $returnhash{$spacequalifierrest};
12409: 	}
12410:     } elsif ($realm eq 'system') {
12411: # ----------------------------------------------------------------- system.time
12412: 	if ($space eq 'time') {
12413: 	    return time;
12414:         }
12415:     } elsif ($realm eq 'server') {
12416: # ----------------------------------------------------------------- system.time
12417: 	if ($space eq 'name') {
12418: 	    return $ENV{'SERVER_NAME'};
12419:         }
12420:     } elsif ($realm eq 'client') {
12421:         if ($space eq 'remote_addr') {
12422:             return &get_requestor_ip();
12423:         }
12424:     }
12425:     return '';
12426: }
12427: 
12428: sub get_reply {
12429:     my ($reply_value) = @_;
12430:     if (ref($reply_value) eq 'ARRAY') {
12431:         if (wantarray) {
12432: 	    return @$reply_value;
12433:         }
12434:         return $reply_value->[0];
12435:     } else {
12436:         return $reply_value;
12437:     }
12438: }
12439: 
12440: sub check_group_parms {
12441:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12442:         $recursed,$recurseupref) = @_;
12443:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12444:                   [$what,'course']);
12445:     my $coursereply;
12446:     foreach my $group (@{$groups}) {
12447:         my @groupitems = ();
12448:         foreach my $level (@levels) {
12449:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12450:              push(@groupitems,[$item,$level->[1]]);
12451:         }
12452:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12453:                                    $env{'course.'.$courseid.'.domain'},
12454:                                    'course',$mapp,$recursed,$recurseupref,
12455:                                    $courseid,'.['.$group.'].',$what,
12456:                                    @groupitems);
12457:         last if (defined($coursereply));
12458:     }
12459:     return $coursereply;
12460: }
12461: 
12462: sub get_map_hierarchy {
12463:     my ($mapname,$courseid) = @_;
12464:     my @recurseup = ();
12465:     if ($mapname) {
12466:         if (($cachedmapkey eq $courseid) &&
12467:             (abs($cachedmaptime-time)<5)) {
12468:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12469:                 return @{$cachedmaps{$mapname}};
12470:             }
12471:         }
12472:         my $navmap = Apache::lonnavmaps::navmap->new();
12473:         if (ref($navmap)) {
12474:             @recurseup = $navmap->recurseup_maps($mapname);
12475:             undef($navmap);
12476:             $cachedmaps{$mapname} = \@recurseup;
12477:             $cachedmaptime=time;
12478:             $cachedmapkey=$courseid;
12479:         }
12480:     }
12481:     return @recurseup;
12482: }
12483: 
12484: }
12485: 
12486: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12487:     my ($courseid,@groups) = @_;
12488:     @groups = sort(@groups);
12489:     return @groups;
12490: }
12491: 
12492: sub packages_tab_default {
12493:     my ($uri,$varname,$toolsymb)=@_;
12494:     my (undef,$part,$name)=split(/\./,$varname);
12495: 
12496:     my (@extension,@specifics,$do_default);
12497:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12498: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12499: 	if ($pack_type eq 'default') {
12500: 	    $do_default=1;
12501: 	} elsif ($pack_type eq 'extension') {
12502: 	    push(@extension,[$package,$pack_type,$pack_part]);
12503: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12504: 	    # only look at packages defaults for packages that this id is
12505: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12506: 	}
12507:     }
12508:     # first look for a package that matches the requested part id
12509:     foreach my $package (@specifics) {
12510: 	my (undef,$pack_type,$pack_part)=@{$package};
12511: 	next if ($pack_part ne $part);
12512: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12513: 	    return $packagetab{"$pack_type&$name&default"};
12514: 	}
12515:     }
12516:     # look for any possible matching non extension_ package
12517:     foreach my $package (@specifics) {
12518: 	my (undef,$pack_type,$pack_part)=@{$package};
12519: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12520: 	    return $packagetab{"$pack_type&$name&default"};
12521: 	}
12522: 	if ($pack_type eq 'part') { $pack_part='0'; }
12523: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12524: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12525: 	}
12526:     }
12527:     # look for any posible extension_ match
12528:     foreach my $package (@extension) {
12529: 	my ($package,$pack_type)=@{$package};
12530: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12531: 	    return $packagetab{"$pack_type&$name&default"};
12532: 	}
12533: 	if (defined($packagetab{$package."&$name&default"})) {
12534: 	    return $packagetab{$package."&$name&default"};
12535: 	}
12536:     }
12537:     # look for a global default setting
12538:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12539: 	return $packagetab{"default&$name&default"};
12540:     }
12541:     return undef;
12542: }
12543: 
12544: sub add_prefix_and_part {
12545:     my ($prefix,$part)=@_;
12546:     my $keyroot;
12547:     if (defined($prefix) && $prefix !~ /^__/) {
12548: 	# prefix that has a part already
12549: 	$keyroot=$prefix;
12550:     } elsif (defined($prefix)) {
12551: 	# prefix that is missing a part
12552: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12553:     } else {
12554: 	# no prefix at all
12555: 	if (defined($part)) { $keyroot='_'.$part; }
12556:     }
12557:     return $keyroot;
12558: }
12559: 
12560: # ---------------------------------------------------------------- Get metadata
12561: 
12562: my %metaentry;
12563: my %importedpartids;
12564: my %importedrespids;
12565: sub metadata {
12566:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12567:     $uri=&declutter($uri);
12568:     # if it is a non metadata possible uri return quickly
12569:     if (($uri eq '') || 
12570: 	(($uri =~ m|^/*adm/|) && 
12571: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12572:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12573: 	return undef;
12574:     }
12575:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12576: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12577: 	return undef;
12578:     }
12579:     my $filename=$uri;
12580:     $uri=~s/\.meta$//;
12581: #
12582: # Is the metadata already cached?
12583: # Look at timestamp of caching
12584: # Everything is cached by the main uri, libraries are never directly cached
12585: #
12586:     if (!defined($liburi)) {
12587: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12588: 	if (defined($cached)) { return $result->{':'.$what}; }
12589:     }
12590: 
12591: #
12592: # If the uri is for an external tool the file from
12593: # which metadata should be retrieved depends on whether
12594: # the tool had been configured to be gradable (set in the Course
12595: # Editor or Resource Editor).
12596: #
12597: # If a valid symb has been included as the third arg in the call
12598: # to &metadata() that can be used to retrieve the value of
12599: # parameter_0_gradable set for the resource, and included in the
12600: # uploaded map containing the tool. The value is retrieved via
12601: # &EXT(), if a valid symb is available.  Otherwise the value of
12602: # gradable in the exttool_$marker.db file for the tool instance
12603: # is retrieved via &get().
12604: #
12605: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12606: # hiddenresource and encrypturl (during course initialization)
12607: # the map-level parameter for resource.0.gradable included in the 
12608: # uploaded map containing the tool will not yet have been stored
12609: # in the user_course_parms.db file for the user's session, so in 
12610: # this case fall back to retrieving gradable status from the
12611: # exttool_$marker.db file.
12612: #
12613: # In order to avoid an infinite loop, &metadata() will return
12614: # before a call to &EXT(), if the uri is for an external tool
12615: # and the $what for which metadata is being requested is
12616: # parameter_0_gradable or 0_gradable.
12617: #
12618: 
12619:     if ($uri =~ /ext\.tool$/) {
12620:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12621:             return;
12622:         } else {
12623:             my ($checked,$use_passback);
12624:             if ($toolsymb ne '') {
12625:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12626:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12627:                     $checked = 1;
12628:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12629:                         $use_passback = 1;
12630:                     }
12631:                 }
12632:             }
12633:             unless ($checked) {
12634:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12635:                 $marker=~s/\D//g;
12636:                 if ($marker) {
12637:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12638:                     $use_passback = $toolsettings{'gradable'};
12639:                 }
12640:             }
12641:             if ($use_passback) {
12642:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12643:             } else {
12644:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12645:             }
12646:         }
12647:     }
12648: 
12649:     {
12650: # Imported parts would go here
12651:         my @origfiletagids=();
12652:         my $importedparts=0;
12653: 
12654: # Imported responseids would go here
12655:         my $importedresponses=0;
12656: #
12657: # Is this a recursive call for a library?
12658: #
12659: #	if (! exists($metacache{$uri})) {
12660: #	    $metacache{$uri}={};
12661: #	}
12662: 	my $cachetime = 60*60;
12663:         if ($liburi) {
12664: 	    $liburi=&declutter($liburi);
12665:             $filename=$liburi;
12666:         } else {
12667: 	    &devalidate_cache_new('meta',$uri);
12668: 	    undef(%metaentry);
12669: 	}
12670:         my %metathesekeys=();
12671:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12672: 	my $metastring;
12673: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12674: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12675: 	    $metastring = 
12676: 		&Apache::lonnet::ssi_body($which,
12677: 					  ('grade_target' => 'meta'));
12678: 	    $cachetime = 1; # only want this cached in the child not long term
12679: 	} elsif (($uri !~ m -^(editupload)/-) && 
12680:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12681: 	    my $file=&filelocation('',&clutter($filename));
12682: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12683: 	    $metastring=&getfile($file);
12684: 	}
12685:         my $parser=HTML::LCParser->new(\$metastring);
12686:         my $token;
12687:         undef %metathesekeys;
12688:         while ($token=$parser->get_token) {
12689: 	    if ($token->[0] eq 'S') {
12690: 		if (defined($token->[2]->{'package'})) {
12691: #
12692: # This is a package - get package info
12693: #
12694: 		    my $package=$token->[2]->{'package'};
12695: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12696: 		    if (defined($token->[2]->{'id'})) { 
12697: 			$keyroot.='_'.$token->[2]->{'id'}; 
12698: 		    }
12699: 		    if ($metaentry{':packages'}) {
12700: 			$metaentry{':packages'}.=','.$package.$keyroot;
12701: 		    } else {
12702: 			$metaentry{':packages'}=$package.$keyroot;
12703: 		    }
12704: 		    foreach my $pack_entry (keys(%packagetab)) {
12705: 			my $part=$keyroot;
12706: 			$part=~s/^\_//;
12707: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12708: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12709: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12710: 			    # ignore package.tab specified default values
12711:                             # here &package_tab_default() will fetch those
12712: 			    if ($subp eq 'default') { next; }
12713: 			    my $value=$packagetab{$pack_entry};
12714: 			    my $unikey;
12715: 			    if ($pack =~ /_0$/) {
12716: 				$unikey='parameter_0_'.$name;
12717: 				$part=0;
12718: 			    } else {
12719: 				$unikey='parameter'.$keyroot.'_'.$name;
12720: 			    }
12721: 			    if ($subp eq 'display') {
12722: 				$value.=' [Part: '.$part.']';
12723: 			    }
12724: 			    $metaentry{':'.$unikey.'.part'}=$part;
12725: 			    $metathesekeys{$unikey}=1;
12726: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12727: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12728: 			    }
12729: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12730: 				$metaentry{':'.$unikey}=
12731: 				    $metaentry{':'.$unikey.'.default'};
12732: 			    }
12733: 			}
12734: 		    }
12735: 		} else {
12736: #
12737: # This is not a package - some other kind of start tag
12738: #
12739: 		    my $entry=$token->[1];
12740: 		    my $unikey='';
12741: 
12742: 		    if ($entry eq 'import') {
12743: #
12744: # Importing a library here
12745: #
12746:                         my $location=$parser->get_text('/import');
12747:                         my $dir=$filename;
12748:                         $dir=~s|[^/]*$||;
12749:                         $location=&filelocation($dir,$location);
12750: 
12751:                         my $importid=$token->[2]->{'id'};
12752:                         my $importmode=$token->[2]->{'importmode'};
12753: #
12754: # Check metadata for imported file to
12755: # see if it contained response items
12756: #
12757:                         my ($origfile,@libfilekeys);
12758:                         my %currmetaentry = %metaentry;
12759:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12760:                                                            $depthcount+1));
12761:                         if (grep(/^responseorder$/,@libfilekeys)) {
12762:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12763:                                                              undef,$depthcount+1);
12764:                             if ($libresponseorder ne '') {
12765:                                 if ($#origfiletagids<0) {
12766:                                     undef(%importedrespids);
12767:                                     undef(%importedpartids);
12768:                                 }
12769:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12770:                                 if (@respids) {
12771:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12772:                                 }
12773:                                 if ($importedrespids{$importid} ne '') {
12774:                                     $importedresponses = 1;
12775: # We need to get the original file and the imported file to get the response order correct
12776: # Load and inspect original file
12777:                                     if ($#origfiletagids<0) {
12778:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12779:                                         $origfile=&getfile($origfilelocation);
12780:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12781:                                     }
12782:                                 }
12783:                             }
12784:                         }
12785: # Do not overwrite contents of %metaentry hash for resource itself with 
12786: # hash populated for imported library file
12787:                         %metaentry = %currmetaentry;
12788:                         undef(%currmetaentry);
12789:                         if ($importmode eq 'part') {
12790: # Import as part(s)
12791:                            $importedparts=1;
12792: # We need to get the original file and the imported file to get the part order correct
12793: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12794: # Load and inspect original file if we didn't do that already
12795:                            if ($#origfiletagids<0) {
12796:                                undef(%importedrespids);
12797:                                undef(%importedpartids);
12798:                                if ($origfile eq '') {
12799:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12800:                                    $origfile=&getfile($origfilelocation);
12801:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12802:                                }
12803:                            }
12804:                            my @impfilepartids;
12805: # If <partorder> tag is included in metadata for the imported file
12806: # get the parts in the imported file from that.
12807:                            if (grep(/^partorder$/,@libfilekeys)) {
12808:                                %currmetaentry = %metaentry;
12809:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12810:                                                             $depthcount+1);
12811:                                %metaentry = %currmetaentry;
12812:                                undef(%currmetaentry);
12813:                                if ($libpartorder ne '') {
12814:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12815:                                }
12816:                            } else {
12817: # If no <partorder> tag available, load and inspect imported file
12818:                                my $impfile=&getfile($location);
12819:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12820:                            }
12821:                            if ($#impfilepartids>=0) {
12822: # This problem had parts
12823:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12824:                            } else {
12825: # Importing by turning a single problem into a problem part
12826: # It gets the import-tags ID as part-ID
12827:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12828:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12829:                            }
12830:                         } else {
12831: # Import as problem or as normal import
12832:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12833:                             unless ($importmode eq 'problem') {
12834: # Normal import
12835:                                 if (defined($token->[2]->{'id'})) {
12836:                                     $unikey.='_'.$token->[2]->{'id'};
12837:                                 }
12838:                             }
12839: # Check metadata for imported file to
12840: # see if it contained parts
12841:                             if (grep(/^partorder$/,@libfilekeys)) {
12842:                                 %currmetaentry = %metaentry;
12843:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12844:                                                              $depthcount+1);
12845:                                 %metaentry = %currmetaentry;
12846:                                 undef(%currmetaentry);
12847:                                 if ($libpartorder ne '') {
12848:                                     $importedparts = 1;
12849:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12850:                                 }
12851:                             }
12852:                         }
12853: 			if ($depthcount<20) {
12854: 			    my $metadata = 
12855: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12856: 					  $depthcount+1);
12857: 			    foreach my $meta (split(',',$metadata)) {
12858: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12859: 				$metathesekeys{$meta}=1;
12860: 			    }
12861:                         }
12862: 		    } else {
12863: #
12864: # Not importing, some other kind of non-package, non-library start tag
12865: # 
12866:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12867:                         if (defined($token->[2]->{'id'})) {
12868:                             $unikey.='_'.$token->[2]->{'id'};
12869:                         }
12870: 			if (defined($token->[2]->{'name'})) { 
12871: 			    $unikey.='_'.$token->[2]->{'name'}; 
12872: 			}
12873: 			$metathesekeys{$unikey}=1;
12874: 			foreach my $param (@{$token->[3]}) {
12875: 			    $metaentry{':'.$unikey.'.'.$param} =
12876: 				$token->[2]->{$param};
12877: 			}
12878: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12879: 			my $default=$metaentry{':'.$unikey.'.default'};
12880: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12881: 		 # only ws inside the tag, and not in default, so use default
12882: 		 # as value
12883: 			    $metaentry{':'.$unikey}=$default;
12884: 			} elsif ( $internaltext =~ /\S/ ) {
12885: 		  # something interesting inside the tag
12886: 			    $metaentry{':'.$unikey}=$internaltext;
12887: 			} else {
12888: 		  # no interesting values, don't set a default
12889: 			}
12890: # end of not-a-package not-a-library import
12891: 		    }
12892: # end of not-a-package start tag
12893: 		}
12894: # the next is the end of "start tag"
12895: 	    }
12896: 	}
12897: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12898: 	$extension = lc($extension);
12899: 	if ($extension eq 'htm') { $extension='html'; }
12900: 
12901: 	foreach my $key (keys(%packagetab)) {
12902: 	    #no specific packages #how's our extension
12903: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12904: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12905: 					 \%metathesekeys);
12906: 	}
12907: 
12908: 	if (!exists($metaentry{':packages'})
12909: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12910: 	    foreach my $key (keys(%packagetab)) {
12911: 		#no specific packages well let's get default then
12912: 		if ($key!~/^default&/) { next; }
12913: 		&metadata_create_package_def($uri,$key,'default',
12914: 					     \%metathesekeys);
12915: 	    }
12916: 	}
12917: # are there custom rights to evaluate
12918: 	if ($metaentry{':copyright'} eq 'custom') {
12919: 
12920:     #
12921:     # Importing a rights file here
12922:     #
12923: 	    unless ($depthcount) {
12924: 		my $location=$metaentry{':customdistributionfile'};
12925: 		my $dir=$filename;
12926: 		$dir=~s|[^/]*$||;
12927: 		$location=&filelocation($dir,$location);
12928: 		my $rights_metadata =
12929: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12930: 			      $depthcount+1);
12931: 		foreach my $rights (split(',',$rights_metadata)) {
12932: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12933: 		    $metathesekeys{$rights}=1;
12934: 		}
12935: 	    }
12936: 	}
12937: 	# uniqifiy package listing
12938: 	my %seen;
12939: 	my @uniq_packages =
12940: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12941: 	$metaentry{':packages'} = join(',',@uniq_packages);
12942: 
12943:         if (($importedresponses) || ($importedparts)) {
12944:             if ($importedparts) {
12945: # We had imported parts and need to rebuild partorder
12946:                 $metaentry{':partorder'}='';
12947:                 $metathesekeys{'partorder'}=1;
12948:             }
12949:             if ($importedresponses) {
12950: # We had imported responses and need to rebuil responseorder
12951:                 $metaentry{':responseorder'}='';
12952:                 $metathesekeys{'responseorder'}=1;
12953:             }
12954:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12955:                 my $origid = $origfiletagids[$index+1];
12956:                 if ($origfiletagids[$index] eq 'part') {
12957: # Original part, part of the problem
12958:                     if ($importedparts) {
12959:                         $metaentry{':partorder'}.=','.$origid;
12960:                     }
12961:                 } elsif ($origfiletagids[$index] eq 'import') {
12962:                     if ($importedparts) {
12963: # We have imported parts at this position
12964:                         if ($importedpartids{$origid} ne '') {
12965:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12966:                         }
12967:                     }
12968:                     if ($importedresponses) {
12969: # We have imported responses at this position
12970:                         if ($importedrespids{$origid} ne '') {
12971:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12972:                         }
12973:                     }
12974:                 } else {
12975: # Original response item, part of the problem
12976:                     if ($importedresponses) {
12977:                         $metaentry{':responseorder'}.=','.$origid;
12978:                     }
12979:                 }
12980:             }
12981:             if ($importedparts) {
12982:                 $metaentry{':partorder'}=~s/^\,//;
12983:             }
12984:             if ($importedresponses) {
12985:                 $metaentry{':responseorder'}=~s/^\,//;
12986:             }
12987:         }
12988: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12989: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12990: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12991:         unless ($liburi) {
12992: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12993:         }
12994: # this is the end of "was not already recently cached
12995:     }
12996:     return $metaentry{':'.$what};
12997: }
12998: 
12999: sub metadata_create_package_def {
13000:     my ($uri,$key,$package,$metathesekeys)=@_;
13001:     my ($pack,$name,$subp)=split(/\&/,$key);
13002:     if ($subp eq 'default') { next; }
13003:     
13004:     if (defined($metaentry{':packages'})) {
13005: 	$metaentry{':packages'}.=','.$package;
13006:     } else {
13007: 	$metaentry{':packages'}=$package;
13008:     }
13009:     my $value=$packagetab{$key};
13010:     my $unikey;
13011:     $unikey='parameter_0_'.$name;
13012:     $metaentry{':'.$unikey.'.part'}=0;
13013:     $$metathesekeys{$unikey}=1;
13014:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13015: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13016:     }
13017:     if (defined($metaentry{':'.$unikey.'.default'})) {
13018: 	$metaentry{':'.$unikey}=
13019: 	    $metaentry{':'.$unikey.'.default'};
13020:     }
13021: }
13022: 
13023: sub metadata_generate_part0 {
13024:     my ($metadata,$metacache,$uri) = @_;
13025:     my %allnames;
13026:     foreach my $metakey (keys(%$metadata)) {
13027: 	if ($metakey=~/^parameter\_(.*)/) {
13028: 	  my $part=$$metacache{':'.$metakey.'.part'};
13029: 	  my $name=$$metacache{':'.$metakey.'.name'};
13030: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13031: 	    $allnames{$name}=$part;
13032: 	  }
13033: 	}
13034:     }
13035:     foreach my $name (keys(%allnames)) {
13036:       $$metadata{"parameter_0_$name"}=1;
13037:       my $key=":parameter_0_$name";
13038:       $$metacache{"$key.part"}='0';
13039:       $$metacache{"$key.name"}=$name;
13040:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13041: 					   $allnames{$name}.'_'.$name.
13042: 					   '.type'};
13043:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13044: 			     '.display'};
13045:       my $expr='[Part: '.$allnames{$name}.']';
13046:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13047:       $$metacache{"$key.display"}=$olddis;
13048:     }
13049: }
13050: 
13051: # ------------------------------------------------------ Devalidate title cache
13052: 
13053: sub devalidate_title_cache {
13054:     my ($url)=@_;
13055:     if (!$env{'request.course.id'}) { return; }
13056:     my $symb=&symbread($url);
13057:     if (!$symb) { return; }
13058:     my $key=$env{'request.course.id'}."\0".$symb;
13059:     &devalidate_cache_new('title',$key);
13060: }
13061: 
13062: # ------------------------------------------------- Get the title of a course
13063: 
13064: sub current_course_title {
13065:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13066: }
13067: # ------------------------------------------------- Get the title of a resource
13068: 
13069: sub gettitle {
13070:     my $urlsymb=shift;
13071:     my $symb=&symbread($urlsymb);
13072:     if ($symb) {
13073: 	my $key=$env{'request.course.id'}."\0".$symb;
13074: 	my ($result,$cached)=&is_cached_new('title',$key);
13075: 	if (defined($cached)) { 
13076: 	    return $result;
13077: 	}
13078: 	my ($map,$resid,$url)=&decode_symb($symb);
13079: 	my $title='';
13080: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13081: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13082: 	} else {
13083: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13084: 		    &GDBM_READER(),0640)) {
13085: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13086: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13087: 		untie(%bighash);
13088: 	    }
13089: 	}
13090: 	$title=~s/\&colon\;/\:/gs;
13091: 	if ($title) {
13092: # Remember both $symb and $title for dynamic metadata
13093:             $accesshash{$symb.'___crstitle'}=$title;
13094:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13095: # Cache this title and then return it
13096: 	    return &do_cache_new('title',$key,$title,600);
13097: 	}
13098: 	$urlsymb=$url;
13099:     }
13100:     my $title=&metadata($urlsymb,'title');
13101:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13102:     return $title;
13103: }
13104: 
13105: sub get_slot {
13106:     my ($which,$cnum,$cdom)=@_;
13107:     if (!$cnum || !$cdom) {
13108: 	(undef,my $courseid)=&whichuser();
13109: 	$cdom=$env{'course.'.$courseid.'.domain'};
13110: 	$cnum=$env{'course.'.$courseid.'.num'};
13111:     }
13112:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13113:     my %slotinfo;
13114:     if (exists($remembered{$key})) {
13115: 	$slotinfo{$which} = $remembered{$key};
13116:     } else {
13117: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13118: 	&Apache::lonhomework::showhash(%slotinfo);
13119: 	my ($tmp)=keys(%slotinfo);
13120: 	if ($tmp=~/^error:/) { return (); }
13121: 	$remembered{$key} = $slotinfo{$which};
13122:     }
13123:     if (ref($slotinfo{$which}) eq 'HASH') {
13124: 	return %{$slotinfo{$which}};
13125:     }
13126:     return $slotinfo{$which};
13127: }
13128: 
13129: sub get_reservable_slots {
13130:     my ($cnum,$cdom,$uname,$udom) = @_;
13131:     my $now = time;
13132:     my $reservable_info;
13133:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13134:     if (exists($remembered{$key})) {
13135:         $reservable_info = $remembered{$key};
13136:     } else {
13137:         my %resv;
13138:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13139:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13140:         $reservable_info = \%resv;
13141:         $remembered{$key} = $reservable_info;
13142:     }
13143:     return $reservable_info;
13144: }
13145: 
13146: sub get_course_slots {
13147:     my ($cnum,$cdom) = @_;
13148:     my $hashid=$cnum.':'.$cdom;
13149:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13150:     if (defined($cached)) {
13151:         if (ref($result) eq 'HASH') {
13152:             return %{$result};
13153:         }
13154:     } else {
13155:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13156:         my ($tmp) = keys(%slots);
13157:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13158:             &do_cache_new('allslots',$hashid,\%slots,600);
13159:             return %slots;
13160:         }
13161:     }
13162:     return;
13163: }
13164: 
13165: sub devalidate_slots_cache {
13166:     my ($cnum,$cdom)=@_;
13167:     my $hashid=$cnum.':'.$cdom;
13168:     &devalidate_cache_new('allslots',$hashid);
13169: }
13170: 
13171: sub get_coursechange {
13172:     my ($cdom,$cnum) = @_;
13173:     if ($cdom eq '' || $cnum eq '') {
13174:         return unless ($env{'request.course.id'});
13175:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13176:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13177:     }
13178:     my $hashid=$cdom.'_'.$cnum;
13179:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13180:     if ((defined($cached)) && ($change ne '')) {
13181:         return $change;
13182:     } else {
13183:         my %crshash;
13184:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13185:         if ($crshash{'internal.contentchange'} eq '') {
13186:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13187:             if ($change eq '') {
13188:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13189:                 $change = $crshash{'internal.created'};
13190:             }
13191:         } else {
13192:             $change = $crshash{'internal.contentchange'};
13193:         }
13194:         my $cachetime = 600;
13195:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13196:     }
13197:     return $change;
13198: }
13199: 
13200: sub devalidate_coursechange_cache {
13201:     my ($cnum,$cdom)=@_;
13202:     my $hashid=$cnum.':'.$cdom;
13203:     &devalidate_cache_new('crschange',$hashid);
13204: }
13205: 
13206: # ------------------------------------------------- Update symbolic store links
13207: 
13208: sub symblist {
13209:     my ($mapname,%newhash)=@_;
13210:     $mapname=&deversion(&declutter($mapname));
13211:     my %hash;
13212:     if (($env{'request.course.fn'}) && (%newhash)) {
13213:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13214:                       &GDBM_WRCREAT(),0640)) {
13215: 	    foreach my $url (keys(%newhash)) {
13216: 		next if ($url eq 'last_known'
13217: 			 && $env{'form.no_update_last_known'});
13218: 		$hash{declutter($url)}=&encode_symb($mapname,
13219: 						    $newhash{$url}->[1],
13220: 						    $newhash{$url}->[0]);
13221:             }
13222:             if (untie(%hash)) {
13223: 		return 'ok';
13224:             }
13225:         }
13226:     }
13227:     return 'error';
13228: }
13229: 
13230: # --------------------------------------------------------------- Verify a symb
13231: 
13232: sub symbverify {
13233:     my ($symb,$thisurl,$encstate)=@_;
13234:     my $thisfn=$thisurl;
13235:     $thisfn=&declutter($thisfn);
13236: # direct jump to resource in page or to a sequence - will construct own symbs
13237:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13238: # check URL part
13239:     my ($map,$resid,$url)=&decode_symb($symb);
13240: 
13241:     unless ($url eq $thisfn) { return 0; }
13242: 
13243:     $symb=&symbclean($symb);
13244:     $thisurl=&deversion($thisurl);
13245:     $thisfn=&deversion($thisfn);
13246: 
13247:     my %bighash;
13248:     my $okay=0;
13249: 
13250:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13251:                             &GDBM_READER(),0640)) {
13252:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13253:             $thisurl =~ s/\?.+$//;
13254:             if ($map =~ m{^uploaded/.+\.page$}) {
13255:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13256:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13257:             }
13258:         }
13259:         my $ids;
13260:         if ($map =~ m{^uploaded/.+\.page$}) {
13261:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13262:         } else {
13263:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13264:         }
13265:         unless ($ids) {
13266:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13267:             $ids=$bighash{$idkey};
13268:         }
13269:         if ($ids) {
13270: # ------------------------------------------------------------------- Has ID(s)
13271:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13272:                 $symb =~ s/\?.+$//;
13273:             }
13274: 	    foreach my $id (split(/\,/,$ids)) {
13275: 	       my ($mapid,$resid)=split(/\./,$id);
13276:                if (
13277:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13278:    eq $symb) {
13279:                    if (ref($encstate)) {
13280:                        $$encstate = $bighash{'encrypted_'.$id};
13281:                    }
13282: 		   if (($env{'request.role.adv'}) ||
13283: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13284:                        ($thisurl eq '/adm/navmaps')) {
13285: 		       $okay=1;
13286:                        last;
13287: 		   }
13288: 	       }
13289: 	   }
13290:         }
13291: 	untie(%bighash);
13292:     }
13293:     return $okay;
13294: }
13295: 
13296: # --------------------------------------------------------------- Clean-up symb
13297: 
13298: sub symbclean {
13299:     my $symb=shift;
13300:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13301: # remove version from map
13302:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13303: 
13304: # remove version from URL
13305:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13306: 
13307: # remove wrapper
13308: 
13309:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13310:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13311:     return $symb;
13312: }
13313: 
13314: # ---------------------------------------------- Split symb to find map and url
13315: 
13316: sub encode_symb {
13317:     my ($map,$resid,$url)=@_;
13318:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13319: }
13320: 
13321: sub decode_symb {
13322:     my $symb=shift;
13323:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13324:     my ($map,$resid,$url)=split(/___/,$symb);
13325:     return (&fixversion($map),$resid,&fixversion($url));
13326: }
13327: 
13328: sub fixversion {
13329:     my $fn=shift;
13330:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13331:     my %bighash;
13332:     my $uri=&clutter($fn);
13333:     my $key=$env{'request.course.id'}.'_'.$uri;
13334: # is this cached?
13335:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13336:     if (defined($cached)) { return $result; }
13337: # unfortunately not cached, or expired
13338:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13339: 	    &GDBM_READER(),0640)) {
13340:  	if ($bighash{'version_'.$uri}) {
13341:  	    my $version=$bighash{'version_'.$uri};
13342:  	    unless (($version eq 'mostrecent') || 
13343: 		    ($version==&getversion($uri))) {
13344:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13345:  	    }
13346:  	}
13347:  	untie %bighash;
13348:     }
13349:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13350: }
13351: 
13352: sub deversion {
13353:     my $url=shift;
13354:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13355:     return $url;
13356: }
13357: 
13358: # ------------------------------------------------------ Return symb list entry
13359: 
13360: sub symbread {
13361:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13362:         $ignoresymbdb,$noenccheck)=@_;
13363:     my $cache_str='request.symbread.cached.'.$thisfn;
13364:     if (defined($env{$cache_str})) {
13365:         unless (ref($possibles) eq 'HASH') {
13366:             if ($ignorecachednull) {
13367:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
13368:             } else {
13369:                 return $env{$cache_str};
13370:             }
13371:         }
13372:     }
13373: # no filename provided? try from environment
13374:     unless ($thisfn) {
13375:         if ($env{'request.symb'}) {
13376:             return $env{$cache_str}=&symbclean($env{'request.symb'});
13377: 	}
13378: 	$thisfn=$env{'request.filename'};
13379:     }
13380:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13381: # is that filename actually a symb? Verify, clean, and return
13382:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13383: 	if (&symbverify($thisfn,$1)) {
13384: 	    return $env{$cache_str}=&symbclean($thisfn);
13385: 	}
13386:     }
13387:     $thisfn=declutter($thisfn);
13388:     my %hash;
13389:     my %bighash;
13390:     my $syval='';
13391:     if (($env{'request.course.fn'}) && ($thisfn)) {
13392:         my $targetfn = $thisfn;
13393:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13394:             $targetfn = 'adm/wrapper/'.$thisfn;
13395:         }
13396: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13397: 	    $targetfn=$1;
13398: 	}
13399:         unless ($ignoresymbdb) {
13400:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13401:                           &GDBM_READER(),0640)) {
13402: 	        $syval=$hash{$targetfn};
13403:                 untie(%hash);
13404:             }
13405:             if ($syval && $checkforblock) {
13406:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13407:                 if (@blockers) {
13408:                     $syval='';
13409:                 }
13410:             }
13411:         }
13412: # ---------------------------------------------------------- There was an entry
13413:         if ($syval) {
13414: 	    #unless ($syval=~/\_\d+$/) {
13415: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13416: 		    #&appenv({'request.ambiguous' => $thisfn});
13417: 		    #return $env{$cache_str}='';
13418: 		#}    
13419: 		#$syval.=$1;
13420: 	    #}
13421:         } else {
13422: # ------------------------------------------------------- Was not in symb table
13423:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13424:                             &GDBM_READER(),0640)) {
13425: # ---------------------------------------------- Get ID(s) for current resource
13426:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13427:               unless ($ids) { 
13428:                  $ids=$bighash{'ids_/'.$thisfn};
13429:               }
13430:               unless ($ids) {
13431: # alias?
13432: 		  $ids=$bighash{'mapalias_'.$thisfn};
13433:               }
13434:               if ($ids) {
13435: # ------------------------------------------------------------------- Has ID(s)
13436:                  my @possibilities=split(/\,/,$ids);
13437:                  if ($#possibilities==0) {
13438: # ----------------------------------------------- There is only one possibility
13439: 		     my ($mapid,$resid)=split(/\./,$ids);
13440: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13441: 						    $resid,$thisfn);
13442:                      if (ref($possibles) eq 'HASH') {
13443:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13444:                              $possibles->{$syval} = 1;
13445:                          }
13446:                      }
13447:                      if ($checkforblock) {
13448:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13449:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13450:                              if (@blockers) {
13451:                                  $syval = '';
13452:                                  untie(%bighash);
13453:                                  return $env{$cache_str}='';
13454:                              }
13455:                          }
13456:                      }
13457:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13458: # ------------------------------------------ There is more than one possibility
13459:                      my $realpossible=0;
13460:                      foreach my $id (@possibilities) {
13461: 			 my $file=$bighash{'src_'.$id};
13462:                          my $canaccess;
13463:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13464:                              $canaccess = 1;
13465:                          } else { 
13466:                              $canaccess = &allowed('bre',$file);
13467:                          }
13468:                          if ($canaccess) {
13469:          		     my ($mapid,$resid)=split(/\./,$id);
13470:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13471:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13472: 						             $resid,$thisfn);
13473:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13474:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13475:                                  if ($checkforblock) {
13476:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13477:                                      if (@blockers > 0) {
13478:                                          $syval = '';
13479:                                      } else {
13480:                                          $syval = $poss_syval;
13481:                                          $realpossible++;
13482:                                      }
13483:                                  } else {
13484:                                      $syval = $poss_syval;
13485:                                      $realpossible++;
13486:                                  }
13487:                                  if ($syval) {
13488:                                      if (ref($possibles) eq 'HASH') {
13489:                                          $possibles->{$syval} = 1;
13490:                                      }
13491:                                  }
13492:                              }
13493: 			 }
13494:                      }
13495: 		     if ($realpossible!=1) { $syval=''; }
13496:                  } else {
13497:                      $syval='';
13498:                  }
13499: 	      }
13500:               untie(%bighash);
13501:            }
13502:         }
13503:         if ($syval) {
13504: 	    return $env{$cache_str}=$syval;
13505:         }
13506:     }
13507:     &appenv({'request.ambiguous' => $thisfn});
13508:     return $env{$cache_str}='';
13509: }
13510: 
13511: # ---------------------------------------------------------- Return random seed
13512: 
13513: sub numval {
13514:     my $txt=shift;
13515:     $txt=~tr/A-J/0-9/;
13516:     $txt=~tr/a-j/0-9/;
13517:     $txt=~tr/K-T/0-9/;
13518:     $txt=~tr/k-t/0-9/;
13519:     $txt=~tr/U-Z/0-5/;
13520:     $txt=~tr/u-z/0-5/;
13521:     $txt=~s/\D//g;
13522:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13523:     return int($txt);
13524: }
13525: 
13526: sub numval2 {
13527:     my $txt=shift;
13528:     $txt=~tr/A-J/0-9/;
13529:     $txt=~tr/a-j/0-9/;
13530:     $txt=~tr/K-T/0-9/;
13531:     $txt=~tr/k-t/0-9/;
13532:     $txt=~tr/U-Z/0-5/;
13533:     $txt=~tr/u-z/0-5/;
13534:     $txt=~s/\D//g;
13535:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13536:     my $total;
13537:     foreach my $val (@txts) { $total+=$val; }
13538:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13539:     return int($total);
13540: }
13541: 
13542: sub numval3 {
13543:     use integer;
13544:     my $txt=shift;
13545:     $txt=~tr/A-J/0-9/;
13546:     $txt=~tr/a-j/0-9/;
13547:     $txt=~tr/K-T/0-9/;
13548:     $txt=~tr/k-t/0-9/;
13549:     $txt=~tr/U-Z/0-5/;
13550:     $txt=~tr/u-z/0-5/;
13551:     $txt=~s/\D//g;
13552:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13553:     my $total;
13554:     foreach my $val (@txts) { $total+=$val; }
13555:     if ($_64bit) { $total=(($total<<32)>>32); }
13556:     return $total;
13557: }
13558: 
13559: sub digest {
13560:     my ($data)=@_;
13561:     my $digest=&Digest::MD5::md5($data);
13562:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13563:     my ($e,$f);
13564:     {
13565:         use integer;
13566:         $e=($a+$b);
13567:         $f=($c+$d);
13568:         if ($_64bit) {
13569:             $e=(($e<<32)>>32);
13570:             $f=(($f<<32)>>32);
13571:         }
13572:     }
13573:     if (wantarray) {
13574: 	return ($e,$f);
13575:     } else {
13576: 	my $g;
13577: 	{
13578: 	    use integer;
13579: 	    $g=($e+$f);
13580: 	    if ($_64bit) {
13581: 		$g=(($g<<32)>>32);
13582: 	    }
13583: 	}
13584: 	return $g;
13585:     }
13586: }
13587: 
13588: sub latest_rnd_algorithm_id {
13589:     return '64bit5';
13590: }
13591: 
13592: sub get_rand_alg {
13593:     my ($courseid)=@_;
13594:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13595:     if ($courseid) {
13596: 	return $env{"course.$courseid.rndseed"};
13597:     }
13598:     return &latest_rnd_algorithm_id();
13599: }
13600: 
13601: sub validCODE {
13602:     my ($CODE)=@_;
13603:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13604:     return 0;
13605: }
13606: 
13607: sub getCODE {
13608:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13609:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13610: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13611: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13612: 	return $Apache::lonhomework::history{'resource.CODE'};
13613:     }
13614:     return undef;
13615: }
13616: #
13617: #  Determines the random seed for a specific context:
13618: #
13619: # parameters:
13620: #   symb      - in course context the symb for the seed.
13621: #   course_id - The course id of the form domain_coursenum.
13622: #   domain    - Domain for the user.
13623: #   course    - Course for the user.
13624: #   cenv      - environment of the course.
13625: #
13626: # NOTE:
13627: #   All parameters are picked out of the environment if missing
13628: #   or not defined.
13629: #   If a symb cannot be determined the current time is used instead.
13630: #
13631: #  For a given well defined symb, courside, domain, username,
13632: #  and course environment, the seed is reproducible.
13633: #
13634: sub rndseed {
13635:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13636:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13637:     if (!defined($symb)) {
13638: 	unless ($symb=$wsymb) { return time; }
13639:     }
13640:     if (!defined $courseid) { 
13641: 	$courseid=$wcourseid; 
13642:     }
13643:     if (!defined $domain) { $domain=$wdomain; }
13644:     if (!defined $username) { $username=$wusername }
13645: 
13646:     my $which;
13647:     if (defined($cenv->{'rndseed'})) {
13648: 	$which = $cenv->{'rndseed'};
13649:     } else {
13650: 	$which =&get_rand_alg($courseid);
13651:     }
13652:     if (defined(&getCODE())) {
13653: 
13654: 	if ($which eq '64bit5') {
13655: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13656: 	} elsif ($which eq '64bit4') {
13657: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13658: 	} else {
13659: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13660: 	}
13661:     } elsif ($which eq '64bit5') {
13662: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13663:     } elsif ($which eq '64bit4') {
13664: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13665:     } elsif ($which eq '64bit3') {
13666: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13667:     } elsif ($which eq '64bit2') {
13668: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13669:     } elsif ($which eq '64bit') {
13670: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13671:     }
13672:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13673: }
13674: 
13675: sub rndseed_32bit {
13676:     my ($symb,$courseid,$domain,$username)=@_;
13677:     {
13678: 	use integer;
13679: 	my $symbchck=unpack("%32C*",$symb) << 27;
13680: 	my $symbseed=numval($symb) << 22;
13681: 	my $namechck=unpack("%32C*",$username) << 17;
13682: 	my $nameseed=numval($username) << 12;
13683: 	my $domainseed=unpack("%32C*",$domain) << 7;
13684: 	my $courseseed=unpack("%32C*",$courseid);
13685: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13686: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13687: 	#&logthis("rndseed :$num:$symb");
13688: 	if ($_64bit) { $num=(($num<<32)>>32); }
13689: 	return $num;
13690:     }
13691: }
13692: 
13693: sub rndseed_64bit {
13694:     my ($symb,$courseid,$domain,$username)=@_;
13695:     {
13696: 	use integer;
13697: 	my $symbchck=unpack("%32S*",$symb) << 21;
13698: 	my $symbseed=numval($symb) << 10;
13699: 	my $namechck=unpack("%32S*",$username);
13700: 	
13701: 	my $nameseed=numval($username) << 21;
13702: 	my $domainseed=unpack("%32S*",$domain) << 10;
13703: 	my $courseseed=unpack("%32S*",$courseid);
13704: 	
13705: 	my $num1=$symbchck+$symbseed+$namechck;
13706: 	my $num2=$nameseed+$domainseed+$courseseed;
13707: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13708: 	#&logthis("rndseed :$num:$symb");
13709: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13710: 	return "$num1,$num2";
13711:     }
13712: }
13713: 
13714: sub rndseed_64bit2 {
13715:     my ($symb,$courseid,$domain,$username)=@_;
13716:     {
13717: 	use integer;
13718: 	# strings need to be an even # of cahracters long, it it is odd the
13719:         # last characters gets thrown away
13720: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13721: 	my $symbseed=numval($symb) << 10;
13722: 	my $namechck=unpack("%32S*",$username.' ');
13723: 	
13724: 	my $nameseed=numval($username) << 21;
13725: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13726: 	my $courseseed=unpack("%32S*",$courseid.' ');
13727: 	
13728: 	my $num1=$symbchck+$symbseed+$namechck;
13729: 	my $num2=$nameseed+$domainseed+$courseseed;
13730: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13731: 	#&logthis("rndseed :$num:$symb");
13732: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13733: 	return "$num1,$num2";
13734:     }
13735: }
13736: 
13737: sub rndseed_64bit3 {
13738:     my ($symb,$courseid,$domain,$username)=@_;
13739:     {
13740: 	use integer;
13741: 	# strings need to be an even # of cahracters long, it it is odd the
13742:         # last characters gets thrown away
13743: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13744: 	my $symbseed=numval2($symb) << 10;
13745: 	my $namechck=unpack("%32S*",$username.' ');
13746: 	
13747: 	my $nameseed=numval2($username) << 21;
13748: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13749: 	my $courseseed=unpack("%32S*",$courseid.' ');
13750: 	
13751: 	my $num1=$symbchck+$symbseed+$namechck;
13752: 	my $num2=$nameseed+$domainseed+$courseseed;
13753: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13754: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13755: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13756: 	
13757: 	return "$num1:$num2";
13758:     }
13759: }
13760: 
13761: sub rndseed_64bit4 {
13762:     my ($symb,$courseid,$domain,$username)=@_;
13763:     {
13764: 	use integer;
13765: 	# strings need to be an even # of cahracters long, it it is odd the
13766:         # last characters gets thrown away
13767: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13768: 	my $symbseed=numval3($symb) << 10;
13769: 	my $namechck=unpack("%32S*",$username.' ');
13770: 	
13771: 	my $nameseed=numval3($username) << 21;
13772: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13773: 	my $courseseed=unpack("%32S*",$courseid.' ');
13774: 	
13775: 	my $num1=$symbchck+$symbseed+$namechck;
13776: 	my $num2=$nameseed+$domainseed+$courseseed;
13777: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13778: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13779: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13780: 	
13781: 	return "$num1:$num2";
13782:     }
13783: }
13784: 
13785: sub rndseed_64bit5 {
13786:     my ($symb,$courseid,$domain,$username)=@_;
13787:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13788:     return "$num1:$num2";
13789: }
13790: 
13791: sub rndseed_CODE_64bit {
13792:     my ($symb,$courseid,$domain,$username)=@_;
13793:     {
13794: 	use integer;
13795: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13796: 	my $symbseed=numval2($symb);
13797: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13798: 	my $CODEseed=numval(&getCODE());
13799: 	my $courseseed=unpack("%32S*",$courseid.' ');
13800: 	my $num1=$symbseed+$CODEchck;
13801: 	my $num2=$CODEseed+$courseseed+$symbchck;
13802: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13803: 	#&logthis("rndseed :$num1:$num2:$symb");
13804: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13805: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13806: 	return "$num1:$num2";
13807:     }
13808: }
13809: 
13810: sub rndseed_CODE_64bit4 {
13811:     my ($symb,$courseid,$domain,$username)=@_;
13812:     {
13813: 	use integer;
13814: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13815: 	my $symbseed=numval3($symb);
13816: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13817: 	my $CODEseed=numval3(&getCODE());
13818: 	my $courseseed=unpack("%32S*",$courseid.' ');
13819: 	my $num1=$symbseed+$CODEchck;
13820: 	my $num2=$CODEseed+$courseseed+$symbchck;
13821: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13822: 	#&logthis("rndseed :$num1:$num2:$symb");
13823: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13824: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13825: 	return "$num1:$num2";
13826:     }
13827: }
13828: 
13829: sub rndseed_CODE_64bit5 {
13830:     my ($symb,$courseid,$domain,$username)=@_;
13831:     my $code = &getCODE();
13832:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13833:     return "$num1:$num2";
13834: }
13835: 
13836: sub setup_random_from_rndseed {
13837:     my ($rndseed)=@_;
13838:     if ($rndseed =~/([,:])/) {
13839:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13840:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13841:             &Math::Random::random_set_seed_from_phrase($rndseed);
13842:         } else {
13843:             &Math::Random::random_set_seed($num1,$num2);
13844:         }
13845:     } else {
13846: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13847:     }
13848: }
13849: 
13850: sub latest_receipt_algorithm_id {
13851:     return 'receipt3';
13852: }
13853: 
13854: sub recunique {
13855:     my $fucourseid=shift;
13856:     my $unique;
13857:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13858: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13859: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13860:     } else {
13861: 	$unique=$perlvar{'lonReceipt'};
13862:     }
13863:     return unpack("%32C*",$unique);
13864: }
13865: 
13866: sub recprefix {
13867:     my $fucourseid=shift;
13868:     my $prefix;
13869:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13870: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13871: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13872:     } else {
13873: 	$prefix=$perlvar{'lonHostID'};
13874:     }
13875:     return unpack("%32C*",$prefix);
13876: }
13877: 
13878: sub ireceipt {
13879:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13880: 
13881:     my $return =&recprefix($fucourseid).'-';
13882: 
13883:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13884: 	$env{'request.state'} eq 'construct') {
13885: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13886: 	return $return;
13887:     }
13888: 
13889:     my $cuname=unpack("%32C*",$funame);
13890:     my $cudom=unpack("%32C*",$fudom);
13891:     my $cucourseid=unpack("%32C*",$fucourseid);
13892:     my $cusymb=unpack("%32C*",$fusymb);
13893:     my $cunique=&recunique($fucourseid);
13894:     my $cpart=unpack("%32S*",$part);
13895:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13896: 
13897: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13898: 			       
13899: 	$return.= ($cunique%$cuname+
13900: 		   $cunique%$cudom+
13901: 		   $cusymb%$cuname+
13902: 		   $cusymb%$cudom+
13903: 		   $cucourseid%$cuname+
13904: 		   $cucourseid%$cudom+
13905: 		   $cpart%$cuname+
13906: 		   $cpart%$cudom);
13907:     } else {
13908: 	$return.= ($cunique%$cuname+
13909: 		   $cunique%$cudom+
13910: 		   $cusymb%$cuname+
13911: 		   $cusymb%$cudom+
13912: 		   $cucourseid%$cuname+
13913: 		   $cucourseid%$cudom);
13914:     }
13915:     return $return;
13916: }
13917: 
13918: sub receipt {
13919:     my ($part)=@_;
13920:     my ($symb,$courseid,$domain,$name) = &whichuser();
13921:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13922: }
13923: 
13924: sub whichuser {
13925:     my ($passedsymb)=@_;
13926:     my ($symb,$courseid,$domain,$name,$publicuser);
13927:     if (defined($env{'form.grade_symb'})) {
13928: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13929: 	my $allowed=&allowed('vgr',$tmp_courseid);
13930: 	if (!$allowed &&
13931: 	    exists($env{'request.course.sec'}) &&
13932: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13933: 	    $allowed=&allowed('vgr',$tmp_courseid.
13934: 			      '/'.$env{'request.course.sec'});
13935: 	}
13936: 	if ($allowed) {
13937: 	    ($symb)=&get_env_multiple('form.grade_symb');
13938: 	    $courseid=$tmp_courseid;
13939: 	    ($domain)=&get_env_multiple('form.grade_domain');
13940: 	    ($name)=&get_env_multiple('form.grade_username');
13941: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13942: 	}
13943:     }
13944:     if (!$passedsymb) {
13945: 	$symb=&symbread();
13946:     } else {
13947: 	$symb=$passedsymb;
13948:     }
13949:     $courseid=$env{'request.course.id'};
13950:     $domain=$env{'user.domain'};
13951:     $name=$env{'user.name'};
13952:     if ($name eq 'public' && $domain eq 'public') {
13953: 	if (!defined($env{'form.username'})) {
13954: 	    $env{'form.username'}.=time.rand(10000000);
13955: 	}
13956: 	$name.=$env{'form.username'};
13957:     }
13958:     return ($symb,$courseid,$domain,$name,$publicuser);
13959: 
13960: }
13961: 
13962: # ------------------------------------------------------------ Serves up a file
13963: # returns either the contents of the file or 
13964: # -1 if the file doesn't exist
13965: #
13966: # if the target is a file that was uploaded via DOCS, 
13967: # a check will be made to see if a current copy exists on the local server,
13968: # if it does this will be served, otherwise a copy will be retrieved from
13969: # the home server for the course and stored in /home/httpd/html/userfiles on
13970: # the local server.   
13971: 
13972: sub getfile {
13973:     my ($file) = @_;
13974:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13975:     &repcopy($file);
13976:     return &readfile($file);
13977: }
13978: 
13979: sub repcopy_userfile {
13980:     my ($file)=@_;
13981:     my $londocroot = $perlvar{'lonDocRoot'};
13982:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13983:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13984:     my ($cdom,$cnum,$filename) = 
13985: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13986:     my $uri="/uploaded/$cdom/$cnum/$filename";
13987:     if (-e "$file") {
13988: # we already have a local copy, check it out
13989: 	my @fileinfo = stat($file);
13990: 	my $rtncode;
13991: 	my $info;
13992: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13993: 	if ($lwpresp ne 'ok') {
13994: # there is no such file anymore, even though we had a local copy
13995: 	    if ($rtncode eq '404') {
13996: 		unlink($file);
13997: 	    }
13998: 	    return -1;
13999: 	}
14000: 	if ($info < $fileinfo[9]) {
14001: # nice, the file we have is up-to-date, just say okay
14002: 	    return 'ok';
14003: 	} else {
14004: # the file is outdated, get rid of it
14005: 	    unlink($file);
14006: 	}
14007:     }
14008: # one way or the other, at this point, we don't have the file
14009: # construct the correct path for the file
14010:     my @parts = ($cdom,$cnum); 
14011:     if ($filename =~ m|^(.+)/[^/]+$|) {
14012: 	push @parts, split(/\//,$1);
14013:     }
14014:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14015:     foreach my $part (@parts) {
14016: 	$path .= '/'.$part;
14017: 	if (!-e $path) {
14018: 	    mkdir($path,0770);
14019: 	}
14020:     }
14021: # now the path exists for sure
14022: # get a user agent
14023:     my $transferfile=$file.'.in.transfer';
14024: # FIXME: this should flock
14025:     if (-e $transferfile) { return 'ok'; }
14026:     my $request;
14027:     $uri=~s/^\///;
14028:     my $homeserver = &homeserver($cnum,$cdom);
14029:     my $hostname = &hostname($homeserver);
14030:     my $protocol = $protocol{$homeserver};
14031:     $protocol = 'http' if ($protocol ne 'https');
14032:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14033:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14034: # did it work?
14035:     if ($response->is_error()) {
14036: 	unlink($transferfile);
14037: 	&logthis("Userfile repcopy failed for $uri");
14038: 	return -1;
14039:     }
14040: # worked, rename the transfer file
14041:     rename($transferfile,$file);
14042:     return 'ok';
14043: }
14044: 
14045: sub tokenwrapper {
14046:     my $uri=shift;
14047:     $uri=~s|^https?\://([^/]+)||;
14048:     $uri=~s|^/||;
14049:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14050:     my $token=$1;
14051:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14052:     if ($udom && $uname && $file) {
14053: 	$file=~s|(\?\.*)*$||;
14054:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14055:         my $homeserver = &homeserver($uname,$udom);
14056:         my $hostname = &hostname($homeserver);
14057:         my $protocol = $protocol{$homeserver};
14058:         $protocol = 'http' if ($protocol ne 'https');
14059:         return $protocol.'://'.$hostname.'/'.$uri.
14060:                (($uri=~/\?/)?'&':'?').'token='.$token.
14061:                                '&tokenissued='.$perlvar{'lonHostID'};
14062:     } else {
14063:         return '/adm/notfound.html';
14064:     }
14065: }
14066: 
14067: # call with reqtype HEAD: get last modification time
14068: # call with reqtype GET: get the file contents
14069: # Do not call this with reqtype GET for large files! It loads everything into memory
14070: #
14071: sub getuploaded {
14072:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14073:     $uri=~s/^\///;
14074:     my $homeserver = &homeserver($cnum,$cdom);
14075:     my $hostname = &hostname($homeserver);
14076:     my $protocol = $protocol{$homeserver};
14077:     $protocol = 'http' if ($protocol ne 'https');
14078:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14079:     my $request=new HTTP::Request($reqtype,$uri);
14080:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14081:     $$rtncode = $response->code;
14082:     if (! $response->is_success()) {
14083: 	return 'failed';
14084:     }      
14085:     if ($reqtype eq 'HEAD') {
14086: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14087:     } elsif ($reqtype eq 'GET') {
14088: 	$$info = $response->content;
14089:     }
14090:     return 'ok';
14091: }
14092: 
14093: sub readfile {
14094:     my $file = shift;
14095:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14096:     my $fh;
14097:     open($fh,"<",$file);
14098:     my $a='';
14099:     while (my $line = <$fh>) { $a .= $line; }
14100:     return $a;
14101: }
14102: 
14103: sub filelocation {
14104:     my ($dir,$file) = @_;
14105:     my $location;
14106:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14107: 
14108:     if ($file =~ m-^/adm/-) {
14109: 	$file=~s-^/adm/wrapper/-/-;
14110: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14111:     }
14112: 
14113:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14114:         $location = $file;
14115:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14116:         my ($udom,$uname,$filename)=
14117:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14118:         my $home=&homeserver($uname,$udom);
14119:         my $is_me=0;
14120:         my @ids=&current_machine_ids();
14121:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14122:         if ($is_me) {
14123:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14124:         } else {
14125:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14126:   	      $udom.'/'.$uname.'/'.$filename;
14127:         }
14128:     } elsif ($file =~ m-^/adm/-) {
14129: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14130:     } else {
14131:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14132:         $file=~s:^/(res|priv)/:/:;
14133:         my $space=$1;
14134:         if ( !( $file =~ m:^/:) ) {
14135:             $location = $dir. '/'.$file;
14136:         } else {
14137:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14138:         }
14139:     }
14140:     $location=~s://+:/:g; # remove duplicate /
14141:     while ($location=~m{/\.\./}) {
14142: 	if ($location =~ m{/[^/]+/\.\./}) {
14143: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14144: 	} else {
14145: 	    $location=~ s{/\.\./}{/}g;
14146: 	}
14147:     } #remove dir/..
14148:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14149:     return $location;
14150: }
14151: 
14152: sub hreflocation {
14153:     my ($dir,$file)=@_;
14154:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14155: 	$file=filelocation($dir,$file);
14156:     } elsif ($file=~m-^/adm/-) {
14157: 	$file=~s-^/adm/wrapper/-/-;
14158: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14159:     }
14160:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14161: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14162:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14163: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14164: 	        {/uploaded/$1/$2/}x;
14165:     }
14166:     if ($file=~ m{^/userfiles/}) {
14167: 	$file =~ s{^/userfiles/}{/uploaded/};
14168:     }
14169:     return $file;
14170: }
14171: 
14172: 
14173: 
14174: 
14175: 
14176: sub current_machine_domains {
14177:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14178: }
14179: 
14180: sub machine_domains {
14181:     my ($hostname) = @_;
14182:     my @domains;
14183:     my %hostname = &all_hostnames();
14184:     while( my($id, $name) = each(%hostname)) {
14185: #	&logthis("-$id-$name-$hostname-");
14186: 	if ($hostname eq $name) {
14187: 	    push(@domains,&host_domain($id));
14188: 	}
14189:     }
14190:     return @domains;
14191: }
14192: 
14193: sub current_machine_ids {
14194:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14195: }
14196: 
14197: sub machine_ids {
14198:     my ($hostname) = @_;
14199:     $hostname ||= &hostname($perlvar{'lonHostID'});
14200:     my @ids;
14201:     my %name_to_host = &all_names();
14202:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14203: 	return @{ $name_to_host{$hostname} };
14204:     }
14205:     return;
14206: }
14207: 
14208: sub additional_machine_domains {
14209:     my @domains;
14210:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
14211:     while( my $line = <$fh>) {
14212:         $line =~ s/\s//g;
14213:         push(@domains,$line);
14214:     }
14215:     return @domains;
14216: }
14217: 
14218: sub default_login_domain {
14219:     my $domain = $perlvar{'lonDefDomain'};
14220:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14221:     foreach my $posdom (&current_machine_domains(),
14222:                         &additional_machine_domains()) {
14223:         if (lc($posdom) eq lc($testdomain)) {
14224:             $domain=$posdom;
14225:             last;
14226:         }
14227:     }
14228:     return $domain;
14229: }
14230: 
14231: sub shared_institution {
14232:     my ($dom,$lonhost) = @_;
14233:     if ($lonhost eq '') {
14234:         $lonhost = $perlvar{'lonHostID'};
14235:     }
14236:     my $same_intdom;
14237:     my $hostintdom = &internet_dom($lonhost);
14238:     if ($hostintdom ne '') {
14239:         my %iphost = &get_iphost();
14240:         my $primary_id = &domain($dom,'primary');
14241:         my $primary_ip = &get_host_ip($primary_id);
14242:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14243:             foreach my $id (@{$iphost{$primary_ip}}) {
14244:                 my $intdom = &internet_dom($id);
14245:                 if ($intdom eq $hostintdom) {
14246:                     $same_intdom = 1;
14247:                     last;
14248:                 }
14249:             }
14250:         }
14251:     }
14252:     return $same_intdom;
14253: }
14254: 
14255: sub uses_sts {
14256:     my ($ignore_cache) = @_;
14257:     my $lonhost = $perlvar{'lonHostID'};
14258:     my $hostname = &hostname($lonhost);
14259:     my $sts_on;
14260:     if ($protocol{$lonhost} eq 'https') {
14261:         my $cachetime = 12*3600;
14262:         if (!$ignore_cache) {
14263:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14264:             if (defined($cached)) {
14265:                 return $sts_on;
14266:             }
14267:         }
14268:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14269:         my $request=new HTTP::Request('HEAD',$url);
14270:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14271:         if ($response->is_success) {
14272:             my $has_sts = $response->header('Strict-Transport-Security');
14273:             if ($has_sts eq '') {
14274:                 $sts_on = 0;
14275:             } else {
14276:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14277:                     my $maxage = $1;
14278:                     if ($maxage) {
14279:                         $sts_on = 1;
14280:                     } else {
14281:                         $sts_on = 0;
14282:                     }
14283:                 } else {
14284:                     $sts_on = 0;
14285:                 }
14286:             }
14287:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14288:         }
14289:     }
14290:     return;
14291: }
14292: 
14293: sub get_requestor_ip {
14294:     my ($r,$nolookup,$noproxy) = @_;
14295:     my $from_ip;
14296:     if (ref($r)) {
14297:         $from_ip = $r->get_remote_host($nolookup);
14298:     } else {
14299:         $from_ip = $ENV{'REMOTE_ADDR'};
14300:     }
14301:     return $from_ip if ($noproxy); 
14302:     # Who controls proxy settings for server
14303:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14304:     my $proxyinfo = &get_proxy_settings($dom_in_use);
14305:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14306:         if ($proxyinfo->{'vpnint'}) {
14307:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14308:                 return $from_ip;
14309:             }
14310:         }
14311:         if ($proxyinfo->{'trusted'}) {
14312:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14313:                 my $ipheader = $proxyinfo->{'ipheader'};
14314:                 my ($ip,$xfor);
14315:                 if (ref($r)) {
14316:                     if ($ipheader) {
14317:                         $ip = $r->headers_in->{$ipheader};
14318:                     }
14319:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
14320:                 } else {
14321:                     if ($ipheader) {
14322:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
14323:                     }
14324:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14325:                 }
14326:                 if (($ip eq '') && ($xfor ne '')) {
14327:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14328:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14329:                             $ip = $poss_ip;
14330:                             last;
14331:                         }
14332:                     }
14333:                 }
14334:                 if ($ip ne '') {
14335:                     return $ip;
14336:                 }
14337:             }
14338:         }
14339:     }
14340:     return $from_ip;
14341: }
14342: 
14343: sub get_proxy_settings {
14344:     my ($dom_in_use) = @_;
14345:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14346:     my $proxyinfo = {
14347:                        ipheader => $domdefaults{'waf_ipheader'},
14348:                        trusted  => $domdefaults{'waf_trusted'},
14349:                        vpnint   => $domdefaults{'waf_vpnint'},
14350:                        vpnext   => $domdefaults{'waf_vpnext'},
14351:                     };
14352:     return $proxyinfo;
14353: }
14354: 
14355: sub ip_match {
14356:     my ($ip,$pattern_str) = @_;
14357:     $ip=Net::CIDR::cidrvalidate($ip);
14358:     if ($ip) {
14359:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14360:     }
14361:     return;
14362: }
14363: 
14364: sub get_proxy_alias {
14365:     my $lonhost = $perlvar{'lonHostID'};
14366:     if ($lonhost ne '') {
14367:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonhost);
14368:         if ($cached) {
14369:             return $alias;
14370:         }
14371:         my $dom = &Apache::lonnet::host_domain($lonhost);
14372:         if ($dom ne '') {
14373:             my $cachetime = 60*60*24;
14374:             my %domconfig =
14375:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14376:             my $alias;
14377:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14378:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14379:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonhost};
14380:                 }
14381:             }
14382:             return &do_cache_new('proxyalias',$lonhost,$alias,$cachetime);
14383:         }
14384:     }
14385:     return;
14386: }
14387: 
14388: # ------------------------------------------------------------- Declutters URLs
14389: 
14390: sub declutter {
14391:     my $thisfn=shift;
14392:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14393:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14394:         $thisfn=~s{^/home/httpd/html}{};
14395:     }
14396:     $thisfn=~s/^\///;
14397:     $thisfn=~s|^adm/wrapper/||;
14398:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14399:     $thisfn=~s/^res\///;
14400:     $thisfn=~s/^priv\///;
14401:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14402:         $thisfn=~s/\?.+$//;
14403:     }
14404:     return $thisfn;
14405: }
14406: 
14407: # ------------------------------------------------------------- Clutter up URLs
14408: 
14409: sub clutter {
14410:     my $thisfn='/'.&declutter(shift);
14411:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14412: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14413:        $thisfn='/res'.$thisfn; 
14414:     }
14415:     if ($thisfn !~m|^/adm|) {
14416: 	if ($thisfn =~ m|^/ext/|) {
14417: 	    $thisfn='/adm/wrapper'.$thisfn;
14418: 	} else {
14419: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14420: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14421: 	    if ($embstyle eq 'ssi'
14422: 		|| ($embstyle eq 'hdn')
14423: 		|| ($embstyle eq 'rat')
14424: 		|| ($embstyle eq 'prv')
14425: 		|| ($embstyle eq 'ign')) {
14426: 		#do nothing with these
14427: 	    } elsif (($embstyle eq 'img') 
14428: 		|| ($embstyle eq 'emb')
14429: 		|| ($embstyle eq 'wrp')) {
14430: 		$thisfn='/adm/wrapper'.$thisfn;
14431: 	    } elsif ($embstyle eq 'unk'
14432: 		     && $thisfn!~/\.(sequence|page)$/) {
14433: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14434: 	    } else {
14435: #		&logthis("Got a blank emb style");
14436: 	    }
14437: 	}
14438:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14439:         $thisfn='/adm/wrapper'.$thisfn;
14440:     }
14441:     return $thisfn;
14442: }
14443: 
14444: sub clutter_with_no_wrapper {
14445:     my $uri = &clutter(shift);
14446:     if ($uri =~ m-^/adm/-) {
14447: 	$uri =~ s-^/adm/wrapper/-/-;
14448: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14449:     }
14450:     return $uri;
14451: }
14452: 
14453: sub freeze_escape {
14454:     my ($value)=@_;
14455:     if (ref($value)) {
14456: 	$value=&nfreeze($value);
14457: 	return '__FROZEN__'.&escape($value);
14458:     }
14459:     return &escape($value);
14460: }
14461: 
14462: 
14463: sub thaw_unescape {
14464:     my ($value)=@_;
14465:     if ($value =~ /^__FROZEN__/) {
14466: 	substr($value,0,10,undef);
14467: 	$value=&unescape($value);
14468: 	return &thaw($value);
14469:     }
14470:     return &unescape($value);
14471: }
14472: 
14473: sub correct_line_ends {
14474:     my ($result)=@_;
14475:     $$result =~s/\r\n/\n/mg;
14476:     $$result =~s/\r/\n/mg;
14477: }
14478: # ================================================================ Main Program
14479: 
14480: sub goodbye {
14481:    &logthis("Starting Shut down");
14482: #not converted to using infrastruture and probably shouldn't be
14483:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14484: #converted
14485: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14486:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14487: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14488: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14489: #1.1 only
14490: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14491: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14492: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14493: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14494:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14495:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14496:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14497:    &flushcourselogs();
14498:    &logthis("Shutting down");
14499: }
14500: 
14501: sub get_dns {
14502:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14503:     if (!$ignore_cache) {
14504: 	my ($content,$cached)=
14505: 	    &Apache::lonnet::is_cached_new('dns',$url);
14506: 	if ($cached) {
14507: 	    &$func($content,$hashref);
14508: 	    return;
14509: 	}
14510:     }
14511: 
14512:     my %alldns;
14513:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14514:         foreach my $dns (<$config>) {
14515: 	    next if ($dns !~ /^\^(\S*)/x);
14516:             my $line = $1;
14517:             my ($host,$protocol) = split(/:/,$line);
14518:             if ($protocol ne 'https') {
14519:                 $protocol = 'http';
14520:             }
14521: 	    $alldns{$host} = $protocol;
14522:         }
14523:         close($config);
14524:     }
14525:     while (%alldns) {
14526: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14527: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14528:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14529:         delete($alldns{$dns});
14530: 	next if ($response->is_error());
14531:         if ($url eq '/adm/dns/loncapaCRL') {
14532:             return &$func($response);
14533:         } else {
14534: 	    my @content = split("\n",$response->content);
14535: 	    unless ($nocache) {
14536: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14537: 	    }
14538: 	    &$func(\@content,$hashref);
14539:             return;
14540:         }
14541:     }
14542:     my $which = (split('/',$url,4))[3];
14543:     if ($which eq 'loncapaCRL') {
14544:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14545:         if (-e $diskfile) {
14546:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14547:         } else {
14548:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14549:         }
14550:     } else {
14551:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14552:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14553:             my @content = <$config>;
14554:             close($config);
14555:             &$func(\@content,$hashref);
14556:         }
14557:     }
14558:     return;
14559: }
14560: 
14561: # ------------------------------------------------------Get DNS checksums file
14562: sub parse_dns_checksums_tab {
14563:     my ($lines,$hashref) = @_;
14564:     my $lonhost = $perlvar{'lonHostID'};
14565:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14566:     my $loncaparev = &get_server_loncaparev($machine_dom);
14567:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14568:     my $webconfdir = '/etc/httpd/conf';
14569:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14570:         $webconfdir = '/etc/apache2';
14571:     } elsif ($distro =~ /^sles(\d+)$/) {
14572:         if ($1 >= 10) {
14573:             $webconfdir = '/etc/apache2';
14574:         }
14575:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14576:         if ($1 >= 10.0) {
14577:             $webconfdir = '/etc/apache2';
14578:         }
14579:     }
14580:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14581:     my (%chksum,%revnum);
14582:     if (ref($lines) eq 'ARRAY') {
14583:         chomp(@{$lines});
14584:         my $version = shift(@{$lines});
14585:         if ($version eq $release) {  
14586:             foreach my $line (@{$lines}) {
14587:                 my ($file,$version,$shasum) = split(/,/,$line);
14588:                 if ($file =~ m{^/etc/httpd/conf}) {
14589:                     if ($webconfdir eq '/etc/apache2') {
14590:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14591:                     }
14592:                 }
14593:                 $chksum{$file} = $shasum;
14594:                 $revnum{$file} = $version;
14595:             }
14596:             if (ref($hashref) eq 'HASH') {
14597:                 %{$hashref} = (
14598:                                 sums     => \%chksum,
14599:                                 versions => \%revnum,
14600:                               );
14601:             }
14602:         }
14603:     }
14604:     return;
14605: }
14606: 
14607: sub fetch_dns_checksums {
14608:     my %checksums;
14609:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14610:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14611:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14612:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14613:              \%checksums);
14614:     return \%checksums;
14615: }
14616: 
14617: sub fetch_crl_pemfile {
14618:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14619: }
14620: 
14621: sub save_crl_pem {
14622:     my ($response) = @_;
14623:     my ($msg,$hadchanges);
14624:     if (ref($response)) {
14625:         my $now = time;
14626:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14627:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14628:         if (open(my $fh,'>',"$tmpcrl")) {
14629:             print $fh $response->content;
14630:             close($fh);
14631:             if (-e $lonca) {
14632:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14633:                     my $check = <PIPE>;
14634:                     close(PIPE);
14635:                     chomp($check);
14636:                     if ($check eq 'verify OK') {
14637:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14638:                         my $backup;
14639:                         if (-e $dest) {
14640:                             if (&File::Copy::move($dest,"$dest.bak")) {
14641:                                 $backup = 'ok';
14642:                             }
14643:                         }
14644:                         if (&File::Copy::move($tmpcrl,$dest)) {
14645:                             $msg = 'ok';
14646:                             if ($backup) {
14647:                                 my (%oldnums,%newnums);
14648:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14649:                                     while (<PIPE>) {
14650:                                         $oldnums{(split(/:/))[1]} = 1;
14651:                                     }
14652:                                     close(PIPE);
14653:                                 }
14654:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14655:                                     while(<PIPE>) {
14656:                                         $newnums{(split(/:/))[1]} = 1;
14657:                                     }
14658:                                     close(PIPE);
14659:                                 }
14660:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14661:                                     unless (exists($oldnums{$key})) {
14662:                                         $hadchanges = 1;
14663:                                         last;
14664:                                     }
14665:                                 }
14666:                                 unless ($hadchanges) {
14667:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14668:                                         unless (exists($newnums{$key})) {
14669:                                             $hadchanges = 1;
14670:                                             last;
14671:                                         }
14672:                                     }
14673:                                 }
14674:                             }
14675:                         }
14676:                     } else {
14677:                         unlink($tmpcrl);
14678:                     }
14679:                 } else {
14680:                     unlink($tmpcrl);
14681:                 }
14682:             } else {
14683:                 unlink($tmpcrl);
14684:             }
14685:         }
14686:     }
14687:     return ($msg,$hadchanges);
14688: }
14689: 
14690: # ------------------------------------------------------------ Read domain file
14691: {
14692:     my $loaded;
14693:     my %domain;
14694: 
14695:     sub parse_domain_tab {
14696: 	my ($lines) = @_;
14697: 	foreach my $line (@$lines) {
14698: 	    next if ($line =~ /^(\#|\s*$ )/x);
14699: 
14700: 	    chomp($line);
14701: 	    my ($name,@elements) = split(/:/,$line,9);
14702: 	    my %this_domain;
14703: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14704: 			       'lang_def', 'city', 'longi', 'lati',
14705: 			       'primary') {
14706: 		$this_domain{$field} = shift(@elements);
14707: 	    }
14708: 	    $domain{$name} = \%this_domain;
14709: 	}
14710:     }
14711: 
14712:     sub reset_domain_info {
14713: 	undef($loaded);
14714: 	undef(%domain);
14715:     }
14716: 
14717:     sub load_domain_tab {
14718: 	my ($ignore_cache,$nocache) = @_;
14719: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14720: 	my $fh;
14721: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14722: 	    my @lines = <$fh>;
14723: 	    &parse_domain_tab(\@lines);
14724: 	}
14725: 	close($fh);
14726: 	$loaded = 1;
14727:     }
14728: 
14729:     sub domain {
14730: 	&load_domain_tab() if (!$loaded);
14731: 
14732: 	my ($name,$what) = @_;
14733: 	return if ( !exists($domain{$name}) );
14734: 
14735: 	if (!$what) {
14736: 	    return $domain{$name}{'description'};
14737: 	}
14738: 	return $domain{$name}{$what};
14739:     }
14740: 
14741:     sub domain_info {
14742:         &load_domain_tab() if (!$loaded);
14743:         return %domain;
14744:     }
14745: 
14746: }
14747: 
14748: 
14749: # ------------------------------------------------------------- Read hosts file
14750: {
14751:     my %hostname;
14752:     my %hostdom;
14753:     my %libserv;
14754:     my $loaded;
14755:     my %name_to_host;
14756:     my %internetdom;
14757:     my %LC_dns_serv;
14758: 
14759:     sub parse_hosts_tab {
14760: 	my ($file) = @_;
14761: 	foreach my $configline (@$file) {
14762: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14763:             chomp($configline);
14764: 	    if ($configline =~ /^\^/) {
14765:                 if ($configline =~ /^\^([\w.\-]+)/) {
14766:                     $LC_dns_serv{$1} = 1;
14767:                 }
14768:                 next;
14769:             }
14770: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14771: 	    $name=~s/\s//g;
14772: 	    if ($id && $domain && $role && $name) {
14773:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14774:                     my $curr = $hostname{$id};
14775:                     my $skip;
14776:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14777:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14778:                             $skip = 1;
14779:                         } else {
14780:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14781:                         }
14782:                     }
14783:                     unless ($skip) {
14784:                         push(@{$name_to_host{$name}},$id);
14785:                     }
14786:                 } else {
14787:                     push(@{$name_to_host{$name}},$id);
14788:                 }
14789: 		$hostname{$id}=$name;
14790: 		$hostdom{$id}=$domain;
14791: 		if ($role eq 'library') { $libserv{$id}=$name; }
14792:                 if (defined($protocol)) {
14793:                     if ($protocol eq 'https') {
14794:                         $protocol{$id} = $protocol;
14795:                     } else {
14796:                         $protocol{$id} = 'http'; 
14797:                     }
14798:                 } else {
14799:                     $protocol{$id} = 'http';
14800:                 }
14801:                 if (defined($intdom)) {
14802:                     $internetdom{$id} = $intdom;
14803:                 }
14804: 	    }
14805: 	}
14806:     }
14807:     
14808:     sub reset_hosts_info {
14809: 	&purge_remembered();
14810: 	&reset_domain_info();
14811: 	&reset_hosts_ip_info();
14812:         undef(%internetdom);
14813: 	undef(%name_to_host);
14814: 	undef(%hostname);
14815: 	undef(%hostdom);
14816: 	undef(%libserv);
14817: 	undef($loaded);
14818:     }
14819: 
14820:     sub load_hosts_tab {
14821: 	my ($ignore_cache,$nocache) = @_;
14822: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14823: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14824: 	my @config = <$config>;
14825: 	&parse_hosts_tab(\@config);
14826: 	close($config);
14827: 	$loaded=1;
14828:     }
14829: 
14830:     sub hostname {
14831: 	&load_hosts_tab() if (!$loaded);
14832: 
14833: 	my ($lonid) = @_;
14834: 	return $hostname{$lonid};
14835:     }
14836: 
14837:     sub all_hostnames {
14838: 	&load_hosts_tab() if (!$loaded);
14839: 
14840: 	return %hostname;
14841:     }
14842: 
14843:     sub all_names {
14844:         my ($ignore_cache,$nocache) = @_;
14845: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14846: 
14847: 	return %name_to_host;
14848:     }
14849: 
14850:     sub all_host_domain {
14851:         &load_hosts_tab() if (!$loaded);
14852:         return %hostdom;
14853:     }
14854: 
14855:     sub all_host_intdom {
14856:         &load_hosts_tab() if (!$loaded);
14857:         return %internetdom;
14858:     }
14859: 
14860:     sub is_library {
14861: 	&load_hosts_tab() if (!$loaded);
14862: 
14863: 	return exists($libserv{$_[0]});
14864:     }
14865: 
14866:     sub all_library {
14867: 	&load_hosts_tab() if (!$loaded);
14868: 
14869: 	return %libserv;
14870:     }
14871: 
14872:     sub unique_library {
14873: 	#2x reverse removes all hostnames that appear more than once
14874:         my %unique = reverse &all_library();
14875:         return reverse %unique;
14876:     }
14877: 
14878:     sub get_servers {
14879: 	&load_hosts_tab() if (!$loaded);
14880: 
14881: 	my ($domain,$type) = @_;
14882: 	my %possible_hosts = ($type eq 'library') ? %libserv
14883: 	                                          : %hostname;
14884: 	my %result;
14885: 	if (ref($domain) eq 'ARRAY') {
14886: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14887: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14888: 		    $result{$host} = $hostname;
14889: 		}
14890: 	    }
14891: 	} else {
14892: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14893: 		if ($hostdom{$host} eq $domain) {
14894: 		    $result{$host} = $hostname;
14895: 		}
14896: 	    }
14897: 	}
14898: 	return %result;
14899:     }
14900: 
14901:     sub get_unique_servers {
14902:         my %unique = reverse &get_servers(@_);
14903: 	return reverse %unique;
14904:     }
14905: 
14906:     sub host_domain {
14907: 	&load_hosts_tab() if (!$loaded);
14908: 
14909: 	my ($lonid) = @_;
14910: 	return $hostdom{$lonid};
14911:     }
14912: 
14913:     sub all_domains {
14914: 	&load_hosts_tab() if (!$loaded);
14915: 
14916: 	my %seen;
14917: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14918: 	return @uniq;
14919:     }
14920: 
14921:     sub internet_dom {
14922:         &load_hosts_tab() if (!$loaded);
14923: 
14924:         my ($lonid) = @_;
14925:         return $internetdom{$lonid};
14926:     }
14927: 
14928:     sub is_LC_dns {
14929:         &load_hosts_tab() if (!$loaded);
14930: 
14931:         my ($hostname) = @_;
14932:         return exists($LC_dns_serv{$hostname});
14933:     }
14934: 
14935: }
14936: 
14937: { 
14938:     my %iphost;
14939:     my %name_to_ip;
14940:     my %lonid_to_ip;
14941: 
14942:     sub get_hosts_from_ip {
14943: 	my ($ip) = @_;
14944: 	my %iphosts = &get_iphost();
14945: 	if (ref($iphosts{$ip})) {
14946: 	    return @{$iphosts{$ip}};
14947: 	}
14948: 	return;
14949:     }
14950:     
14951:     sub reset_hosts_ip_info {
14952: 	undef(%iphost);
14953: 	undef(%name_to_ip);
14954: 	undef(%lonid_to_ip);
14955:     }
14956: 
14957:     sub get_host_ip {
14958: 	my ($lonid) = @_;
14959: 	if (exists($lonid_to_ip{$lonid})) {
14960: 	    return $lonid_to_ip{$lonid};
14961: 	}
14962: 	my $name=&hostname($lonid);
14963:    	my $ip = gethostbyname($name);
14964: 	return if (!$ip || length($ip) ne 4);
14965: 	$ip=inet_ntoa($ip);
14966: 	$name_to_ip{$name}   = $ip;
14967: 	$lonid_to_ip{$lonid} = $ip;
14968: 	return $ip;
14969:     }
14970:     
14971:     sub get_iphost {
14972: 	my ($ignore_cache,$nocache) = @_;
14973: 
14974: 	if (!$ignore_cache) {
14975: 	    if (%iphost) {
14976: 		return %iphost;
14977: 	    }
14978: 	    my ($ip_info,$cached)=
14979: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14980: 	    if ($cached) {
14981: 		%iphost      = %{$ip_info->[0]};
14982: 		%name_to_ip  = %{$ip_info->[1]};
14983: 		%lonid_to_ip = %{$ip_info->[2]};
14984: 		return %iphost;
14985: 	    }
14986: 	}
14987: 
14988: 	# get yesterday's info for fallback
14989: 	my %old_name_to_ip;
14990: 	my ($ip_info,$cached)=
14991: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14992: 	if ($cached) {
14993: 	    %old_name_to_ip = %{$ip_info->[1]};
14994: 	}
14995: 
14996: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14997: 	foreach my $name (keys(%name_to_host)) {
14998: 	    my $ip;
14999: 	    if (!exists($name_to_ip{$name})) {
15000: 		$ip = gethostbyname($name);
15001: 		if (!$ip || length($ip) ne 4) {
15002: 		    if (defined($old_name_to_ip{$name})) {
15003: 			$ip = $old_name_to_ip{$name};
15004: 			&logthis("Can't find $name defaulting to old $ip");
15005: 		    } else {
15006: 			&logthis("Name $name no IP found");
15007: 			next;
15008: 		    }
15009: 		} else {
15010: 		    $ip=inet_ntoa($ip);
15011: 		}
15012: 		$name_to_ip{$name} = $ip;
15013: 	    } else {
15014: 		$ip = $name_to_ip{$name};
15015: 	    }
15016: 	    foreach my $id (@{ $name_to_host{$name} }) {
15017: 		$lonid_to_ip{$id} = $ip;
15018: 	    }
15019: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
15020: 	}
15021:         unless ($nocache) {
15022: 	    &do_cache_new('iphost','iphost',
15023: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
15024: 		          48*60*60);
15025:         }
15026: 
15027: 	return %iphost;
15028:     }
15029: 
15030:     #
15031:     #  Given a DNS returns the loncapa host name for that DNS 
15032:     # 
15033:     sub host_from_dns {
15034:         my ($dns) = @_;
15035:         my @hosts;
15036:         my $ip;
15037: 
15038:         if (exists($name_to_ip{$dns})) {
15039:             $ip = $name_to_ip{$dns};
15040:         }
15041:         if (!$ip) {
15042:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15043:             if (length($ip) == 4) { 
15044: 	        $ip   = &IO::Socket::inet_ntoa($ip);
15045:             }
15046:         }
15047:         if ($ip) {
15048: 	    @hosts = get_hosts_from_ip($ip);
15049: 	    return $hosts[0];
15050:         }
15051:         return undef;
15052:     }
15053: 
15054:     sub get_internet_names {
15055:         my ($lonid) = @_;
15056:         return if ($lonid eq '');
15057:         my ($idnref,$cached)=
15058:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
15059:         if ($cached) {
15060:             return $idnref;
15061:         }
15062:         my $ip = &get_host_ip($lonid);
15063:         my @hosts = &get_hosts_from_ip($ip);
15064:         my %iphost = &get_iphost();
15065:         my (@idns,%seen);
15066:         foreach my $id (@hosts) {
15067:             my $dom = &host_domain($id);
15068:             my $prim_id = &domain($dom,'primary');
15069:             my $prim_ip = &get_host_ip($prim_id);
15070:             next if ($seen{$prim_ip});
15071:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15072:                 foreach my $id (@{$iphost{$prim_ip}}) {
15073:                     my $intdom = &internet_dom($id);
15074:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
15075:                         push(@idns,$intdom);
15076:                     }
15077:                 }
15078:             }
15079:             $seen{$prim_ip} = 1;
15080:         }
15081:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15082:     }
15083: 
15084: }
15085: 
15086: sub all_loncaparevs {
15087:     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);
15088: }
15089: 
15090: # ---------------------------------------------------------- Read loncaparev table
15091: {
15092:     sub load_loncaparevs { 
15093:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15094:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15095:                 while (my $configline=<$config>) {
15096:                     chomp($configline);
15097:                     my ($hostid,$loncaparev)=split(/:/,$configline);
15098:                     $loncaparevs{$hostid}=$loncaparev;
15099:                 }
15100:                 close($config);
15101:             }
15102:         }
15103:     }
15104: }
15105: 
15106: # ---------------------------------------------------------- Read serverhostID table
15107: {
15108:     sub load_serverhomeIDs {
15109:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15110:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15111:                 while (my $configline=<$config>) {
15112:                     chomp($configline);
15113:                     my ($name,$id)=split(/:/,$configline);
15114:                     $serverhomeIDs{$name}=$id;
15115:                 }
15116:                 close($config);
15117:             }
15118:         }
15119:     }
15120: }
15121: 
15122: 
15123: BEGIN {
15124: 
15125: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15126:     unless ($readit) {
15127: {
15128:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15129:     %perlvar = (%perlvar,%{$configvars});
15130: }
15131: 
15132: 
15133: # ------------------------------------------------------ Read spare server file
15134: {
15135:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15136: 
15137:     while (my $configline=<$config>) {
15138:        chomp($configline);
15139:        if ($configline) {
15140: 	   my ($host,$type) = split(':',$configline,2);
15141: 	   if (!defined($type) || $type eq '') { $type = 'default' };
15142: 	   push(@{ $spareid{$type} }, $host);
15143:        }
15144:     }
15145:     close($config);
15146: }
15147: # ------------------------------------------------------------ Read permissions
15148: {
15149:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15150: 
15151:     while (my $configline=<$config>) {
15152: 	chomp($configline);
15153: 	if ($configline) {
15154: 	    my ($role,$perm)=split(/ /,$configline);
15155: 	    if ($perm ne '') { $pr{$role}=$perm; }
15156: 	}
15157:     }
15158:     close($config);
15159: }
15160: 
15161: # -------------------------------------------- Read plain texts for permissions
15162: {
15163:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15164: 
15165:     while (my $configline=<$config>) {
15166: 	chomp($configline);
15167: 	if ($configline) {
15168: 	    my ($short,@plain)=split(/:/,$configline);
15169:             %{$prp{$short}} = ();
15170: 	    if (@plain > 0) {
15171:                 $prp{$short}{'std'} = $plain[0];
15172:                 for (my $i=1; $i<@plain; $i++) {
15173:                     $prp{$short}{'alt'.$i} = $plain[$i];  
15174:                 }
15175:             }
15176: 	}
15177:     }
15178:     close($config);
15179: }
15180: 
15181: # ---------------------------------------------------------- Read package table
15182: {
15183:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15184: 
15185:     while (my $configline=<$config>) {
15186: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15187: 	chomp($configline);
15188: 	my ($short,$plain)=split(/:/,$configline);
15189: 	my ($pack,$name)=split(/\&/,$short);
15190: 	if ($plain ne '') {
15191: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
15192: 	    $packagetab{$short}=$plain; 
15193: 	}
15194:     }
15195:     close($config);
15196: }
15197: 
15198: # ---------------------------------------------------------- Read loncaparev table
15199: 
15200: &load_loncaparevs();
15201: 
15202: # ---------------------------------------------------------- Read serverhostID table
15203: 
15204: &load_serverhomeIDs();
15205: 
15206: # ---------------------------------------------------------- Read releaseslist XML
15207: {
15208:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15209:     if (-e $file) {
15210:         my $parser = HTML::LCParser->new($file);
15211:         while (my $token = $parser->get_token()) {
15212:             if ($token->[0] eq 'S') {
15213:                 my $item = $token->[1];
15214:                 my $name = $token->[2]{'name'};
15215:                 my $value = $token->[2]{'value'};
15216:                 my $valuematch = $token->[2]{'valuematch'};
15217:                 my $namematch = $token->[2]{'namematch'};
15218:                 if ($item eq 'parameter') {
15219:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15220:                         my $release = $parser->get_text();
15221:                         $release =~ s/(^\s*|\s*$ )//gx;
15222:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15223:                     }
15224:                 } elsif ($item ne '' && $name ne '') {
15225:                     my $release = $parser->get_text();
15226:                     $release =~ s/(^\s*|\s*$ )//gx;
15227:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
15228:                 }
15229:             }
15230:         }
15231:     }
15232: }
15233: 
15234: # ---------------------------------------------------------- Read managers table
15235: {
15236:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15237:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15238:             while (my $configline=<$config>) {
15239:                 chomp($configline);
15240:                 next if ($configline =~ /^\#/);
15241:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15242:                     $managerstab{$configline} = 1;
15243:                 }
15244:             }
15245:             close($config);
15246:         }
15247:     }
15248: }
15249: 
15250: # ------------- set up temporary directory
15251: {
15252:     $tmpdir = LONCAPA::tempdir();
15253: 
15254: }
15255: 
15256: # ------------- set default texengine (domain default overrides this)
15257: {
15258:     $deftex = LONCAPA::texengine();
15259: }
15260: 
15261: # ------------- set default minimum length for passwords for internal auth users
15262: {
15263:     $passwdmin = LONCAPA::passwd_min();
15264: }
15265: 
15266: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
15267: 				'compress_threshold'=> 20_000,
15268:  			        });
15269: 
15270: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15271: $dumpcount=0;
15272: $locknum=0;
15273: 
15274: &logtouch();
15275: &logthis('<font color="yellow">INFO: Read configuration</font>');
15276: $readit=1;
15277:     {
15278: 	use integer;
15279: 	my $test=(2**32)+1;
15280: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15281: 	&logthis(" Detected 64bit platform ($_64bit)");
15282:     }
15283: }
15284: }
15285: 
15286: 1;
15287: __END__
15288: 
15289: =pod
15290: 
15291: =head1 NAME
15292: 
15293: Apache::lonnet - Subroutines to ask questions about things in the network.
15294: 
15295: =head1 SYNOPSIS
15296: 
15297: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15298: 
15299:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15300: 
15301: Common parameters:
15302: 
15303: =over 4
15304: 
15305: =item *
15306: 
15307: $uname : an internal username (if $cname expecting a course Id specifically)
15308: 
15309: =item *
15310: 
15311: $udom : a domain (if $cdom expecting a course's domain specifically)
15312: 
15313: =item *
15314: 
15315: $symb : a resource instance identifier
15316: 
15317: =item *
15318: 
15319: $namespace : the name of a .db file that contains the data needed or
15320: being set.
15321: 
15322: =back
15323: 
15324: =head1 OVERVIEW
15325: 
15326: lonnet provides subroutines which interact with the
15327: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15328: about classes, users, and resources.
15329: 
15330: For many of these objects you can also use this to store data about
15331: them or modify them in various ways.
15332: 
15333: =head2 Symbs
15334: 
15335: To identify a specific instance of a resource, LON-CAPA uses symbols
15336: or "symbs"X<symb>. These identifiers are built from the URL of the
15337: map, the resource number of the resource in the map, and the URL of
15338: the resource itself. The latter is somewhat redundant, but might help
15339: if maps change.
15340: 
15341: An example is
15342: 
15343:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15344: 
15345: The respective map entry is
15346: 
15347:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15348:   title="Problem 2">
15349:  </resource>
15350: 
15351: Symbs are used by the random number generator, as well as to store and
15352: restore data specific to a certain instance of for example a problem.
15353: 
15354: =head2 Storing And Retrieving Data
15355: 
15356: X<store()>X<cstore()>X<restore()>Three of the most important functions
15357: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15358: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15359: is is the non-critical message twin of cstore. These functions are for
15360: handlers to store a perl hash to a user's permanent data space in an
15361: easy manner, and to retrieve it again on another call. It is expected
15362: that a handler would use this once at the beginning to retrieve data,
15363: and then again once at the end to send only the new data back.
15364: 
15365: The data is stored in the user's data directory on the user's
15366: homeserver under the ID of the course.
15367: 
15368: The hash that is returned by restore will have all of the previous
15369: value for all of the elements of the hash.
15370: 
15371: Example:
15372: 
15373:  #creating a hash
15374:  my %hash;
15375:  $hash{'foo'}='bar';
15376: 
15377:  #storing it
15378:  &Apache::lonnet::cstore(\%hash);
15379: 
15380:  #changing a value
15381:  $hash{'foo'}='notbar';
15382: 
15383:  #adding a new value
15384:  $hash{'bar'}='foo';
15385:  &Apache::lonnet::cstore(\%hash);
15386: 
15387:  #retrieving the hash
15388:  my %history=&Apache::lonnet::restore();
15389: 
15390:  #print the hash
15391:  foreach my $key (sort(keys(%history))) {
15392:    print("\%history{$key} = $history{$key}");
15393:  }
15394: 
15395: Will print out:
15396: 
15397:  %history{1:foo} = bar
15398:  %history{1:keys} = foo:timestamp
15399:  %history{1:timestamp} = 990455579
15400:  %history{2:bar} = foo
15401:  %history{2:foo} = notbar
15402:  %history{2:keys} = foo:bar:timestamp
15403:  %history{2:timestamp} = 990455580
15404:  %history{bar} = foo
15405:  %history{foo} = notbar
15406:  %history{timestamp} = 990455580
15407:  %history{version} = 2
15408: 
15409: Note that the special hash entries C<keys>, C<version> and
15410: C<timestamp> were added to the hash. C<version> will be equal to the
15411: total number of versions of the data that have been stored. The
15412: C<timestamp> attribute will be the UNIX time the hash was
15413: stored. C<keys> is available in every historical section to list which
15414: keys were added or changed at a specific historical revision of a
15415: hash.
15416: 
15417: B<Warning>: do not store the hash that restore returns directly. This
15418: will cause a mess since it will restore the historical keys as if the
15419: were new keys. I.E. 1:foo will become 1:1:foo etc.
15420: 
15421: Calling convention:
15422: 
15423:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15424:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15425: 
15426: For more detailed information, see lonnet specific documentation.
15427: 
15428: =head1 RETURN MESSAGES
15429: 
15430: =over 4
15431: 
15432: =item * B<con_lost>: unable to contact remote host
15433: 
15434: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15435: when the connection is brought back up
15436: 
15437: =item * B<con_failed>: unable to contact remote host and unable to save message
15438: for later delivery
15439: 
15440: =item * B<error:>: an error a occurred, a description of the error follows the :
15441: 
15442: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15443: that was requested
15444: 
15445: =back
15446: 
15447: =head1 PUBLIC SUBROUTINES
15448: 
15449: =head2 Session Environment Functions
15450: 
15451: =over 4
15452: 
15453: =item * 
15454: X<appenv()>
15455: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15456: the user envirnoment file, and will be restored for each access this
15457: user makes during this session, also modifies the %env for the current
15458: process. Optional rolesarrayref - if defined contains a reference to an array
15459: of roles which are exempt from the restriction on modifying user.role entries 
15460: in the user's environment.db and in %env.    
15461: 
15462: =item *
15463: X<delenv()>
15464: B<delenv($delthis,$regexp)>: removes all items from the session
15465: environment file that begin with $delthis. If the 
15466: optional second arg - $regexp - is true, $delthis is treated as a 
15467: regular expression, otherwise \Q$delthis\E is used. 
15468: The values are also deleted from the current processes %env.
15469: 
15470: =item * get_env_multiple($name) 
15471: 
15472: gets $name from the %env hash, it seemlessly handles the cases where multiple
15473: values may be defined and end up as an array ref.
15474: 
15475: returns an array of values
15476: 
15477: =back
15478: 
15479: =head2 User Information
15480: 
15481: =over 4
15482: 
15483: =item *
15484: X<queryauthenticate()>
15485: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15486: authentication scheme
15487: 
15488: =item *
15489: X<authenticate()>
15490: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15491: authenticate user from domain's lib servers (first use the current
15492: one). C<$upass> should be the users password.
15493: $checkdefauth is optional (value is 1 if a check should be made to
15494:    authenticate user using default authentication method, and allow
15495:    account creation if username does not have account in the domain).
15496: $clientcancheckhost is optional (value is 1 if checking whether the
15497:    server can host will occur on the client side in lonauth.pm).   
15498: 
15499: =item *
15500: X<homeserver()>
15501: B<homeserver($uname,$udom)>: find the server which has
15502: the user's directory and files (there must be only one), this caches
15503: the answer, and also caches if there is a borken connection.
15504: 
15505: =item *
15506: X<idget()>
15507: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15508: a list of student/employee IDs or clicker IDs
15509: (student/employee IDs are a unique resource in a domain, there must be 
15510: only 1 ID per username, and only 1 username per ID in a specific domain).
15511: clickerIDs are not necessarily unique, as students might share clickers.
15512: (returns hash: id=>name,id=>name)
15513: 
15514: =item *
15515: X<idrget()>
15516: B<idrget($udom,@unames)>: find the IDs behind a list of
15517: usernames (returns hash: name=>id,name=>id)
15518: 
15519: =item *
15520: X<idput()>
15521: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15522: names and associated student/employee IDs or clicker IDs.
15523: 
15524: =item *
15525: X<iddel()>
15526: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15527: student/employee ID or clicker ID username look-ups from domain.
15528: The homeserver ($uhome) and namespace ($namespace) are optional.
15529: If no $uhome is provided, it will be determined usig &homeserver()
15530: for each user.  If no $namespace is provided, the default is ids.
15531: 
15532: =item *
15533: X<updateclickers()>
15534: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15535: clicker ID-to-username look-ups in clickers.db on library server.
15536: Permitted actions are add or del (i.e., add or delete). The 
15537: clickers.db contains clickerID as keys (escaped), and each corresponding
15538: value is an escaped comma-separated list of usernames (for whom the
15539: library server is the homeserver), who registered that particular ID.
15540: If $critical is true, the update will be sent via &critical, otherwise
15541: &reply() will be used.
15542: 
15543: =item *
15544: X<rolesinit()>
15545: B<rolesinit($udom,$username)>: get user privileges.
15546: returns user role, first access and timer interval hashes
15547: 
15548: =item *
15549: X<privileged()>
15550: B<privileged($username,$domain)>: returns a true if user has a
15551: privileged and active role (i.e. su or dc), false otherwise.
15552: 
15553: =item *
15554: X<getsection()>
15555: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15556: course $cname, return section name/number or '' for "not in course"
15557: and '-1' for "no section"
15558: 
15559: =item *
15560: X<userenvironment()>
15561: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15562: passed in @what from the requested user's environment, returns a hash
15563: 
15564: =item * 
15565: X<userlog_query()>
15566: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15567: activity.log file. %filters defines filters applied when parsing the
15568: log file. These can be start or end timestamps, or the type of action
15569: - log to look for Login or Logout events, check for Checkin or
15570: Checkout, role for role selection. The response is in the form
15571: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15572: escaped strings of the action recorded in the activity.log file.
15573: 
15574: =back
15575: 
15576: =head2 User Roles
15577: 
15578: =over 4
15579: 
15580: =item *
15581: 
15582: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15583: returns codes for allowed actions.
15584: 
15585: The first argument is required, all others are optional.
15586: 
15587: $priv is the privilege being checked.
15588: $uri contains additional information about what is being checked for access (e.g.,
15589: URL, course ID etc.). 
15590: $symb is the unique resource instance identifier in a course; if needed,
15591: but not provided, it will be retrieved via a call to &symbread(). 
15592: $role is the role for which a priv is being checked (only used if priv is evb). 
15593: $clientip is the user's IP address (only used when checking for access to portfolio 
15594: files).
15595: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15596: prevents recursive calls to &allowed.
15597: 
15598:  F: full access
15599:  U,I,K: authentication modes (cxx only)
15600:  '': forbidden
15601:  1: user needs to choose course
15602:  2: browse allowed
15603:  A: passphrase authentication needed
15604:  B: access temporarily blocked because of a blocking event in a course.
15605:  D: access blocked because access is required via session initiated via deep-link 
15606: 
15607: =item *
15608: 
15609: constructaccess($url,$setpriv) : check for access to construction space URL
15610: 
15611: See if the owner domain and name in the URL match those in the
15612: expected environment.  If so, return three element list
15613: ($ownername,$ownerdomain,$ownerhome).
15614: 
15615: Otherwise return the null string.
15616: 
15617: If second argument 'setpriv' is true, it assigns the privileges,
15618: and returns the same three element list, unless the owner has
15619: blocked "ad hoc" Domain Coordinator access to the Author Space,
15620: in which case the null string is returned.
15621: 
15622: =item *
15623: 
15624: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15625: define a custom role rolename set privileges in format of lonTabs/roles.tab
15626: for system, domain, and course level. $uname and $udom are optional (current
15627: user's username and domain will be used when either of $uname or $udom are absent.
15628: 
15629: =item *
15630: 
15631: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15632: (rolesplain.tab); plain text explanation of a user role term.
15633: $type is Course (default) or Community.
15634: If $forcedefault evaluates to true, text returned will be default 
15635: text for $type. Otherwise, if this is a course, the text returned 
15636: will be a custom name for the role (if defined in the course's 
15637: environment).  If no custom name is defined the default is returned.
15638:    
15639: =item *
15640: 
15641: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15642: All arguments are optional. Returns a hash of a roles, either for
15643: co-author/assistant author roles for a user's Construction Space
15644: (default), or if $context is 'userroles', roles for the user himself,
15645: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15646: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15647: For each key, value is set to colon-separated start and end times for
15648: the role.  If no username and domain are specified, will default to
15649: current user/domain. Types, roles, and roledoms are references to arrays
15650: of role statuses (active, future or previous), roles 
15651: (e.g., cc,in, st etc.) and domains of the roles which can be used
15652: to restrict the list of roles reported. If no array ref is 
15653: provided for types, will default to return only active roles.
15654: 
15655: =item *
15656: 
15657: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15658: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15659: 
15660: Additional optional arguments are: $type (if role checking is to be restricted 
15661: to certain user status types -- previous (expired roles), active (currently
15662: available roles) or future (roles available in the future), and
15663: $hideprivileged -- if true will not report course roles for users who
15664: have active Domain Coordinator role in course's domain or in additional
15665: domains (specified in 'Domains to check for privileged users' in course
15666: environment -- set via:  Course Settings -> Classlists and staff listing).
15667: 
15668: =item *
15669: 
15670: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15671: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15672: $possdomains and $possroles are optional array refs -- to domains to check and
15673: roles to check.  If $possdomains is not specified, a dump will be done of the
15674: users' roles.db to check for a dc or su role in any domain. This can be
15675: time consuming if &privileged is called repeatedly (e.g., when displaying a
15676: classlist), so in such cases, supplying a $possdomains array is preferred, as
15677: this then allows &privileged_by_domain() to be used, which caches the identity
15678: of privileged users, eliminating the need for repeated calls to &dump().
15679: 
15680: =item *
15681: 
15682: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15683: where the outer hash keys are domains specified in the $possdomains array ref,
15684: next inner hash keys are privileged roles specified in the $roles array ref,
15685: and the innermost hash contains key = value pairs for username:domain = end:start
15686: for active or future "privileged" users with that role in that domain. To avoid
15687: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15688: innerhash are cached using priv_$role and $dom as the identifiers.
15689: 
15690: =back
15691: 
15692: =head2 User Modification
15693: 
15694: =over 4
15695: 
15696: =item *
15697: 
15698: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15699: user for the level given by URL.  Optional start and end dates (leave empty
15700: string or zero for "no date")
15701: 
15702: =item *
15703: 
15704: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15705: change a users, password, possible return values are: ok,
15706: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15707: refused
15708: 
15709: =item *
15710: 
15711: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15712: 
15713: =item *
15714: 
15715: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15716:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15717: 
15718: will update user information (firstname,middlename,lastname,generation,
15719: permanentemail), and if forceid is true, student/employee ID also.
15720: A user's institutional affiliation(s) can also be updated.
15721: User information fields will not be overwritten with empty entries 
15722: unless the field is included in the $candelete array reference.
15723: This array is included when a single user is modified via "Manage Users",
15724: or when Autoupdate.pl is run by cron in a domain.
15725: 
15726: =item *
15727: 
15728: modifystudent
15729: 
15730: modify a student's enrollment and identification information.
15731: The course id is resolved based on the current user's environment.  
15732: This means the invoking user must be a course coordinator or otherwise
15733: associated with a course.
15734: 
15735: This call is essentially a wrapper for lonnet::modifyuser and
15736: lonnet::modify_student_enrollment
15737: 
15738: Inputs: 
15739: 
15740: =over 4
15741: 
15742: =item B<$udom> Student's loncapa domain
15743: 
15744: =item B<$uname> Student's loncapa login name
15745: 
15746: =item B<$uid> Student/Employee ID
15747: 
15748: =item B<$umode> Student's authentication mode
15749: 
15750: =item B<$upass> Student's password
15751: 
15752: =item B<$first> Student's first name
15753: 
15754: =item B<$middle> Student's middle name
15755: 
15756: =item B<$last> Student's last name
15757: 
15758: =item B<$gene> Student's generation
15759: 
15760: =item B<$usec> Student's section in course
15761: 
15762: =item B<$end> Unix time of the roles expiration
15763: 
15764: =item B<$start> Unix time of the roles start date
15765: 
15766: =item B<$forceid> If defined, allow $uid to be changed
15767: 
15768: =item B<$desiredhome> server to use as home server for student
15769: 
15770: =item B<$email> Student's permanent e-mail address
15771: 
15772: =item B<$type> Type of enrollment (auto or manual)
15773: 
15774: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15775: 
15776: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15777: 
15778: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15779: 
15780: =item B<$context> role change context (shown in User Management Logs display in a course)
15781: 
15782: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15783: 
15784: =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.
15785: 
15786: =back
15787: 
15788: =item *
15789: 
15790: modify_student_enrollment
15791: 
15792: Change a student's enrollment status in a class.  The environment variable
15793: 'role.request.course' must be defined for this function to proceed.
15794: 
15795: Inputs:
15796: 
15797: =over 4
15798: 
15799: =item $udom, student's domain
15800: 
15801: =item $uname, student's name
15802: 
15803: =item $uid, student's user id
15804: 
15805: =item $first, student's first name
15806: 
15807: =item $middle
15808: 
15809: =item $last
15810: 
15811: =item $gene
15812: 
15813: =item $usec
15814: 
15815: =item $end
15816: 
15817: =item $start
15818: 
15819: =item $type
15820: 
15821: =item $locktype
15822: 
15823: =item $cid
15824: 
15825: =item $selfenroll
15826: 
15827: =item $context
15828: 
15829: =item $credits, number of credits student will earn from this class
15830: 
15831: =item $instsec, institutional course section code for student
15832: 
15833: =back
15834: 
15835: 
15836: =item *
15837: 
15838: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15839: custom role; give a custom role to a user for the level given by URL.  Specify
15840: name and domain of role author, and role name
15841: 
15842: =item *
15843: 
15844: revokerole($udom,$uname,$url,$role) : revoke a role for url
15845: 
15846: =item *
15847: 
15848: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15849: 
15850: =back
15851: 
15852: =head2 Course Infomation
15853: 
15854: =over 4
15855: 
15856: =item *
15857: 
15858: coursedescription($courseid,$options) : returns a hash of information about the
15859: specified course id, including all environment settings for the
15860: course, the description of the course will be in the hash under the
15861: key 'description'
15862: 
15863: $options is an optional parameter that if supplied is a hash reference that controls
15864: what how this function works.  It has the following key/values:
15865: 
15866: =over 4
15867: 
15868: =item freshen_cache
15869: 
15870: If defined, and the environment cache for the course is valid, it is 
15871: returned in the returned hash.
15872: 
15873: =item one_time
15874: 
15875: If defined, the last cache time is set to _now_
15876: 
15877: =item user
15878: 
15879: If defined, the supplied username is used instead of the current user.
15880: 
15881: 
15882: =back
15883: 
15884: =item *
15885: 
15886: resdata($name,$domain,$type,@which) : request for current parameter
15887: setting for a specific $type, where $type is either 'course' or 'user',
15888: @what should be a list of parameters to ask about. This routine caches
15889: answers for 10 minutes.
15890: 
15891: =item *
15892: 
15893: get_courseresdata($courseid, $domain) : dump the entire course resource
15894: data base, returning a hash that is keyed by the resource name and has
15895: values that are the resource value.  I believe that the timestamps and
15896: versions are also returned.
15897: 
15898: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15899: supplemental content area. This routine caches the number of files for 
15900: 10 minutes.
15901: 
15902: =back
15903: 
15904: =head2 Course Modification
15905: 
15906: =over 4
15907: 
15908: =item *
15909: 
15910: writecoursepref($courseid,%prefs) : write preferences (environment
15911: database) for a course
15912: 
15913: =item *
15914: 
15915: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15916: 
15917: =item *
15918: 
15919: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15920: 
15921: =item *
15922: 
15923: is_course($courseid), is_course($cdom, $cnum)
15924: 
15925: Accepts either a combined $courseid (in the form of domain_courseid) or the
15926: two component version $cdom, $cnum. It checks if the specified course exists.
15927: 
15928: Returns:
15929:     undef if the course doesn't exist, otherwise
15930:     in scalar context the combined courseid.
15931:     in list context the two components of the course identifier, domain and 
15932:     courseid.    
15933: 
15934: =back
15935: 
15936: =head2 Bubblesheet Configuration
15937: 
15938: =over 4
15939: 
15940: =item *
15941: 
15942: get_scantron_config($which)
15943: 
15944: $which - the name of the configuration to parse from the file.
15945: 
15946: Parses and returns the bubblesheet configuration line selected as a
15947: hash of configuration file fields.
15948: 
15949: 
15950: Returns:
15951:     If the named configuration is not in the file, an empty
15952:     hash is returned.
15953: 
15954:     a hash with the fields
15955:       name         - internal name for the this configuration setup
15956:       description  - text to display to operator that describes this config
15957:       CODElocation - if 0 or the string 'none'
15958:                           - no CODE exists for this config
15959:                      if -1 || the string 'letter'
15960:                           - a CODE exists for this config and is
15961:                             a string of letters
15962:                      Unsupported value (but planned for future support)
15963:                           if a positive integer
15964:                                - The CODE exists as the first n items from
15965:                                  the question section of the form
15966:                           if the string 'number'
15967:                                - The CODE exists for this config and is
15968:                                  a string of numbers
15969:       CODEstart   - (only matter if a CODE exists) column in the line where
15970:                      the CODE starts
15971:       CODElength  - length of the CODE
15972:       IDstart     - column where the student/employee ID starts
15973:       IDlength    - length of the student/employee ID info
15974:       Qstart      - column where the information from the bubbled
15975:                     'questions' start
15976:       Qlength     - number of columns comprising a single bubble line from
15977:                     the sheet. (usually either 1 or 10)
15978:       Qon         - either a single character representing the character used
15979:                     to signal a bubble was chosen in the positional setup, or
15980:                     the string 'letter' if the letter of the chosen bubble is
15981:                     in the final, or 'number' if a number representing the
15982:                     chosen bubble is in the file (1->A 0->J)
15983:       Qoff        - the character used to represent that a bubble was
15984:                     left blank
15985:       PaperID     - if the scanning process generates a unique number for each
15986:                     sheet scanned the column that this ID number starts in
15987:       PaperIDlength - number of columns that comprise the unique ID number
15988:                       for the sheet of paper
15989:       FirstName   - column that the first name starts in
15990:       FirstNameLength - number of columns that the first name spans
15991:       LastName    - column that the last name starts in
15992:       LastNameLength - number of columns that the last name spans
15993:       BubblesPerRow - number of bubbles available in each row used to
15994:                       bubble an answer. (If not specified, 10 assumed).
15995: 
15996: 
15997: =item *
15998: 
15999: get_scantronformat_file($cdom)
16000: 
16001: $cdom - the course's domain (optional); if not supplied, uses
16002: domain for current $env{'request.course.id'}.
16003: 
16004: Returns an array containing lines from the scantron format file for
16005: the domain of the course.
16006: 
16007: If a url for a custom.tab file is listed in domain's configuration.db,
16008: lines are from this file.
16009: 
16010: Otherwise, if a default.tab has been published in RES space by the
16011: domainconfig user, lines are from this file.
16012: 
16013: Otherwise, fall back to getting lines from the legacy file on the
16014: local server:  /home/httpd/lonTabs/default_scantronformat.tab
16015: 
16016: =back
16017: 
16018: =head2 Resource Subroutines
16019: 
16020: =over 4
16021: 
16022: =item *
16023: 
16024: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16025: 
16026: =item *
16027: 
16028: repcopy($filename) : subscribes to the requested file, and attempts to
16029: replicate from the owning library server, Might return
16030: 'unavailable', 'not_found', 'forbidden', 'ok', or
16031: 'bad_request', also attempts to grab the metadata for the
16032: resource. Expects the local filesystem pathname
16033: (/home/httpd/html/res/....)
16034: 
16035: =back
16036: 
16037: =head2 Resource Information
16038: 
16039: =over 4
16040: 
16041: =item *
16042: 
16043: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
16044: and returns the value of a variety of different possible values,
16045: $varname should be a request string, and the other parameters can be
16046: used to specify who and what one is asking about. Ordinarily, $cid 
16047: does not need to be specified, as it is retrived from 
16048: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16049: within lonuserstate::loadmap() when initializing a course, before
16050: $env{'request.course.id'} has been set, so it needs to be provided
16051: in that one case.
16052: 
16053: Possible values for $varname are environment.lastname (or other item
16054: from the envirnment hash), user.name (or someother aspect about the
16055: user), resource.0.maxtries (or some other part and parameter of a
16056: resource)
16057: 
16058: =item *
16059: 
16060: directcondval($number) : get current value of a condition; reads from a state
16061: string
16062: 
16063: =item *
16064: 
16065: condval($condidx) : value of condition index based on state
16066: 
16067: =item *
16068: 
16069: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16070: resource's metadata, $what should be either a specific key, or either
16071: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16072: packages that this resource currently uses, the last 3 arguments are 
16073: only used internally for recursive metadata.
16074: 
16075: the toolsymb is only used where the uri is for an external tool (for which
16076: the uri as well as the symb are guaranteed to be unique).
16077: 
16078: this function automatically caches all requests except any made recursively
16079: to retrieve a list of metadata keys for an imported library file ($liburi is 
16080: defined).
16081: 
16082: =item *
16083: 
16084: metadata_query($query,$custom,$customshow) : make a metadata query against the
16085: network of library servers; returns file handle of where SQL and regex results
16086: will be stored for query
16087: 
16088: =item *
16089: 
16090: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
16091: return symbolic list entry (all arguments optional). 
16092: 
16093: Args: filename is the filename (including path) for the file for which a symb 
16094: is required; donotrecurse, if true will prevent calls to allowed() being made 
16095: to check access status if more than one resource was found in the bighash 
16096: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
16097: a randompick); ignorecachednull, if true will prevent a symb of '' being 
16098: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16099: cause possible symbs to be checked to determine if they are subject to content
16100: blocking, if so they will not be included as possible symbs; possibles is a
16101: ref to a hash, which, as a side effect, will be populated with all possible 
16102: symbs (content blocking not tested).
16103:  
16104: returns the data handle
16105: 
16106: =item *
16107: 
16108: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16109: and is a possible symb for the URL in $thisfn, and if is an encrypted
16110: resource that the user accessed using /enc/ returns a 1 on success, 0
16111: on failure, user must be in a course, as it assumes the existence of
16112: the course initial hash, and uses $env('request.course.id'}.  The third
16113: arg is an optional reference to a scalar.  If this arg is passed in the 
16114: call to symbverify, it will be set to 1 if the symb has been set to be 
16115: encrypted; otherwise it will be null.  
16116: 
16117: =item *
16118: 
16119: symbclean($symb) : removes versions numbers from a symb, returns the
16120: cleaned symb
16121: 
16122: =item *
16123: 
16124: is_on_map($uri) : checks if the $uri is somewhere on the current
16125: course map, user must be in a course for it to work.
16126: 
16127: =item *
16128: 
16129: numval($salt) : return random seed value (addend for rndseed)
16130: 
16131: =item *
16132: 
16133: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16134: a random seed, all arguments are optional, if they aren't sent it uses the
16135: environment to derive them. Note: if symb isn't sent and it can't get one
16136: from &symbread it will use the current time as its return value
16137: 
16138: =item *
16139: 
16140: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16141: unfakeable, receipt
16142: 
16143: =item *
16144: 
16145: receipt() : API to ireceipt working off of env values; given out to users
16146: 
16147: =item *
16148: 
16149: countacc($url) : count the number of accesses to a given URL
16150: 
16151: =item *
16152: 
16153: 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
16154: 
16155: =item *
16156: 
16157: 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)
16158: 
16159: =item *
16160: 
16161: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16162: 
16163: =item *
16164: 
16165: devalidate($symb) : devalidate temporary spreadsheet calculations,
16166: forcing spreadsheet to reevaluate the resource scores next time.
16167: 
16168: =item * 
16169: 
16170: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16171: when viewing in course context.
16172: 
16173:  input: six args -- filename (decluttered), course number, course domain,
16174:                     url, symb (if registered) and group (if this is a 
16175:                     group item -- e.g., bulletin board, group page etc.).
16176: 
16177:  output: array of five scalars --
16178:          $cfile -- url for file editing if editable on current server
16179:          $home -- homeserver of resource (i.e., for author if published,
16180:                                           or course if uploaded.).
16181:          $switchserver --  1 if server switch will be needed.
16182:          $forceedit -- 1 if icon/link should be to go to edit mode 
16183:          $forceview -- 1 if icon/link should be to go to view mode
16184: 
16185: =item *
16186: 
16187: is_course_upload($file,$cnum,$cdom)
16188: 
16189: Used in course context to determine if current file was uploaded to 
16190: the course (i.e., would be found in /userfiles/docs on the course's 
16191: homeserver.
16192: 
16193:   input: 3 args -- filename (decluttered), course number and course domain.
16194:   output: boolean -- 1 if file was uploaded.
16195: 
16196: =back
16197: 
16198: =head2 Storing/Retreiving Data
16199: 
16200: =over 4
16201: 
16202: =item *
16203: 
16204: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16205: permanently for this url; hashref needs to be given and should be a \%hashname;
16206: the remaining args aren't required and if they aren't passed or are '' they will
16207: be derived from the env (with the exception of $laststore, which is an 
16208: optional arg used when a user's submission is stored in grading).
16209: $laststore is $version=$timestamp, where $version is the most recent version
16210: number retrieved for the corresponding $symb in the $namespace db file, and
16211: $timestamp is the timestamp for that transaction (UNIX time).
16212: $laststore is currently only passed when cstore() is called by 
16213: structuretags::finalize_storage().
16214: 
16215: =item *
16216: 
16217: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16218: but uses critical subroutine
16219: 
16220: =item *
16221: 
16222: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16223: all args are optional
16224: 
16225: =item *
16226: 
16227: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
16228: dumps the complete (or key matching regexp) namespace into a hash
16229: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16230: normally &store()ed into
16231: 
16232: $range should be either an integer '100' (give me the first 100
16233:                                            matching records)
16234:               or be  two integers sperated by a - with no spaces
16235:                  '30-50' (give me the 30th through the 50th matching
16236:                           records)
16237: 
16238: 
16239: =item *
16240: 
16241: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16242: replaces a &store() version of data with a replacement set of data
16243: for a particular resource in a namespace passed in the $storehash hash 
16244: reference. If $tolog is true, the transaction is logged in the courselog
16245: with an action=PUTSTORE.
16246: 
16247: =item *
16248: 
16249: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16250: works very similar to store/cstore, but all data is stored in a
16251: temporary location and can be reset using tmpreset, $storehash should
16252: be a hash reference, returns nothing on success
16253: 
16254: =item *
16255: 
16256: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16257: similar to restore, but all data is stored in a temporary location and
16258: can be reset using tmpreset. Returns a hash of values on success,
16259: error string otherwise.
16260: 
16261: =item *
16262: 
16263: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16264: deltes all keys for $symb form the temporary storage hash.
16265: 
16266: =item *
16267: 
16268: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16269: reference filled in from namesp ($udom and $uname are optional)
16270: 
16271: =item *
16272: 
16273: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16274: namesp ($udom and $uname are optional)
16275: 
16276: =item *
16277: 
16278: dump($namespace,$udom,$uname,$regexp,$range) : 
16279: dumps the complete (or key matching regexp) namespace into a hash
16280: ($udom, $uname, $regexp, $range are optional)
16281: 
16282: $range should be either an integer '100' (give me the first 100
16283:                                            matching records)
16284:               or be  two integers sperated by a - with no spaces
16285:                  '30-50' (give me the 30th through the 50th matching
16286:                           records)
16287: =item *
16288: 
16289: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16290: $store can be a scalar, an array reference, or if the amount to be 
16291: incremented is > 1, a hash reference.
16292: 
16293: ($udom and $uname are optional)
16294: 
16295: =item *
16296: 
16297: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16298: ($udom and $uname are optional)
16299: 
16300: =item *
16301: 
16302: cput($namespace,$storehash,$udom,$uname) : critical put
16303: ($udom and $uname are optional)
16304: 
16305: =item *
16306: 
16307: newput($namespace,$storehash,$udom,$uname) :
16308: 
16309: Attempts to store the items in the $storehash, but only if they don't
16310: currently exist, if this succeeds you can be certain that you have 
16311: successfully created a new key value pair in the $namespace db.
16312: 
16313: 
16314: Args:
16315:  $namespace: name of database to store values to
16316:  $storehash: hashref to store to the db
16317:  $udom: (optional) domain of user containing the db
16318:  $uname: (optional) name of user caontaining the db
16319: 
16320: Returns:
16321:  'ok' -> succeeded in storing all keys of $storehash
16322:  'key_exists: <key>' -> failed to anything out of $storehash, as at
16323:                         least <key> already existed in the db (other
16324:                         requested keys may also already exist)
16325:  'error: <msg>' -> unable to tie the DB or other error occurred
16326:  'con_lost' -> unable to contact request server
16327:  'refused' -> action was not allowed by remote machine
16328: 
16329: 
16330: =item *
16331: 
16332: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16333: reference filled in from namesp (encrypts the return communication)
16334: ($udom and $uname are optional)
16335: 
16336: =item *
16337: 
16338: log($udom,$name,$home,$message) : write to permanent log for user; use
16339: critical subroutine
16340: 
16341: =item *
16342: 
16343: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16344: array reference filled in from namespace found in domain level on either
16345: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16346: 
16347: =item *
16348: 
16349: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16350: domain level either on specified domain server ($uhome) or primary domain 
16351: server ($udom and $uhome are optional)
16352: 
16353: =item * 
16354: 
16355: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16356: for: authentication, language, quotas, timezone, date locale, and portal URL in
16357: the target domain.
16358: 
16359: May also include additional key => value pairs for the following groups:
16360: 
16361: =over
16362: 
16363: =item
16364: disk quotas (MB allocated by default to portfolios and authoring spaces).
16365: 
16366: =over
16367: 
16368: =item defaultquota, authorquota
16369: 
16370: =back
16371: 
16372: =item
16373: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16374: portfolio for users).
16375: 
16376: =over
16377: 
16378: =item
16379: aboutme, blog, webdav, portfolio
16380: 
16381: =back
16382: 
16383: =item
16384: requestcourses: ability to request courses, and how requests are processed.
16385: 
16386: =over
16387: 
16388: =item
16389: official, unofficial, community, textbook, placement
16390: 
16391: =back
16392: 
16393: =item
16394: inststatus: types of institutional affiliation, and order in which they are displayed.
16395: 
16396: =over
16397: 
16398: =item
16399: inststatustypes, inststatusorder, inststatusguest
16400: 
16401: =back
16402: 
16403: =item
16404: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16405: for course's uploaded content.
16406: 
16407: =over
16408: 
16409: =item
16410: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16411: communityquota, textbookquota, placementquota
16412: 
16413: =back
16414: 
16415: =item
16416: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16417: on your servers.
16418: 
16419: =over
16420: 
16421: =item 
16422: remotesessions, hostedsessions
16423: 
16424: =back
16425: 
16426: =back
16427: 
16428: In cases where a domain coordinator has never used the "Set Domain Configuration"
16429: utility to create a configuration.db file on a domain's primary library server 
16430: only the following domain defaults: auth_def, auth_arg_def, lang_def
16431: -- corresponding values are authentication type (internal, krb4, krb5,
16432: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16433: will be available. Values are retrieved from cache (if current), unless the
16434: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16435: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16436: 
16437: Typical usage:
16438: 
16439: %domdefaults = &get_domain_defaults($target_domain);
16440: 
16441: =back
16442: 
16443: =head2 Network Status Functions
16444: 
16445: =over 4
16446: 
16447: =item *
16448: 
16449: dirlist() : return directory list based on URI (first arg).
16450: 
16451: Inputs: 1 required, 5 optional.
16452: 
16453: =over
16454: 
16455: =item 
16456: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16457: 
16458: =item
16459: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16460: 
16461: =item
16462: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16463: 
16464: =item
16465: $getpropath - boolean: 1 if prepend path using &propath(). 
16466: 
16467: =item
16468: $getuserdir - boolean: 1 if prepend path for "userfiles".
16469: 
16470: =item 
16471: $alternateRoot - path to prepend in place of path from $uri.
16472: 
16473: =back
16474: 
16475: Returns: Array of up to two items.
16476: 
16477: =over
16478: 
16479: a reference to an array of files/subdirectories
16480: 
16481: =over
16482: 
16483: Each element in the array of files/subdirectories is a & separated list of
16484: item name and the result of running stat on the item.  If dirlist was requested
16485: for a file instead of a directory, the item name will be ''. For a directory 
16486: listing, if the item is a metadata file, the element will end &N&M 
16487: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16488: default copyright set (1).  
16489: 
16490: =back
16491: 
16492: a scalar containing error condition (if encountered).
16493: 
16494: =over
16495: 
16496: =item 
16497: no_host (no homeserver identified for $username:$domain).
16498: 
16499: =item 
16500: no_such_host (server contacted for listing not identified as valid host).
16501: 
16502: =item 
16503: con_lost (connection to remote server failed).
16504: 
16505: =item 
16506: refused (invalid $username:$domain received on lond side).
16507: 
16508: =item 
16509: no_such_dir (directory at specified path on lond side does not exist). 
16510: 
16511: =item 
16512: empty (directory at specified path on lond side is empty).
16513: 
16514: =over
16515: 
16516: This is currently not encountered because the &ls3, &ls2, 
16517: &ls (_handler) routines on the lond side do not filter out
16518: . and .. from a directory listing. 
16519: 
16520: =back
16521: 
16522: =back
16523: 
16524: =back
16525: 
16526: =item *
16527: 
16528: spareserver() : find server with least workload from spare.tab
16529: 
16530: 
16531: =item *
16532: 
16533: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16534: if there is no corresponding loncapa host.
16535: 
16536: =back
16537: 
16538: 
16539: =head2 Apache Request
16540: 
16541: =over 4
16542: 
16543: =item *
16544: 
16545: ssi($url,%hash) : server side include, does a complete request cycle on url to
16546: localhost, posts hash
16547: 
16548: =back
16549: 
16550: =head2 Data to String to Data
16551: 
16552: =over 4
16553: 
16554: =item *
16555: 
16556: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16557: and '&' separators, supports elements that are arrayrefs and hashrefs
16558: 
16559: =item *
16560: 
16561: hashref2str($hashref) : convert a hashref into a string complete with
16562: escaping and '=' and '&' separators, supports elements that are
16563: arrayrefs and hashrefs
16564: 
16565: =item *
16566: 
16567: arrayref2str($arrayref) : convert an arrayref into a string complete
16568: with escaping and '&' separators, supports elements that are arrayrefs
16569: and hashrefs
16570: 
16571: =item *
16572: 
16573: str2hash($string) : convert string to hash using unescaping and
16574: splitting on '=' and '&', supports elements that are arrayrefs and
16575: hashrefs
16576: 
16577: =item *
16578: 
16579: str2array($string) : convert string to hash using unescaping and
16580: splitting on '&', supports elements that are arrayrefs and hashrefs
16581: 
16582: =back
16583: 
16584: =head2 Logging Routines
16585: 
16586: 
16587: These routines allow one to make log messages in the lonnet.log and
16588: lonnet.perm logfiles.
16589: 
16590: =over 4
16591: 
16592: =item *
16593: 
16594: logtouch() : make sure the logfile, lonnet.log, exists
16595: 
16596: =item *
16597: 
16598: logthis() : append message to the normal lonnet.log file, it gets
16599: preiodically rolled over and deleted.
16600: 
16601: =item *
16602: 
16603: logperm() : append a permanent message to lonnet.perm.log, this log
16604: file never gets deleted by any automated portion of the system, only
16605: messages of critical importance should go in here.
16606: 
16607: 
16608: =back
16609: 
16610: =head2 General File Helper Routines
16611: 
16612: =over 4
16613: 
16614: =item *
16615: 
16616: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16617: (a) files in /uploaded
16618:   (i) If a local copy of the file exists - 
16619:       compares modification date of local copy with last-modified date for 
16620:       definitive version stored on home server for course. If local copy is 
16621:       stale, requests a new version from the home server and stores it. 
16622:       If the original has been removed from the home server, then local copy 
16623:       is unlinked.
16624:   (ii) If local copy does not exist -
16625:       requests the file from the home server and stores it. 
16626:   
16627:   If $caller is 'uploadrep':  
16628:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16629:     for request for files originally uploaded via DOCS. 
16630:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16631:   
16632:   Otherwise:
16633:      This indicates a call from the content generation phase of the request.
16634:      -  returns the entire contents of the file or -1.
16635:      
16636: (b) files in /res
16637:    - returns the entire contents of a file or -1; 
16638:    it properly subscribes to and replicates the file if neccessary.
16639: 
16640: 
16641: =item *
16642: 
16643: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16644:                   reference
16645: 
16646: returns either a stat() list of data about the file or an empty list
16647: if the file doesn't exist or couldn't find out about it (connection
16648: problems or user unknown)
16649: 
16650: =item *
16651: 
16652: filelocation($dir,$file) : returns file system location of a file
16653: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16654: directory that relative $file lookups are to looked in ($dir of /a/dir
16655: and a file of ../bob will become /a/bob)
16656: 
16657: =item *
16658: 
16659: hreflocation($dir,$file) : returns file system location or a URL; same as
16660: filelocation except for hrefs
16661: 
16662: =item *
16663: 
16664: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16665: also removes beginning /home/httpd/html unless /priv/ follows it.
16666: 
16667: =back
16668: 
16669: =head2 Usererfile file routines (/uploaded*)
16670: 
16671: =over 4
16672: 
16673: =item *
16674: 
16675: userfileupload(): main rotine for putting a file in a user or course's
16676:                   filespace, arguments are,
16677: 
16678:  formname - required - this is the name of the element in $env where the
16679:            filename, and the contents of the file to create/modifed exist
16680:            the filename is in $env{'form.'.$formname.'.filename'} and the
16681:            contents of the file is located in $env{'form.'.$formname}
16682:  context - if coursedoc, store the file in the course of the active role
16683:              of the current user; 
16684:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16685:            if 'canceloverwrite': delete file in tmp/overwrites directory
16686:  subdir - required - subdirectory to put the file in under ../userfiles/
16687:          if undefined, it will be placed in "unknown"
16688: 
16689:  (This routine calls clean_filename() to remove any dangerous
16690:  characters from the filename, and then calls finuserfileupload() to
16691:  complete the transaction)
16692: 
16693:  returns either the url of the uploaded file (/uploaded/....) if successful
16694:  and /adm/notfound.html if unsuccessful
16695: 
16696: =item *
16697: 
16698: clean_filename(): routine for cleaing a filename up for storage in
16699:                  userfile space, argument is:
16700: 
16701:  filename - proposed filename
16702: 
16703: returns: the new clean filename
16704: 
16705: =item *
16706: 
16707: finishuserfileupload(): routine that creates and sends the file to
16708: userspace, probably shouldn't be called directly
16709: 
16710:   docuname: username or courseid of destination for the file
16711:   docudom: domain of user/course of destination for the file
16712:   formname: same as for userfileupload()
16713:   fname: filename (including subdirectories) for the file
16714:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16715:           if hashref, and context is scantron, will convert csv format to standard format
16716:   allfiles: reference to hash used to store objects found by parser
16717:   codebase: reference to hash used for codebases of java objects found by parser
16718:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16719:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16720:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16721:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16722:   context: if 'overwrite', will move the uploaded file from its temporary location to
16723:             userfiles to facilitate overwriting a previously uploaded file with same name.
16724:   mimetype: reference to scalar to accommodate mime type determined
16725:             from File::MMagic if $parser = parse.
16726: 
16727:  returns either the url of the uploaded file (/uploaded/....) if successful
16728:  and /adm/notfound.html if unsuccessful (or an error message if context 
16729:  was 'overwrite').
16730:  
16731: 
16732: =item *
16733: 
16734: renameuserfile(): renames an existing userfile to a new name
16735: 
16736:   Args:
16737:    docuname: username or courseid of destination for the file
16738:    docudom: domain of user/course of destination for the file
16739:    old: current file name (including any subdirs under userfiles)
16740:    new: desired file name (including any subdirs under userfiles)
16741: 
16742: =item *
16743: 
16744: mkdiruserfile(): creates a directory is a userfiles dir
16745: 
16746:   Args:
16747:    docuname: username or courseid of destination for the file
16748:    docudom: domain of user/course of destination for the file
16749:    dir: dir to create (including any subdirs under userfiles)
16750: 
16751: =item *
16752: 
16753: removeuserfile(): removes a file that exists in userfiles
16754: 
16755:   Args:
16756:    docuname: username or courseid of destination for the file
16757:    docudom: domain of user/course of destination for the file
16758:    fname: filname to delete (including any subdirs under userfiles)
16759: 
16760: =item *
16761: 
16762: removeuploadedurl(): convience function for removeuserfile()
16763: 
16764:   Args:
16765:    url:  a full /uploaded/... url to delete
16766: 
16767: =item * 
16768: 
16769: get_portfile_permissions():
16770:   Args:
16771:     domain: domain of user or course contain the portfolio files
16772:     user: name of user or num of course contain the portfolio files
16773:   Returns:
16774:     hashref of a dump of the proper file_permissions.db
16775:    
16776: 
16777: =item * 
16778: 
16779: get_access_controls():
16780: 
16781: Args:
16782:   current_permissions: the hash ref returned from get_portfile_permissions()
16783:   group: (optional) the group you want the files associated with
16784:   file: (optional) the file you want access info on
16785: 
16786: Returns:
16787:     a hash (keys are file names) of hashes containing
16788:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16789:         values are XML containing access control settings (see below) 
16790: 
16791: Internal notes:
16792: 
16793:  access controls are stored in file_permissions.db as key=value pairs.
16794:     key -> path to file/file_name\0uniqueID:scope_end_start
16795:         where scope -> public,guest,course,group,domains or users.
16796:               end -> UNIX time for end of access (0 -> no end date)
16797:               start -> UNIX time for start of access
16798: 
16799:     value -> XML description of access control
16800:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16801:             <start></start>
16802:             <end></end>
16803: 
16804:             <password></password>  for scope type = guest
16805: 
16806:             <domain></domain>     for scope type = course or group
16807:             <number></number>
16808:             <roles id="">
16809:              <role></role>
16810:              <access></access>
16811:              <section></section>
16812:              <group></group>
16813:             </roles>
16814: 
16815:             <dom></dom>         for scope type = domains
16816: 
16817:             <users>             for scope type = users
16818:              <user>
16819:               <uname></uname>
16820:               <udom></udom>
16821:              </user>
16822:             </users>
16823:            </scope> 
16824:               
16825:  Access data is also aggregated for each file in an additional key=value pair:
16826:  key -> path to file/file_name\0accesscontrol 
16827:  value -> reference to hash
16828:           hash contains key = value pairs
16829:           where key = uniqueID:scope_end_start
16830:                 value = UNIX time record was last updated
16831: 
16832:           Used to improve speed of look-ups of access controls for each file.  
16833:  
16834:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16835: 
16836: =item *
16837: 
16838: modify_access_controls():
16839: 
16840: Modifies access controls for a portfolio file
16841: Args
16842: 1. file name
16843: 2. reference to hash of required changes,
16844: 3. domain
16845: 4. username
16846:   where domain,username are the domain of the portfolio owner 
16847:   (either a user or a course) 
16848: 
16849: Returns:
16850: 1. result of additions or updates ('ok' or 'error', with error message). 
16851: 2. result of deletions ('ok' or 'error', with error message).
16852: 3. reference to hash of any new or updated access controls.
16853: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16854:    key = integer (inbound ID)
16855:    value = uniqueID
16856: 
16857: =item *
16858: 
16859: get_timebased_id():
16860: 
16861: Attempts to get a unique timestamp-based suffix for use with items added to a 
16862: course via the Course Editor (e.g., folders, composite pages, 
16863: group bulletin boards).
16864: 
16865: Args: (first three required; six others optional)
16866: 
16867: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16868:    docssequence, or name of group
16869: 
16870: 2. keyid (alphanumeric): name of temporary locking key in hash,
16871:    e.g., num, boardids
16872: 
16873: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16874:    file will be named nohist_namespace.db
16875: 
16876: 4. cdom: domain of course; default is current course domain from %env
16877: 
16878: 5. cnum: course number; default is current course number from %env
16879: 
16880: 6. idtype: set to concat if an additional digit is to be appended to the 
16881:    unix timestamp to form the suffix, if the plain timestamp is already
16882:    in use.  Default is to not do this, but simply increment the unix 
16883:    timestamp by 1 until a unique key is obtained.
16884: 
16885: 7. who: holder of locking key; defaults to user:domain for user.
16886: 
16887: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16888:    retrying); default is 3.
16889: 
16890: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16891: 
16892: Returns:
16893: 
16894: 1. suffix obtained (numeric)
16895: 
16896: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16897: 
16898: 3. error: contains (localized) error message if an error occurred.
16899: 
16900: 
16901: =back
16902: 
16903: =head2 HTTP Helper Routines
16904: 
16905: =over 4
16906: 
16907: =item *
16908: 
16909: escape() : unpack non-word characters into CGI-compatible hex codes
16910: 
16911: =item *
16912: 
16913: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16914: 
16915: =back
16916: 
16917: =head1 PRIVATE SUBROUTINES
16918: 
16919: =head2 Underlying communication routines (Shouldn't call)
16920: 
16921: =over 4
16922: 
16923: =item *
16924: 
16925: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16926: 
16927: =item *
16928: 
16929: reply() : uses subreply to send a message to remote machine, logs all failures
16930: 
16931: =item *
16932: 
16933: critical() : passes a critical message to another server; if cannot
16934: get through then place message in connection buffer directory and
16935: returns con_delayed, if incapable of saving message, returns
16936: con_failed
16937: 
16938: =item *
16939: 
16940: reconlonc() : tries to reconnect lonc client processes.
16941: 
16942: =back
16943: 
16944: =head2 Resource Access Logging
16945: 
16946: =over 4
16947: 
16948: =item *
16949: 
16950: flushcourselogs() : flush (save) buffer logs and access logs
16951: 
16952: =item *
16953: 
16954: courselog($what) : save message for course in hash
16955: 
16956: =item *
16957: 
16958: courseacclog($what) : save message for course using &courselog().  Perform
16959: special processing for specific resource types (problems, exams, quizzes, etc).
16960: 
16961: =item *
16962: 
16963: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16964: as a PerlChildExitHandler
16965: 
16966: =back
16967: 
16968: =head2 Other
16969: 
16970: =over 4
16971: 
16972: =item *
16973: 
16974: symblist($mapname,%newhash) : update symbolic storage links
16975: 
16976: =back
16977: 
16978: =cut
16979: 

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