File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1433: download - view: text, annotated - select for diffs
Tue Nov 24 16:36:35 2020 UTC (3 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6945

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1433 2020/11/24 16:36:35 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: 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 LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: use LONCAPA::transliterate;
  105: 
  106: use File::Copy;
  107: 
  108: my $readit;
  109: my $max_connection_retries = 20;     # Or some such value.
  110: 
  111: require Exporter;
  112: 
  113: our @ISA = qw (Exporter);
  114: our @EXPORT = qw(%env);
  115: 
  116: 
  117: # ------------------------------------ Logging (parameters, docs, slots, roles)
  118: {
  119:     my $logid;
  120:     sub write_log {
  121: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  122:         if ($context eq 'course') {
  123:             if (($cnum eq '') || ($cdom eq '')) {
  124:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  125:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  126:             }
  127:         }
  128: 	$logid ++;
  129:         my $now = time();
  130: 	my $id=$now.'00000'.$$.'00000'.$logid;
  131:         my $logentry = { 
  132:                           $id => {
  133:                                    'exe_uname' => $env{'user.name'},
  134:                                    'exe_udom'  => $env{'user.domain'},
  135:                                    'exe_time'  => $now,
  136:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  137:                                    'delflag'   => $delflag,
  138:                                    'logentry'  => $storehash,
  139:                                    'uname'     => $uname,
  140:                                    'udom'      => $udom,
  141:                                   }
  142:                        };
  143: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  144:     }
  145: }
  146: 
  147: sub logtouch {
  148:     my $execdir=$perlvar{'lonDaemons'};
  149:     unless (-e "$execdir/logs/lonnet.log") {	
  150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  151: 	close $fh;
  152:     }
  153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  155: }
  156: 
  157: sub logthis {
  158:     my $message=shift;
  159:     my $execdir=$perlvar{'lonDaemons'};
  160:     my $now=time;
  161:     my $local=localtime($now);
  162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  164: 	print $fh $logstring;
  165: 	close($fh);
  166:     }
  167:     return 1;
  168: }
  169: 
  170: sub logperm {
  171:     my $message=shift;
  172:     my $execdir=$perlvar{'lonDaemons'};
  173:     my $now=time;
  174:     my $local=localtime($now);
  175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  176: 	print $fh "$now:$message:$local\n";
  177: 	close($fh);
  178:     }
  179:     return 1;
  180: }
  181: 
  182: sub create_connection {
  183:     my ($hostname,$lonid) = @_;
  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  185: 				     Type    => SOCK_STREAM,
  186: 				     Timeout => 10);
  187:     return 0 if (!$client);
  188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  189:     my $result = <$client>;
  190:     chomp($result);
  191:     return 1 if ($result eq 'done');
  192:     return 0;
  193: }
  194: 
  195: sub get_server_timezone {
  196:     my ($cnum,$cdom) = @_;
  197:     my $home=&homeserver($cnum,$cdom);
  198:     if ($home ne 'no_host') {
  199:         my $cachetime = 24*3600;
  200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  201:         if (defined($cached)) {
  202:             return $timezone;
  203:         } else {
  204:             my $timezone = &reply('servertimezone',$home);
  205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  206:         }
  207:     }
  208: }
  209: 
  210: sub get_server_distarch {
  211:     my ($lonhost,$ignore_cache) = @_;
  212:     if (defined($lonhost)) {
  213:         if (!defined(&hostname($lonhost))) {
  214:             return;
  215:         }
  216:         my $cachetime = 12*3600;
  217:         if (!$ignore_cache) {
  218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  219:             if (defined($cached)) {
  220:                 return $distarch;
  221:             }
  222:         }
  223:         my $rep = &reply('serverdistarch',$lonhost);
  224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  226:                 $rep eq '') {
  227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  228:         }
  229:     }
  230:     return;
  231: }
  232: 
  233: sub get_servercerts_info {
  234:     my ($lonhost,$hostname,$context) = @_;
  235:     return if ($lonhost eq '');
  236:     if ($hostname eq '') {
  237:         $hostname = &hostname($lonhost);
  238:     }
  239:     return if ($hostname eq '');
  240:     my ($rep,$uselocal);
  241:     if ($context eq 'install') {
  242:         $uselocal = 1;
  243:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  244:         $uselocal = 1;
  245:     }
  246:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  247:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  248:         if ($distro eq '') {
  249:             $uselocal = 0;
  250:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  251:             if ($1 < 6) {
  252:                 $uselocal = 0;
  253:             }
  254:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  255:             if ($1 < 12) {
  256:                 $uselocal = 0;
  257:             }
  258:         }
  259:     }
  260:     if ($uselocal) {
  261:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  262:     } else {
  263:         $rep=&reply('servercerts',$lonhost);
  264:     }
  265:     my ($result,%returnhash);
  266:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  267:         ($rep eq 'unknown_cmd')) {
  268:         $result = $rep;
  269:     } else {
  270:         $result = 'ok';
  271:         my @pairs=split(/\&/,$rep);
  272:         foreach my $item (@pairs) {
  273:             my ($key,$value)=split(/=/,$item,2);
  274:             my $what = &unescape($key);
  275:             $returnhash{$what}=&thaw_unescape($value);
  276:         }
  277:     }
  278:     return ($result,\%returnhash);
  279: }
  280: 
  281: sub get_server_loncaparev {
  282:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  283:     if (defined($lonhost)) {
  284:         if (!defined(&hostname($lonhost))) {
  285:             undef($lonhost);
  286:         }
  287:     }
  288:     if (!defined($lonhost)) {
  289:         if (defined(&domain($dom,'primary'))) {
  290:             $lonhost=&domain($dom,'primary');
  291:             if ($lonhost eq 'no_host') {
  292:                 undef($lonhost);
  293:             }
  294:         }
  295:     }
  296:     if (defined($lonhost)) {
  297:         my $cachetime = 12*3600;
  298:         if (!$ignore_cache) {
  299:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  300:             if (defined($cached)) {
  301:                 return $loncaparev;
  302:             }
  303:         }
  304:         my ($answer,$loncaparev);
  305:         my @ids=&current_machine_ids();
  306:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  307:             $answer = $perlvar{'lonVersion'};
  308:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  309:                 $loncaparev = $1;
  310:             }
  311:         } else {
  312:             $answer = &reply('serverloncaparev',$lonhost);
  313:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  314:                 if ($caller eq 'loncron') {
  315:                     my $hostname = &hostname($lonhost);
  316:                     my $protocol = $protocol{$lonhost};
  317:                     $protocol = 'http' if ($protocol ne 'https');
  318:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  319:                     my $request=new HTTP::Request('GET',$url);
  320:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  321:                     unless ($response->is_error()) {
  322:                         my $content = $response->content;
  323:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  324:                             $loncaparev = $1;
  325:                         }
  326:                     }
  327:                 } else {
  328:                     $loncaparev = $loncaparevs{$lonhost};
  329:                 }
  330:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  331:                 $loncaparev = $1;
  332:             }
  333:         }
  334:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  335:     }
  336: }
  337: 
  338: sub get_server_homeID {
  339:     my ($hostname,$ignore_cache,$caller) = @_;
  340:     unless ($ignore_cache) {
  341:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  342:         if (defined($cached)) {
  343:             return $serverhomeID;
  344:         }
  345:     }
  346:     my $cachetime = 12*3600;
  347:     my $serverhomeID;
  348:     if ($caller eq 'loncron') { 
  349:         my @machine_ids = &machine_ids($hostname);
  350:         foreach my $id (@machine_ids) {
  351:             my $response = &reply('serverhomeID',$id);
  352:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  353:                 $serverhomeID = $response;
  354:                 last;
  355:             }
  356:         }
  357:         if ($serverhomeID eq '') {
  358:             $serverhomeID = $machine_ids[-1];
  359:         }
  360:     } else {
  361:         $serverhomeID = $serverhomeIDs{$hostname};
  362:     }
  363:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  364: }
  365: 
  366: sub get_remote_globals {
  367:     my ($lonhost,$whathash,$ignore_cache) = @_;
  368:     my ($result,%returnhash,%whatneeded);
  369:     if (ref($whathash) eq 'HASH') {
  370:         foreach my $what (sort(keys(%{$whathash}))) {
  371:             my $hashid = $lonhost.'-'.$what;
  372:             my ($response,$cached);
  373:             unless ($ignore_cache) {
  374:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  375:             }
  376:             if (defined($cached)) {
  377:                 $returnhash{$what} = $response;
  378:             } else {
  379:                 $whatneeded{$what} = 1;
  380:             }
  381:         }
  382:         if (keys(%whatneeded) == 0) {
  383:             $result = 'ok';
  384:         } else {
  385:             my $requested = &freeze_escape(\%whatneeded);
  386:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  387:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  388:                 ($rep eq 'unknown_cmd')) {
  389:                 $result = $rep;
  390:             } else {
  391:                 $result = 'ok';
  392:                 my @pairs=split(/\&/,$rep);
  393:                 foreach my $item (@pairs) {
  394:                     my ($key,$value)=split(/=/,$item,2);
  395:                     my $what = &unescape($key);
  396:                     my $hashid = $lonhost.'-'.$what;
  397:                     $returnhash{$what}=&thaw_unescape($value);
  398:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  399:                 }
  400:             }
  401:         }
  402:     }
  403:     return ($result,\%returnhash);
  404: }
  405: 
  406: sub remote_devalidate_cache {
  407:     my ($lonhost,$cachekeys) = @_;
  408:     my $items;
  409:     return unless (ref($cachekeys) eq 'ARRAY');
  410:     my $cachestr = join('&',@{$cachekeys});
  411:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  412:     return $response;
  413: }
  414: 
  415: # -------------------------------------------------- Non-critical communication
  416: sub subreply {
  417:     my ($cmd,$server)=@_;
  418:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  419:     #
  420:     #  With loncnew process trimming, there's a timing hole between lonc server
  421:     #  process exit and the master server picking up the listen on the AF_UNIX
  422:     #  socket.  In that time interval, a lock file will exist:
  423: 
  424:     my $lockfile=$peerfile.".lock";
  425:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  426: 	sleep(0.1);
  427:     }
  428:     # At this point, either a loncnew parent is listening or an old lonc
  429:     # or loncnew child is listening so we can connect or everything's dead.
  430:     #
  431:     #   We'll give the connection a few tries before abandoning it.  If
  432:     #   connection is not possible, we'll con_lost back to the client.
  433:     #   
  434:     my $client;
  435:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  436: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  437: 				      Type    => SOCK_STREAM,
  438: 				      Timeout => 10);
  439: 	if ($client) {
  440: 	    last;		# Connected!
  441: 	} else {
  442: 	    &create_connection(&hostname($server),$server);
  443: 	}
  444:         sleep(0.1);	# Try again later if failed connection.
  445:     }
  446:     my $answer;
  447:     if ($client) {
  448: 	print $client "sethost:$server:$cmd\n";
  449: 	$answer=<$client>;
  450: 	if (!$answer) { $answer="con_lost"; }
  451: 	chomp($answer);
  452:     } else {
  453: 	$answer = 'con_lost';	# Failed connection.
  454:     }
  455:     return $answer;
  456: }
  457: 
  458: sub reply {
  459:     my ($cmd,$server)=@_;
  460:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  461:     my $answer=subreply($cmd,$server);
  462:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  463:         my $logged = $cmd;
  464:         if ($cmd =~ /^encrypt:([^:]+):/) {
  465:             my $subcmd = $1;
  466:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  467:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  468:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  469:                 (undef,undef,my @rest) = split(/:/,$cmd);
  470:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  471:                     splice(@rest,2,1,'Hidden');
  472:                 } elsif ($subcmd eq 'passwd') {
  473:                     splice(@rest,2,2,('Hidden','Hidden'));
  474:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  475:                          ($subcmd eq 'autoexportgrades')) {
  476:                     splice(@rest,3,1,'Hidden');
  477:                 }
  478:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  479:             }
  480:         }
  481:         &logthis("<font color=\"blue\">WARNING:".
  482:                  " $logged to $server returned $answer</font>");
  483:     }
  484:     return $answer;
  485: }
  486: 
  487: # ----------------------------------------------------------- Send USR1 to lonc
  488: 
  489: sub reconlonc {
  490:     my ($lonid) = @_;
  491:     if ($lonid) {
  492:         my $hostname = &hostname($lonid);
  493: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  494: 	if ($hostname && -e $peerfile) {
  495: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  496: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  497: 					     Type    => SOCK_STREAM,
  498: 					     Timeout => 10);
  499: 	    if ($client) {
  500: 		print $client ("reset_retries\n");
  501: 		my $answer=<$client>;
  502: 		#reset just this one.
  503: 	    }
  504: 	}
  505: 	return;
  506:     }
  507: 
  508:     &logthis("Trying to reconnect lonc");
  509:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  510:     if (open(my $fh,"<",$loncfile)) {
  511: 	my $loncpid=<$fh>;
  512:         chomp($loncpid);
  513:         if (kill 0 => $loncpid) {
  514: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  515:             kill USR1 => $loncpid;
  516:             sleep 1;
  517:         } else {
  518: 	    &logthis(
  519:                "<font color=\"blue\">WARNING:".
  520:                " lonc at pid $loncpid not responding, giving up</font>");
  521:         }
  522:     } else {
  523: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  524:     }
  525: }
  526: 
  527: # ------------------------------------------------------ Critical communication
  528: 
  529: sub critical {
  530:     my ($cmd,$server)=@_;
  531:     unless (&hostname($server)) {
  532:         &logthis("<font color=\"blue\">WARNING:".
  533:                " Critical message to unknown server ($server)</font>");
  534:         return 'no_such_host';
  535:     }
  536:     my $answer=reply($cmd,$server);
  537:     if ($answer eq 'con_lost') {
  538: 	&reconlonc($server);
  539: 	my $answer=reply($cmd,$server);
  540:         if ($answer eq 'con_lost') {
  541:             my $now=time;
  542:             my $middlename=$cmd;
  543:             $middlename=substr($middlename,0,16);
  544:             $middlename=~s/\W//g;
  545:             my $dfilename=
  546:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  547:             $dumpcount++;
  548:             {
  549: 		my $dfh;
  550: 		if (open($dfh,">",$dfilename)) {
  551: 		    print $dfh "$cmd\n"; 
  552: 		    close($dfh);
  553: 		}
  554:             }
  555:             sleep 1;
  556:             my $wcmd='';
  557:             {
  558: 		my $dfh;
  559: 		if (open($dfh,"<",$dfilename)) {
  560: 		    $wcmd=<$dfh>; 
  561: 		    close($dfh);
  562: 		}
  563:             }
  564:             chomp($wcmd);
  565:             if ($wcmd eq $cmd) {
  566: 		&logthis("<font color=\"blue\">WARNING: ".
  567:                          "Connection buffer $dfilename: $cmd</font>");
  568:                 &logperm("D:$server:$cmd");
  569: 	        return 'con_delayed';
  570:             } else {
  571:                 &logthis("<font color=\"red\">CRITICAL:"
  572:                         ." Critical connection failed: $server $cmd</font>");
  573:                 &logperm("F:$server:$cmd");
  574:                 return 'con_failed';
  575:             }
  576:         }
  577:     }
  578:     return $answer;
  579: }
  580: 
  581: # ------------------------------------------- check if return value is an error
  582: 
  583: sub error {
  584:     my ($result) = @_;
  585:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  586: 	if ($2 == 2) { return undef; }
  587: 	return $1;
  588:     }
  589:     return undef;
  590: }
  591: 
  592: sub convert_and_load_session_env {
  593:     my ($lonidsdir,$handle)=@_;
  594:     my @profile;
  595:     {
  596: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  597: 	if (!$opened) {
  598: 	    return 0;
  599: 	}
  600: 	flock($idf,LOCK_SH);
  601: 	@profile=<$idf>;
  602: 	close($idf);
  603:     }
  604:     my %temp_env;
  605:     foreach my $line (@profile) {
  606: 	if ($line !~ m/=/) {
  607: 	    return 0;
  608: 	}
  609: 	chomp($line);
  610: 	my ($envname,$envvalue)=split(/=/,$line,2);
  611: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  612:     }
  613:     unlink("$lonidsdir/$handle.id");
  614:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  615: 	    0640)) {
  616: 	%disk_env = %temp_env;
  617: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  618: 	untie(%disk_env);
  619:     }
  620:     return 1;
  621: }
  622: 
  623: # ------------------------------------------- Transfer profile into environment
  624: my $env_loaded;
  625: sub transfer_profile_to_env {
  626:     my ($lonidsdir,$handle,$force_transfer) = @_;
  627:     if (!$force_transfer && $env_loaded) { return; } 
  628: 
  629:     if (!defined($lonidsdir)) {
  630: 	$lonidsdir = $perlvar{'lonIDsDir'};
  631:     }
  632:     if (!defined($handle)) {
  633:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  634:     }
  635: 
  636:     my $convert;
  637:     {
  638:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  639: 	if (!$opened) {
  640: 	    return;
  641: 	}
  642: 	flock($idf,LOCK_SH);
  643: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  644: 		&GDBM_READER(),0640)) {
  645: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  646: 	    untie(%disk_env);
  647: 	} else {
  648: 	    $convert = 1;
  649: 	}
  650:     }
  651:     if ($convert) {
  652: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  653: 	    &logthis("Failed to load session, or convert session.");
  654: 	}
  655:     }
  656: 
  657:     my %remove;
  658:     while ( my $envname = each(%env) ) {
  659:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  660:             if ($time < time-300) {
  661:                 $remove{$key}++;
  662:             }
  663:         }
  664:     }
  665: 
  666:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  667:     $env_loaded=1;
  668:     foreach my $expired_key (keys(%remove)) {
  669:         &delenv($expired_key);
  670:     }
  671: }
  672: 
  673: # ---------------------------------------------------- Check for valid session 
  674: sub check_for_valid_session {
  675:     my ($r,$name,$userhashref,$domref) = @_;
  676:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  677:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  678:     if ($name eq 'lonDAV') {
  679:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  680:     } else {
  681:         $lonidsdir=$r->dir_config('lonIDsDir');
  682:         if ($name eq '') {
  683:             $name = 'lonID';
  684:         }
  685:     }
  686:     if ($name eq 'lonID') {
  687:         $secure = 'lonSID';
  688:         $linkname = 'lonLinkID';
  689:         $pubname = 'lonPubID';
  690:         if (exists($cookies{$secure})) {
  691:             $lonid=$cookies{$secure};
  692:         } elsif (exists($cookies{$name})) {
  693:             $lonid=$cookies{$name};
  694:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  695:             $lonid=$cookies{$linkname};
  696:         } elsif (exists($cookies{$pubname})) {
  697:             $lonid=$cookies{$pubname};
  698:         }
  699:     } else {
  700:         $lonid=$cookies{$name};
  701:     }
  702:     return undef if (!$lonid);
  703: 
  704:     my $handle=&LONCAPA::clean_handle($lonid->value);
  705:     if (-l "$lonidsdir/$handle.id") {
  706:         my $link = readlink("$lonidsdir/$handle.id");
  707:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  708:             $handle = $1;
  709:         }
  710:     }
  711:     if (!-e "$lonidsdir/$handle.id") {
  712:         if ((ref($domref)) && ($name eq 'lonID') && 
  713:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  714:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  715:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  716:                 $$domref = $possudom;
  717:             }
  718:         }
  719:         return undef;
  720:     }
  721: 
  722:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  723:     return undef if (!$opened);
  724: 
  725:     flock($idf,LOCK_SH);
  726:     my %disk_env;
  727:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  728: 	    &GDBM_READER(),0640)) {
  729: 	return undef;	
  730:     }
  731: 
  732:     if (!defined($disk_env{'user.name'})
  733: 	|| !defined($disk_env{'user.domain'})) {
  734:         untie(%disk_env);
  735: 	return undef;
  736:     }
  737: 
  738:     if (ref($userhashref) eq 'HASH') {
  739:         $userhashref->{'name'} = $disk_env{'user.name'};
  740:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  741:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  742:         if ($userhashref->{'lti'}) {
  743:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  744:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  745:         }
  746:     }
  747:     untie(%disk_env);
  748: 
  749:     return $handle;
  750: }
  751: 
  752: sub timed_flock {
  753:     my ($file,$lock_type) = @_;
  754:     my $failed=0;
  755:     eval {
  756: 	local $SIG{__DIE__}='DEFAULT';
  757: 	local $SIG{ALRM}=sub {
  758: 	    $failed=1;
  759: 	    die("failed lock");
  760: 	};
  761: 	alarm(13);
  762: 	flock($file,$lock_type);
  763: 	alarm(0);
  764:     };
  765:     if ($failed) {
  766: 	return undef;
  767:     } else {
  768: 	return 1;
  769:     }
  770: }
  771: 
  772: sub get_sessionfile_vars {
  773:     my ($handle,$lonidsdir,$storearr) = @_;
  774:     my %returnhash;
  775:     unless (ref($storearr) eq 'ARRAY') {
  776:         return %returnhash;
  777:     }
  778:     if (-l "$lonidsdir/$handle.id") {
  779:         my $link = readlink("$lonidsdir/$handle.id");
  780:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  781:             $handle = $1;
  782:         }
  783:     }
  784:     if ((-e "$lonidsdir/$handle.id") &&
  785:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  786:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  787:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  788:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  789:                 flock($idf,LOCK_SH);
  790:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  791:                         &GDBM_READER(),0640)) {
  792:                     foreach my $item (@{$storearr}) {
  793:                         $returnhash{$item} = $disk_env{$item};
  794:                     }
  795:                     untie(%disk_env);
  796:                 }
  797:             }
  798:         }
  799:     }
  800:     return %returnhash;
  801: }
  802: 
  803: # ---------------------------------------------------------- Append Environment
  804: 
  805: sub appenv {
  806:     my ($newenv,$roles) = @_;
  807:     if (ref($newenv) eq 'HASH') {
  808:         foreach my $key (keys(%{$newenv})) {
  809:             my $refused = 0;
  810: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  811:                 $refused = 1;
  812:                 if (ref($roles) eq 'ARRAY') {
  813:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  814:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  815:                         $refused = 0;
  816:                     }
  817:                 }
  818:             }
  819:             if ($refused) {
  820:                 &logthis("<font color=\"blue\">WARNING: ".
  821:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  822:                          .'</font>');
  823: 	        delete($newenv->{$key});
  824:             } else {
  825:                 $env{$key}=$newenv->{$key};
  826:             }
  827:         }
  828:         my $lonids = $perlvar{'lonIDsDir'};
  829:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  830:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  831:             if ($opened
  832: 	        && &timed_flock($env_file,LOCK_EX)
  833: 	        &&
  834: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  835: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  836: 	        while (my ($key,$value) = each(%{$newenv})) {
  837: 	            $disk_env{$key} = $value;
  838: 	        }
  839: 	        untie(%disk_env);
  840:             }
  841:         }
  842:     }
  843:     return 'ok';
  844: }
  845: # ----------------------------------------------------- Delete from Environment
  846: 
  847: sub delenv {
  848:     my ($delthis,$regexp,$roles) = @_;
  849:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  850:         my $refused = 1;
  851:         if (ref($roles) eq 'ARRAY') {
  852:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  853:             if (grep(/^\Q$role\E$/,@{$roles})) {
  854:                 $refused = 0;
  855:             }
  856:         }
  857:         if ($refused) {
  858:             &logthis("<font color=\"blue\">WARNING: ".
  859:                      "Attempt to delete from environment ".$delthis);
  860:             return 'error';
  861:         }
  862:     }
  863:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  864:     if ($opened
  865: 	&& &timed_flock($env_file,LOCK_EX)
  866: 	&&
  867: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  868: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  869: 	foreach my $key (keys(%disk_env)) {
  870: 	    if ($regexp) {
  871:                 if ($key=~/^$delthis/) {
  872:                     delete($env{$key});
  873:                     delete($disk_env{$key});
  874:                 } 
  875:             } else {
  876:                 if ($key=~/^\Q$delthis\E/) {
  877: 		    delete($env{$key});
  878: 		    delete($disk_env{$key});
  879: 	        }
  880:             }
  881: 	}
  882: 	untie(%disk_env);
  883:     }
  884:     return 'ok';
  885: }
  886: 
  887: sub get_env_multiple {
  888:     my ($name) = @_;
  889:     my @values;
  890:     if (defined($env{$name})) {
  891:         # exists is it an array
  892:         if (ref($env{$name})) {
  893:             @values=@{ $env{$name} };
  894:         } else {
  895:             $values[0]=$env{$name};
  896:         }
  897:     }
  898:     return(@values);
  899: }
  900: 
  901: # ------------------------------------------------------------------- Locking
  902: 
  903: sub set_lock {
  904:     my ($text)=@_;
  905:     $locknum++;
  906:     my $id=$$.'-'.$locknum;
  907:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  908:              'session.lock.'.$id => $text});
  909:     return $id;
  910: }
  911: 
  912: sub get_locks {
  913:     my $num=0;
  914:     my %texts=();
  915:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  916:        if ($lock=~/\w/) {
  917:           $num++;
  918:           $texts{$lock}=$env{'session.lock.'.$lock};
  919:        }
  920:    }
  921:    return ($num,%texts);
  922: }
  923: 
  924: sub remove_lock {
  925:     my ($id)=@_;
  926:     my $newlocks='';
  927:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  928:        if (($lock=~/\w/) && ($lock ne $id)) {
  929:           $newlocks.=','.$lock;
  930:        }
  931:     }
  932:     &appenv({'session.locks' => $newlocks});
  933:     &delenv('session.lock.'.$id);
  934: }
  935: 
  936: sub remove_all_locks {
  937:     my $activelocks=$env{'session.locks'};
  938:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  939:        if ($lock=~/\w/) {
  940:           &remove_lock($lock);
  941:        }
  942:     }
  943: }
  944: 
  945: 
  946: # ------------------------------------------ Find out current server userload
  947: sub userload {
  948:     my $numusers=0;
  949:     {
  950: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  951: 	my $filename;
  952: 	my $curtime=time;
  953: 	while ($filename=readdir(LONIDS)) {
  954: 	    next if ($filename eq '.' || $filename eq '..');
  955: 	    next if ($filename =~ /publicuser_\d+\.id/);
  956:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  957: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  958: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  959: 	}
  960: 	closedir(LONIDS);
  961:     }
  962:     my $userloadpercent=0;
  963:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  964:     if ($maxuserload) {
  965: 	$userloadpercent=100*$numusers/$maxuserload;
  966:     }
  967:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  968:     return $userloadpercent;
  969: }
  970: 
  971: # ------------------------------ Find server with least workload from spare.tab
  972: 
  973: sub spareserver {
  974:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  975:     my $spare_server;
  976:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  977:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  978:                                                      :  $userloadpercent;
  979:     my ($uint_dom,$remotesessions);
  980:     if (($udom ne '') && (&domain($udom) ne '')) {
  981:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  982:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  983:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  984:         $remotesessions = $udomdefaults{'remotesessions'};
  985:     }
  986:     my $spareshash = &this_host_spares($udom);
  987:     if (ref($spareshash) eq 'HASH') {
  988:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  989:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  990:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  991:                                              $try_server));
  992: 	        ($spare_server, $lowest_load) =
  993: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  994:             }
  995:         }
  996: 
  997:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  998: 
  999:         if (!$found_server) {
 1000:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1001: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1002:                     next unless (&spare_can_host($udom,$uint_dom,
 1003:                                                  $remotesessions,$try_server));
 1004: 	            ($spare_server, $lowest_load) =
 1005: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1006:                 }
 1007: 	    }
 1008:         }
 1009:     }
 1010: 
 1011:     if (!$want_server_name) {
 1012:         if (defined($spare_server)) {
 1013:             my $hostname = &hostname($spare_server);
 1014:             if (defined($hostname)) {
 1015:                 my $protocol = 'http';
 1016:                 if ($protocol{$spare_server} eq 'https') {
 1017:                     $protocol = $protocol{$spare_server};
 1018:                 }
 1019: 	        $spare_server = $protocol.'://'.$hostname;
 1020:             }
 1021:         }
 1022:     }
 1023:     return $spare_server;
 1024: }
 1025: 
 1026: sub compare_server_load {
 1027:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1028: 
 1029:     if ($required) {
 1030:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1031:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1032:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1033:         if (($major eq '' && $minor eq '') ||
 1034:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1035:             return ($spare_server,$lowest_load);
 1036:         }
 1037:     }
 1038: 
 1039:     my $loadans     = &reply('load',    $try_server);
 1040:     my $userloadans = &reply('userload',$try_server);
 1041: 
 1042:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1043: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1044:     }
 1045: 
 1046:     my $load;
 1047:     if ($loadans =~ /\d/) {
 1048: 	if ($userloadans =~ /\d/) {
 1049: 	    #both are numbers, pick the bigger one
 1050: 	    $load = ($loadans > $userloadans) ? $loadans 
 1051: 		                              : $userloadans;
 1052: 	} else {
 1053: 	    $load = $loadans;
 1054: 	}
 1055:     } else {
 1056: 	$load = $userloadans;
 1057:     }
 1058: 
 1059:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1060: 	$spare_server = $try_server;
 1061: 	$lowest_load  = $load;
 1062:     }
 1063:     return ($spare_server,$lowest_load);
 1064: }
 1065: 
 1066: # --------------------------- ask offload servers if user already has a session
 1067: sub find_existing_session {
 1068:     my ($udom,$uname) = @_;
 1069:     my $spareshash = &this_host_spares($udom);
 1070:     if (ref($spareshash) eq 'HASH') {
 1071:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1072:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1073:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1074:             }
 1075:         }
 1076:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1077:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1078:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1079:             }
 1080:         }
 1081:     }
 1082:     return;
 1083: }
 1084: 
 1085: sub delusersession {
 1086:     my ($lonid,$udom,$uname) = @_;
 1087:     my $uprimary_id = &domain($udom,'primary');
 1088:     my $uintdom = &internet_dom($uprimary_id);
 1089:     my $intdom = &internet_dom($lonid);
 1090:     my $serverhomedom = &host_domain($lonid);
 1091:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1092:         return &reply(join(':','delusersession',
 1093:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1094:     }
 1095:     return;
 1096: }
 1097: 
 1098: # check if user's browser sent load balancer cookie and server still has session
 1099: # and is not overloaded.
 1100: sub check_for_balancer_cookie {
 1101:     my ($r,$update_mtime) = @_;
 1102:     my ($otherserver,$cookie);
 1103:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1104:     if (exists($cookies{'balanceID'})) {
 1105:         my $balid = $cookies{'balanceID'};
 1106:         $cookie=&LONCAPA::clean_handle($balid->value);
 1107:         my $balancedir=$r->dir_config('lonBalanceDir');
 1108:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1109:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1110:                 my ($possudom,$possuname) = ($1,$2);
 1111:                 my $has_session = 0;
 1112:                 if ((&domain($possudom) ne '') &&
 1113:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1114:                     my $try_server;
 1115:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1116:                     if ($opened) {
 1117:                         flock($idf,LOCK_SH);
 1118:                         while (my $line = <$idf>) {
 1119:                             chomp($line);
 1120:                             if (&hostname($line) ne '') {
 1121:                                 $try_server = $line;
 1122:                                 last;
 1123:                             }
 1124:                         }
 1125:                         close($idf);
 1126:                         if (($try_server) &&
 1127:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1128:                             my $lowest_load = 30000;
 1129:                             ($otherserver,$lowest_load) =
 1130:                                 &compare_server_load($try_server,undef,$lowest_load);
 1131:                             if ($otherserver ne '' && $lowest_load < 100) {
 1132:                                 $has_session = 1;
 1133:                             } else {
 1134:                                 undef($otherserver);
 1135:                             }
 1136:                         }
 1137:                     }
 1138:                 }
 1139:                 if ($has_session) {
 1140:                     if ($update_mtime) {
 1141:                         my $atime = my $mtime = time;
 1142:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1143:                     }
 1144:                 } else {
 1145:                     unlink("$balancedir/$cookie.id");
 1146:                 }
 1147:             }
 1148:         }
 1149:     }
 1150:     return ($otherserver,$cookie);
 1151: }
 1152: 
 1153: sub updatebalcookie {
 1154:     my ($cookie,$balancer,$lastentry)=@_;
 1155:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1156:         my ($udom,$uname) = ($1,$2);
 1157:         my $uprimary_id = &domain($udom,'primary');
 1158:         my $uintdom = &internet_dom($uprimary_id);
 1159:         my $intdom = &internet_dom($balancer);
 1160:         my $serverhomedom = &host_domain($balancer);
 1161:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1162:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1163:         }
 1164:     }
 1165:     return;
 1166: }
 1167: 
 1168: sub delbalcookie {
 1169:     my ($cookie,$balancer) =@_;
 1170:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1171:         my ($udom,$uname) = ($1,$2);
 1172:         my $uprimary_id = &domain($udom,'primary');
 1173:         my $uintdom = &internet_dom($uprimary_id);
 1174:         my $intdom = &internet_dom($balancer);
 1175:         my $serverhomedom = &host_domain($balancer);
 1176:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1177:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1178:         }
 1179:     }
 1180: }
 1181: 
 1182: # -------------------------------- ask if server already has a session for user
 1183: sub has_user_session {
 1184:     my ($lonid,$udom,$uname) = @_;
 1185:     my $result = &reply(join(':','userhassession',
 1186: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1187:     return 1 if ($result eq 'ok');
 1188: 
 1189:     return 0;
 1190: }
 1191: 
 1192: # --------- determine least loaded server in a user's domain which allows login
 1193: 
 1194: sub choose_server {
 1195:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1196:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1197:     my %servers = &get_servers($udom);
 1198:     my $lowest_load = 30000;
 1199:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1200:     if ($skiploadbal) {
 1201:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1202:         unless (defined($cached)) {
 1203:             my $cachetime = 60*60*24;
 1204:             my %domconfig =
 1205:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1206:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1207:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1208:                                            $cachetime);
 1209:             }
 1210:         }
 1211:     }
 1212:     foreach my $lonhost (keys(%servers)) {
 1213:         if ($skiploadbal) {
 1214:             if (ref($balancers) eq 'HASH') {
 1215:                 next if (exists($balancers->{$lonhost}));
 1216:             }
 1217:         }
 1218:         my $loginvia;
 1219:         if ($checkloginvia) {
 1220:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1221:             if ($loginvia) {
 1222:                 my ($server,$path) = split(/:/,$loginvia);
 1223:                 ($login_host, $lowest_load) =
 1224:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1225:                 if ($login_host eq $server) {
 1226:                     $portal_path = $path;
 1227:                     $isredirect = 1;
 1228:                 }
 1229:             } else {
 1230:                 ($login_host, $lowest_load) =
 1231:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1232:                 if ($login_host eq $lonhost) {
 1233:                     $portal_path = '';
 1234:                     $isredirect = ''; 
 1235:                 }
 1236:             }
 1237:         } else {
 1238:             ($login_host, $lowest_load) =
 1239:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1240:         }
 1241:     }
 1242:     if ($login_host ne '') {
 1243:         $hostname = &hostname($login_host);
 1244:     }
 1245:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1246: }
 1247: 
 1248: sub get_course_sessions {
 1249:     my ($cnum,$cdom,$lastactivity) = @_;
 1250:     my %servers = &internet_dom_servers($cdom);
 1251:     my %returnhash;
 1252:     foreach my $server (sort(keys(%servers))) {
 1253:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1254:         my @pairs=split(/\&/,$rep);
 1255:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1256:             foreach my $item (@pairs) {
 1257:                 my ($key,$value)=split(/=/,$item,2);
 1258:                 $key = &unescape($key);
 1259:                 next if ($key =~ /^error: 2 /);
 1260:                 if (exists($returnhash{$key})) {
 1261:                     next if ($value < $returnhash{$key});
 1262:                 }
 1263:                 $returnhash{$key}=$value;
 1264:             }
 1265:         }
 1266:     }
 1267:     return %returnhash;
 1268: }
 1269: 
 1270: # --------------------------------------------- Try to change a user's password
 1271: 
 1272: sub changepass {
 1273:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1274:     $currentpass = &escape($currentpass);
 1275:     $newpass     = &escape($newpass);
 1276:     my $lonhost = $perlvar{'lonHostID'};
 1277:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1278: 		       $server);
 1279:     if (! $answer) {
 1280: 	&logthis("No reply on password change request to $server ".
 1281: 		 "by $uname in domain $udom.");
 1282:     } elsif ($answer =~ "^ok") {
 1283:         &logthis("$uname in $udom successfully changed their password ".
 1284: 		 "on $server.");
 1285:     } elsif ($answer =~ "^pwchange_failure") {
 1286: 	&logthis("$uname in $udom was unable to change their password ".
 1287: 		 "on $server.  The action was blocked by either lcpasswd ".
 1288: 		 "or pwchange");
 1289:     } elsif ($answer =~ "^non_authorized") {
 1290:         &logthis("$uname in $udom did not get their password correct when ".
 1291: 		 "attempting to change it on $server.");
 1292:     } elsif ($answer =~ "^auth_mode_error") {
 1293:         &logthis("$uname in $udom attempted to change their password despite ".
 1294: 		 "not being locally or internally authenticated on $server.");
 1295:     } elsif ($answer =~ "^unknown_user") {
 1296:         &logthis("$uname in $udom attempted to change their password ".
 1297: 		 "on $server but were unable to because $server is not ".
 1298: 		 "their home server.");
 1299:     } elsif ($answer =~ "^refused") {
 1300: 	&logthis("$server refused to change $uname in $udom password because ".
 1301: 		 "it was sent an unencrypted request to change the password.");
 1302:     } elsif ($answer =~ "invalid_client") {
 1303:         &logthis("$server refused to change $uname in $udom password because ".
 1304:                  "it was a reset by e-mail originating from an invalid server.");
 1305:     } elsif ($answer =~ "^prioruse") {
 1306:        &logthis("$server refused to change $uname in $udom password because ".
 1307:                 "the password had been used before");
 1308:     }
 1309:     return $answer;
 1310: }
 1311: 
 1312: # ----------------------- Try to determine user's current authentication scheme
 1313: 
 1314: sub queryauthenticate {
 1315:     my ($uname,$udom)=@_;
 1316:     my $uhome=&homeserver($uname,$udom);
 1317:     if (!$uhome) {
 1318: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1319: 	return 'no_host';
 1320:     }
 1321:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1322:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1323: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1324:     }
 1325:     return $answer;
 1326: }
 1327: 
 1328: # --------- Try to authenticate user from domain's lib servers (first this one)
 1329: 
 1330: sub authenticate {
 1331:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1332:     $upass=&escape($upass);
 1333:     $uname= &LONCAPA::clean_username($uname);
 1334:     my $uhome=&homeserver($uname,$udom,1);
 1335:     my $newhome;
 1336:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1337: # Maybe the machine was offline and only re-appeared again recently?
 1338:         &reconlonc();
 1339: # One more
 1340: 	$uhome=&homeserver($uname,$udom,1);
 1341:         if (($uhome eq 'no_host') && $checkdefauth) {
 1342:             if (defined(&domain($udom,'primary'))) {
 1343:                 $newhome=&domain($udom,'primary');
 1344:             }
 1345:             if ($newhome ne '') {
 1346:                 $uhome = $newhome;
 1347:             }
 1348:         }
 1349: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1350: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1351: 	    return 'no_host';
 1352:         }
 1353:     }
 1354:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1355:     if ($answer eq 'authorized') {
 1356:         if ($newhome) {
 1357:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1358:             return 'no_account_on_host'; 
 1359:         } else {
 1360:             &logthis("User $uname at $udom authorized by $uhome");
 1361:             return $uhome;
 1362:         }
 1363:     }
 1364:     if ($answer eq 'non_authorized') {
 1365: 	&logthis("User $uname at $udom rejected by $uhome");
 1366: 	return 'no_host'; 
 1367:     }
 1368:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1369:     return 'no_host';
 1370: }
 1371: 
 1372: sub can_host_session {
 1373:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1374:     my $canhost = 1;
 1375:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1376:     if (ref($remotesessions) eq 'HASH') {
 1377:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1378:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1379:                 $canhost = 0;
 1380:             } else {
 1381:                 $canhost = 1;
 1382:             }
 1383:         }
 1384:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1385:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1386:                 $canhost = 1;
 1387:             } else {
 1388:                 $canhost = 0;
 1389:             }
 1390:         }
 1391:         if ($canhost) {
 1392:             if ($remotesessions->{'version'} ne '') {
 1393:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1394:                 if ($reqmajor ne '' && $reqminor ne '') {
 1395:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1396:                         my $major = $1;
 1397:                         my $minor = $2;
 1398:                         if (($major < $reqmajor ) ||
 1399:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1400:                             $canhost = 0;
 1401:                         }
 1402:                     } else {
 1403:                         $canhost = 0;
 1404:                     }
 1405:                 }
 1406:             }
 1407:         }
 1408:     }
 1409:     if ($canhost) {
 1410:         if (ref($hostedsessions) eq 'HASH') {
 1411:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1412:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1413:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1414:                 if (($uint_dom ne '') && 
 1415:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1416:                     $canhost = 0;
 1417:                 } else {
 1418:                     $canhost = 1;
 1419:                 }
 1420:             }
 1421:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1422:                 if (($uint_dom ne '') && 
 1423:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1424:                     $canhost = 1;
 1425:                 } else {
 1426:                     $canhost = 0;
 1427:                 }
 1428:             }
 1429:         }
 1430:     }
 1431:     return $canhost;
 1432: }
 1433: 
 1434: sub spare_can_host {
 1435:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1436:     my $canhost=1;
 1437:     my $try_server_hostname = &hostname($try_server);
 1438:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1439:     my $serverhomedom = &host_domain($serverhomeID);
 1440:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1441:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1442:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1443:             $canhost = 0;
 1444:         }
 1445:     }
 1446:     if (($canhost) && ($uint_dom)) {
 1447:         my @intdoms;
 1448:         my $internet_names = &get_internet_names($try_server);
 1449:         if (ref($internet_names) eq 'ARRAY') {
 1450:             @intdoms = @{$internet_names};
 1451:         }
 1452:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1453:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1454:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1455:                                          $remotesessions,
 1456:                                          $defdomdefaults{'hostedsessions'});
 1457:         }
 1458:     }
 1459:     return $canhost;
 1460: }
 1461: 
 1462: sub this_host_spares {
 1463:     my ($dom) = @_;
 1464:     my ($dom_in_use,$lonhost_in_use,$result);
 1465:     my @hosts = &current_machine_ids();
 1466:     foreach my $lonhost (@hosts) {
 1467:         if (&host_domain($lonhost) eq $dom) {
 1468:             $dom_in_use = $dom;
 1469:             $lonhost_in_use = $lonhost;
 1470:             last;
 1471:         }
 1472:     }
 1473:     if ($dom_in_use ne '') {
 1474:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1475:     }
 1476:     if (ref($result) ne 'HASH') {
 1477:         $lonhost_in_use = $perlvar{'lonHostID'};
 1478:         $dom_in_use = &host_domain($lonhost_in_use);
 1479:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1480:         if (ref($result) ne 'HASH') {
 1481:             $result = \%spareid;
 1482:         }
 1483:     }
 1484:     return $result;
 1485: }
 1486: 
 1487: sub spares_for_offload  {
 1488:     my ($dom_in_use,$lonhost_in_use) = @_;
 1489:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1490:     if (defined($cached)) {
 1491:         return $result;
 1492:     } else {
 1493:         my $cachetime = 60*60*24;
 1494:         my %domconfig =
 1495:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1496:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1497:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1498:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1499:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1500:                 }
 1501:             }
 1502:         }
 1503:     }
 1504:     return;
 1505: }
 1506: 
 1507: sub get_lonbalancer_config {
 1508:     my ($servers) = @_;
 1509:     my ($currbalancer,$currtargets);
 1510:     if (ref($servers) eq 'HASH') {
 1511:         foreach my $server (keys(%{$servers})) {
 1512:             my %what = (
 1513:                          spareid => 1,
 1514:                          perlvar => 1,
 1515:                        );
 1516:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1517:             if ($result eq 'ok') {
 1518:                 if (ref($returnhash) eq 'HASH') {
 1519:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1520:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1521:                             $currbalancer = $server;
 1522:                             $currtargets = {};
 1523:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1524:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1525:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1526:                                 }
 1527:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1528:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1529:                                 }
 1530:                             }
 1531:                             last;
 1532:                         }
 1533:                     }
 1534:                 }
 1535:             }
 1536:         }
 1537:     }
 1538:     return ($currbalancer,$currtargets);
 1539: }
 1540: 
 1541: sub check_loadbalancing {
 1542:     my ($uname,$udom,$caller) = @_;
 1543:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1544:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1545:     my $lonhost = $perlvar{'lonHostID'};
 1546:     my @hosts = &current_machine_ids();
 1547:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1548:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1549:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1550:     my $serverhomedom = &host_domain($lonhost);
 1551:     my $domneedscache;
 1552:     my $cachetime = 60*60*24;
 1553: 
 1554:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1555:         $dom_in_use = $udom;
 1556:         $homeintdom = 1;
 1557:     } else {
 1558:         $dom_in_use = $serverhomedom;
 1559:     }
 1560:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1561:     unless (defined($cached)) {
 1562:         my %domconfig =
 1563:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1564:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1565:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1566:         } else {
 1567:             $domneedscache = $dom_in_use;
 1568:         }
 1569:     }
 1570:     if (ref($result) eq 'HASH') {
 1571:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1572:             &check_balancer_result($result,@hosts);
 1573:         if ($is_balancer) {
 1574:             if (ref($currrules) eq 'HASH') {
 1575:                 if ($homeintdom) {
 1576:                     if ($uname ne '') {
 1577:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1578:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1579:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1580:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1581:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1582:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1583:                             }
 1584:                         }
 1585:                         if ($rule_in_effect eq '') {
 1586:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1587:                             if ($userenv{'inststatus'} ne '') {
 1588:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1589:                                 my ($othertitle,$usertypes,$types) =
 1590:                                     &Apache::loncommon::sorted_inst_types($udom);
 1591:                                 if (ref($types) eq 'ARRAY') {
 1592:                                     foreach my $type (@{$types}) {
 1593:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1594:                                             if (exists($currrules->{$type})) {
 1595:                                                 $rule_in_effect = $currrules->{$type};
 1596:                                             }
 1597:                                         }
 1598:                                     }
 1599:                                 }
 1600:                             } else {
 1601:                                 if (exists($currrules->{'default'})) {
 1602:                                     $rule_in_effect = $currrules->{'default'};
 1603:                                 }
 1604:                             }
 1605:                         }
 1606:                     } else {
 1607:                         if (exists($currrules->{'default'})) {
 1608:                             $rule_in_effect = $currrules->{'default'};
 1609:                         }
 1610:                     }
 1611:                 } else {
 1612:                     if ($currrules->{'_LC_external'} ne '') {
 1613:                         $rule_in_effect = $currrules->{'_LC_external'};
 1614:                     }
 1615:                 }
 1616:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1617:                                                        $uname,$udom);
 1618:             }
 1619:         }
 1620:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1621:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1622:         unless (defined($cached)) {
 1623:             my %domconfig =
 1624:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1625:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1626:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1627:             } else {
 1628:                 $domneedscache = $serverhomedom;
 1629:             }
 1630:         }
 1631:         if (ref($result) eq 'HASH') {
 1632:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1633:                 &check_balancer_result($result,@hosts);
 1634:             if ($is_balancer) {
 1635:                 if (ref($currrules) eq 'HASH') {
 1636:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1637:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1638:                     }
 1639:                 }
 1640:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1641:                                                        $uname,$udom);
 1642:             }
 1643:         } else {
 1644:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1645:                 $is_balancer = 1;
 1646:                 $offloadto = &this_host_spares($dom_in_use);
 1647:             }
 1648:             unless (defined($cached)) {
 1649:                 $domneedscache = $serverhomedom;
 1650:             }
 1651:         }
 1652:     } else {
 1653:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1654:             $is_balancer = 1;
 1655:             $offloadto = &this_host_spares($dom_in_use);
 1656:         }
 1657:         unless (defined($cached)) {
 1658:             $domneedscache = $serverhomedom;
 1659:         }
 1660:     }
 1661:     if ($domneedscache) {
 1662:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1663:     }
 1664:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1665:         my $lowest_load = 30000;
 1666:         if (ref($offloadto) eq 'HASH') {
 1667:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1668:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1669:                     ($otherserver,$lowest_load) =
 1670:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1671:                 }
 1672:             }
 1673:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1674: 
 1675:             if (!$found_server) {
 1676:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1677:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1678:                         ($otherserver,$lowest_load) =
 1679:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1680:                     }
 1681:                 }
 1682:             }
 1683:         } elsif (ref($offloadto) eq 'ARRAY') {
 1684:             if (@{$offloadto} == 1) {
 1685:                 $otherserver = $offloadto->[0];
 1686:             } elsif (@{$offloadto} > 1) {
 1687:                 foreach my $try_server (@{$offloadto}) {
 1688:                     ($otherserver,$lowest_load) =
 1689:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1690:                 }
 1691:             }
 1692:         }
 1693:         unless ($caller eq 'login') {
 1694:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1695:                 $is_balancer = 0;
 1696:                 if ($uname ne '' && $udom ne '') {
 1697:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1698:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1699:                                  'user.loadbalcheck.time' => time});
 1700:                     }
 1701:                 }
 1702:             }
 1703:         }
 1704:     }
 1705:     if (($is_balancer) && (!$homeintdom)) {
 1706:         undef($setcookie);
 1707:     }
 1708:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1709: }
 1710: 
 1711: sub check_balancer_result {
 1712:     my ($result,@hosts) = @_;
 1713:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1714:     if (ref($result) eq 'HASH') {
 1715:         if ($result->{'lonhost'} ne '') {
 1716:             my $currbalancer = $result->{'lonhost'};
 1717:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1718:                 $is_balancer = 1;
 1719:                 $currtargets = $result->{'targets'};
 1720:                 $currrules = $result->{'rules'};
 1721:             }
 1722:             $dom_balancers = $currbalancer;
 1723:         } else {
 1724:             if (keys(%{$result})) {
 1725:                 foreach my $key (keys(%{$result})) {
 1726:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1727:                         (ref($result->{$key}) eq 'HASH')) {
 1728:                         $is_balancer = 1;
 1729:                         $currrules = $result->{$key}{'rules'};
 1730:                         $currtargets = $result->{$key}{'targets'};
 1731:                         $setcookie = $result->{$key}{'cookie'};
 1732:                         last;
 1733:                     }
 1734:                 }
 1735:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1736:             }
 1737:         }
 1738:     }
 1739:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1740: }
 1741: 
 1742: sub get_loadbalancer_targets {
 1743:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1744:     my $offloadto;
 1745:     if ($rule_in_effect eq 'none') {
 1746:         return [$perlvar{'lonHostID'}];
 1747:     } elsif ($rule_in_effect eq '') {
 1748:         $offloadto = $currtargets;
 1749:     } else {
 1750:         if ($rule_in_effect eq 'homeserver') {
 1751:             my $homeserver = &homeserver($uname,$udom);
 1752:             if ($homeserver ne 'no_host') {
 1753:                 $offloadto = [$homeserver];
 1754:             }
 1755:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1756:             my %domconfig =
 1757:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1758:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1759:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1760:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1761:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1762:                     }
 1763:                 }
 1764:             } else {
 1765:                 my %servers = &internet_dom_servers($udom);
 1766:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1767:                 if (&hostname($remotebalancer) ne '') {
 1768:                     $offloadto = [$remotebalancer];
 1769:                 }
 1770:             }
 1771:         } elsif (&hostname($rule_in_effect) ne '') {
 1772:             $offloadto = [$rule_in_effect];
 1773:         }
 1774:     }
 1775:     return $offloadto;
 1776: }
 1777: 
 1778: sub internet_dom_servers {
 1779:     my ($dom) = @_;
 1780:     my (%uniqservers,%servers);
 1781:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1782:     my @machinedoms = &machine_domains($primaryserver);
 1783:     foreach my $mdom (@machinedoms) {
 1784:         my %currservers = %servers;
 1785:         my %server = &get_servers($mdom);
 1786:         %servers = (%currservers,%server);
 1787:     }
 1788:     my %by_hostname;
 1789:     foreach my $id (keys(%servers)) {
 1790:         push(@{$by_hostname{$servers{$id}}},$id);
 1791:     }
 1792:     foreach my $hostname (sort(keys(%by_hostname))) {
 1793:         if (@{$by_hostname{$hostname}} > 1) {
 1794:             my $match = 0;
 1795:             foreach my $id (@{$by_hostname{$hostname}}) {
 1796:                 if (&host_domain($id) eq $dom) {
 1797:                     $uniqservers{$id} = $hostname;
 1798:                     $match = 1;
 1799:                 }
 1800:             }
 1801:             unless ($match) {
 1802:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1803:             }
 1804:         } else {
 1805:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1806:         }
 1807:     }
 1808:     return %uniqservers;
 1809: }
 1810: 
 1811: sub trusted_domains {
 1812:     my ($cmdtype,$calldom) = @_;
 1813:     my ($trusted,$untrusted);
 1814:     if (&domain($calldom) eq '') {
 1815:         return ($trusted,$untrusted);
 1816:     }
 1817:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1818:         return ($trusted,$untrusted);
 1819:     }
 1820:     my $callprimary = &domain($calldom,'primary');
 1821:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1822:     if ($intcalldom eq '') {
 1823:         return ($trusted,$untrusted);
 1824:     }
 1825: 
 1826:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1827:     unless (defined($cached)) {
 1828:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1829:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1830:         $trustconfig = $domconfig{'trust'};
 1831:     }
 1832:     if (ref($trustconfig)) {
 1833:         my (%possexc,%possinc,@allexc,@allinc); 
 1834:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1835:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1836:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1837:             }
 1838:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1839:                 $possinc{$intcalldom} = 1;
 1840:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1841:             }
 1842:         }
 1843:         if (keys(%possexc)) {
 1844:             if (keys(%possinc)) {
 1845:                 foreach my $key (sort(keys(%possexc))) {
 1846:                     next if ($key eq $intcalldom);
 1847:                     unless ($possinc{$key}) {
 1848:                         push(@allexc,$key);
 1849:                     }
 1850:                 }
 1851:             } else {
 1852:                 @allexc = sort(keys(%possexc));
 1853:             }
 1854:         }
 1855:         if (keys(%possinc)) {
 1856:             $possinc{$intcalldom} = 1;
 1857:             @allinc = sort(keys(%possinc));
 1858:         }
 1859:         if ((@allexc > 0) || (@allinc > 0)) {
 1860:             my %doms_by_intdom;
 1861:             my %allintdoms = &all_host_intdom();
 1862:             my %alldoms = &all_host_domain();
 1863:             foreach my $key (%allintdoms) {
 1864:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1865:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1866:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1867:                     }
 1868:                 } else {
 1869:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1870:                 }
 1871:             }
 1872:             foreach my $exc (@allexc) {
 1873:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1874:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1875:                 }
 1876:             }
 1877:             foreach my $inc (@allinc) {
 1878:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1879:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1880:                 }
 1881:             }
 1882:         }
 1883:     }
 1884:     return ($trusted,$untrusted);
 1885: }
 1886: 
 1887: sub will_trust {
 1888:     my ($cmdtype,$domain,$possdom) = @_;
 1889:     return 1 if ($domain eq $possdom);
 1890:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1891:     my $willtrust; 
 1892:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1893:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1894:             $willtrust = 1;
 1895:         }
 1896:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1897:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1898:             $willtrust = 1;
 1899:         }
 1900:     } else {
 1901:         $willtrust = 1;
 1902:     }
 1903:     return $willtrust;
 1904: }
 1905: 
 1906: # ---------------------- Find the homebase for a user from domain's lib servers
 1907: 
 1908: my %homecache;
 1909: sub homeserver {
 1910:     my ($uname,$udom,$ignoreBadCache)=@_;
 1911:     my $index="$uname:$udom";
 1912: 
 1913:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1914: 
 1915:     my %servers = &get_servers($udom,'library');
 1916:     foreach my $tryserver (keys(%servers)) {
 1917:         next if ($ignoreBadCache ne 'true' && 
 1918: 		 exists($badServerCache{$tryserver}));
 1919: 
 1920: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1921: 	if ($answer eq 'found') {
 1922: 	    delete($badServerCache{$tryserver}); 
 1923: 	    return $homecache{$index}=$tryserver;
 1924: 	} elsif ($answer eq 'no_host') {
 1925: 	    $badServerCache{$tryserver}=1;
 1926: 	}
 1927:     }    
 1928:     return 'no_host';
 1929: }
 1930: 
 1931: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1932: 
 1933: sub idget {
 1934:     my ($udom,$idsref,$namespace)=@_;
 1935:     my %returnhash=();
 1936:     my @ids=(); 
 1937:     if (ref($idsref) eq 'ARRAY') {
 1938:         @ids = @{$idsref};
 1939:     } else {
 1940:         return %returnhash; 
 1941:     }
 1942:     if ($namespace eq '') {
 1943:         $namespace = 'ids';
 1944:     }
 1945:     
 1946:     my %servers = &get_servers($udom,'library');
 1947:     foreach my $tryserver (keys(%servers)) {
 1948: 	my $idlist=join('&', map { &escape($_); } @ids);
 1949: 	if ($namespace eq 'ids') {
 1950: 	    $idlist=~tr/A-Z/a-z/;
 1951: 	}
 1952: 	my $reply;
 1953: 	if ($namespace eq 'ids') {
 1954: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1955: 	} else {
 1956: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1957: 	}
 1958: 	my @answer=();
 1959: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1960: 	    @answer=split(/\&/,$reply);
 1961: 	}                    ;
 1962: 	my $i;
 1963: 	for ($i=0;$i<=$#ids;$i++) {
 1964: 	    if ($answer[$i]) {
 1965: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1966: 	    }
 1967: 	}
 1968:     }
 1969:     return %returnhash;
 1970: }
 1971: 
 1972: # ------------------------------------- Find the IDs behind a list of usernames
 1973: 
 1974: sub idrget {
 1975:     my ($udom,@unames)=@_;
 1976:     my %returnhash=();
 1977:     foreach my $uname (@unames) {
 1978:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1979:     }
 1980:     return %returnhash;
 1981: }
 1982: 
 1983: # Store away a list of names and associated student/employee IDs or clicker IDs
 1984: 
 1985: sub idput {
 1986:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1987:     my %servers=();
 1988:     my %ids=();
 1989:     my %byid = ();
 1990:     if (ref($idsref) eq 'HASH') {
 1991:         %ids=%{$idsref};
 1992:     }
 1993:     if ($namespace eq '') {
 1994:         $namespace = 'ids'; 
 1995:     }
 1996:     foreach my $uname (keys(%ids)) {
 1997: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1998:         if ($uhom eq '') {
 1999:             $uhom=&homeserver($uname,$udom);
 2000:         }
 2001:         if ($uhom ne 'no_host') {
 2002:             my $esc_unam=&escape($uname);
 2003:             if ($namespace eq 'ids') {
 2004:                 my $id=&escape($ids{$uname});
 2005:                 $id=~tr/A-Z/a-z/;
 2006:                 my $esc_unam=&escape($uname);
 2007:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2008:             } else {
 2009:                 my @currids = split(/,/,$ids{$uname});
 2010:                 foreach my $id (@currids) {
 2011:                     $byid{$uhom}{$id} .= $uname.',';
 2012:                 }
 2013:             }
 2014:         }
 2015:     }
 2016:     if ($namespace eq 'clickers') {
 2017:         foreach my $server (keys(%byid)) {
 2018:             if (ref($byid{$server}) eq 'HASH') {
 2019:                 foreach my $id (keys(%{$byid{$server}})) {
 2020:                     $byid{$server} =~ s/,$//;
 2021:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2022:                 }
 2023:             }
 2024:         }
 2025:     }
 2026:     foreach my $server (keys(%servers)) {
 2027:         $servers{$server} =~ s/\&$//;
 2028:         if ($namespace eq 'ids') {     
 2029:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2030:         } else {
 2031:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2032:         }
 2033:     }
 2034: }
 2035: 
 2036: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2037: 
 2038: sub iddel {
 2039:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2040:     my %result=();
 2041:     my %ids=();
 2042:     my %byid = ();
 2043:     if (ref($idshashref) eq 'HASH') {
 2044:         %ids=%{$idshashref};
 2045:     } else {
 2046:         return %result;
 2047:     }
 2048:     if ($namespace eq '') {
 2049:         $namespace = 'ids';
 2050:     }
 2051:     my %servers=();
 2052:     while (my ($id,$unamestr) = each(%ids)) {
 2053:         if ($namespace eq 'ids') {
 2054:             my $uhom = $uhome;
 2055:             if ($uhom eq '') { 
 2056:                 $uhom=&homeserver($unamestr,$udom);
 2057:             }
 2058:             if ($uhom ne 'no_host') {
 2059:                 $servers{$uhom}.='&'.&escape($id);
 2060:             }
 2061:          } else {
 2062:             my @curritems = split(/,/,$ids{$id});
 2063:             foreach my $uname (@curritems) {
 2064:                 my $uhom = $uhome;
 2065:                 if ($uhom eq '') {
 2066:                     $uhom=&homeserver($uname,$udom);
 2067:                 }
 2068:                 if ($uhom ne 'no_host') { 
 2069:                     $byid{$uhom}{$id} .= $uname.',';
 2070:                 }
 2071:             }
 2072:         }
 2073:     }
 2074:     if ($namespace eq 'clickers') {
 2075:         foreach my $server (keys(%byid)) {
 2076:             if (ref($byid{$server}) eq 'HASH') {
 2077:                 foreach my $id (keys(%{$byid{$server}})) {
 2078:                     $byid{$server}{$id} =~ s/,$//;
 2079:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2080:                 }
 2081:             }
 2082:         }
 2083:     }
 2084:     foreach my $server (keys(%servers)) {
 2085:         $servers{$server} =~ s/\&$//;
 2086:         if ($namespace eq 'ids') {
 2087:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2088:         } elsif ($namespace eq 'clickers') {
 2089:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2090:         }
 2091:     }
 2092:     return %result;
 2093: }
 2094: 
 2095: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2096: 
 2097: sub updateclickers {
 2098:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2099:     my %clickers;
 2100:     if (ref($idshashref) eq 'HASH') {
 2101:         %clickers=%{$idshashref};
 2102:     } else {
 2103:         return;
 2104:     }
 2105:     my $items='';
 2106:     foreach my $item (keys(%clickers)) {
 2107:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2108:     }
 2109:     $items=~s/\&$//;
 2110:     my $request = "updateclickers:$udom:$action:$items";
 2111:     if ($critical) {
 2112:         return &critical($request,$uhome);
 2113:     } else {
 2114:         return &reply($request,$uhome);
 2115:     }
 2116: }
 2117: 
 2118: # ------------------------------dump from db file owned by domainconfig user
 2119: sub dump_dom {
 2120:     my ($namespace, $udom, $regexp) = @_;
 2121: 
 2122:     $udom ||= $env{'user.domain'};
 2123: 
 2124:     return () unless $udom;
 2125: 
 2126:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2127: }
 2128: 
 2129: # ------------------------------------------ get items from domain db files   
 2130: 
 2131: sub get_dom {
 2132:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2133:     return if ($udom eq 'public');
 2134:     my $items='';
 2135:     foreach my $item (@$storearr) {
 2136:         $items.=&escape($item).'&';
 2137:     }
 2138:     $items=~s/\&$//;
 2139:     if (!$udom) {
 2140:         $udom=$env{'user.domain'};
 2141:         return if ($udom eq 'public');
 2142:         if (defined(&domain($udom,'primary'))) {
 2143:             $uhome=&domain($udom,'primary');
 2144:         } else {
 2145:             undef($uhome);
 2146:         }
 2147:     } else {
 2148:         if (!$uhome) {
 2149:             if (defined(&domain($udom,'primary'))) {
 2150:                 $uhome=&domain($udom,'primary');
 2151:             }
 2152:         }
 2153:     }
 2154:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2155:         my $rep;
 2156:         if ($namespace =~ /^enc/) {
 2157:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2158:         } else {
 2159:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2160:         }
 2161:         my %returnhash;
 2162:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2163:             return %returnhash;
 2164:         }
 2165:         my @pairs=split(/\&/,$rep);
 2166:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2167:             return @pairs;
 2168:         }
 2169:         my $i=0;
 2170:         foreach my $item (@$storearr) {
 2171:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2172:             $i++;
 2173:         }
 2174:         return %returnhash;
 2175:     } else {
 2176:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2177:     }
 2178: }
 2179: 
 2180: # -------------------------------------------- put items in domain db files 
 2181: 
 2182: sub put_dom {
 2183:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2184:     if (!$udom) {
 2185:         $udom=$env{'user.domain'};
 2186:         if (defined(&domain($udom,'primary'))) {
 2187:             $uhome=&domain($udom,'primary');
 2188:         } else {
 2189:             undef($uhome);
 2190:         }
 2191:     } else {
 2192:         if (!$uhome) {
 2193:             if (defined(&domain($udom,'primary'))) {
 2194:                 $uhome=&domain($udom,'primary');
 2195:             }
 2196:         }
 2197:     } 
 2198:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2199:         my $items='';
 2200:         foreach my $item (keys(%$storehash)) {
 2201:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2202:         }
 2203:         $items=~s/\&$//;
 2204:         if ($namespace =~ /^enc/) {
 2205:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2206:         } else {
 2207:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2208:         }
 2209:     } else {
 2210:         &logthis("put_dom failed - no homeserver and/or domain");
 2211:     }
 2212: }
 2213: 
 2214: # --------------------- newput for items in db file owned by domainconfig user
 2215: sub newput_dom {
 2216:     my ($namespace,$storehash,$udom) = @_;
 2217:     my $result;
 2218:     if (!$udom) {
 2219:         $udom=$env{'user.domain'};
 2220:     }
 2221:     if ($udom) {
 2222:         my $uname = &get_domainconfiguser($udom);
 2223:         $result = &newput($namespace,$storehash,$udom,$uname);
 2224:     }
 2225:     return $result;
 2226: }
 2227: 
 2228: # --------------------- delete for items in db file owned by domainconfig user
 2229: sub del_dom {
 2230:     my ($namespace,$storearr,$udom)=@_;
 2231:     if (ref($storearr) eq 'ARRAY') {
 2232:         if (!$udom) {
 2233:             $udom=$env{'user.domain'};
 2234:         }
 2235:         if ($udom) {
 2236:             my $uname = &get_domainconfiguser($udom); 
 2237:             return &del($namespace,$storearr,$udom,$uname);
 2238:         }
 2239:     }
 2240: }
 2241: 
 2242: # ----------------------------------construct domainconfig user for a domain 
 2243: sub get_domainconfiguser {
 2244:     my ($udom) = @_;
 2245:     return $udom.'-domainconfig';
 2246: }
 2247: 
 2248: sub retrieve_inst_usertypes {
 2249:     my ($udom) = @_;
 2250:     my (%returnhash,@order);
 2251:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2252:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2253:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2254:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2255:     } else {
 2256:         if (defined(&domain($udom,'primary'))) {
 2257:             my $uhome=&domain($udom,'primary');
 2258:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2259:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2260:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2261:                 return (\%returnhash,\@order);
 2262:             }
 2263:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2264:             my @pairs=split(/\&/,$hashitems);
 2265:             foreach my $item (@pairs) {
 2266:                 my ($key,$value)=split(/=/,$item,2);
 2267:                 $key = &unescape($key);
 2268:                 next if ($key =~ /^error: 2 /);
 2269:                 $returnhash{$key}=&thaw_unescape($value);
 2270:             }
 2271:             my @esc_order = split(/\&/,$orderitems);
 2272:             foreach my $item (@esc_order) {
 2273:                 push(@order,&unescape($item));
 2274:             }
 2275:         } else {
 2276:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2277:         }
 2278:         return (\%returnhash,\@order);
 2279:     }
 2280: }
 2281: 
 2282: sub is_domainimage {
 2283:     my ($url) = @_;
 2284:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2285:         if (&domain($1) ne '') {
 2286:             return '1';
 2287:         }
 2288:     }
 2289:     return;
 2290: }
 2291: 
 2292: sub inst_directory_query {
 2293:     my ($srch) = @_;
 2294:     my $udom = $srch->{'srchdomain'};
 2295:     my %results;
 2296:     my $homeserver = &domain($udom,'primary');
 2297:     my $outcome;
 2298:     if ($homeserver ne '') {
 2299:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2300:             if ($srch->{'srchby'} eq 'email') {
 2301:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2302:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2303:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2304:                     (($major == 2) && ($minor < 12))) {
 2305:                     return;
 2306:                 }
 2307:             }
 2308:         }
 2309: 	my $queryid=&reply("querysend:instdirsearch:".
 2310: 			   &escape($srch->{'srchby'}).':'.
 2311: 			   &escape($srch->{'srchterm'}).':'.
 2312: 			   &escape($srch->{'srchtype'}),$homeserver);
 2313: 	my $host=&hostname($homeserver);
 2314: 	if ($queryid !~/^\Q$host\E\_/) {
 2315: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2316: 	    return;
 2317: 	}
 2318: 	my $response = &get_query_reply($queryid);
 2319: 	my $maxtries = 5;
 2320: 	my $tries = 1;
 2321: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2322: 	    $response = &get_query_reply($queryid);
 2323: 	    $tries ++;
 2324: 	}
 2325: 
 2326:         if (!&error($response) && $response ne 'refused') {
 2327:             if ($response eq 'unavailable') {
 2328:                 $outcome = $response;
 2329:             } else {
 2330:                 $outcome = 'ok';
 2331:                 my @matches = split(/\n/,$response);
 2332:                 foreach my $match (@matches) {
 2333:                     my ($key,$value) = split(/=/,$match);
 2334:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2335:                 }
 2336:             }
 2337:         }
 2338:     }
 2339:     return ($outcome,%results);
 2340: }
 2341: 
 2342: sub usersearch {
 2343:     my ($srch) = @_;
 2344:     my $dom = $srch->{'srchdomain'};
 2345:     my %results;
 2346:     my %libserv = &all_library();
 2347:     my $query = 'usersearch';
 2348:     foreach my $tryserver (keys(%libserv)) {
 2349:         if (&host_domain($tryserver) eq $dom) {
 2350:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2351:                 if ($srch->{'srchby'} eq 'email') {
 2352:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2353:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2354:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2355:                              (($major == 2) && ($minor < 12)));
 2356:                 }
 2357:             }
 2358:             my $host=&hostname($tryserver);
 2359:             my $queryid=
 2360:                 &reply("querysend:".&escape($query).':'.
 2361:                        &escape($srch->{'srchby'}).':'.
 2362:                        &escape($srch->{'srchtype'}).':'.
 2363:                        &escape($srch->{'srchterm'}),$tryserver);
 2364:             if ($queryid !~/^\Q$host\E\_/) {
 2365:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2366:                 next;
 2367:             }
 2368:             my $reply = &get_query_reply($queryid);
 2369:             my $maxtries = 1;
 2370:             my $tries = 1;
 2371:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2372:                 $reply = &get_query_reply($queryid);
 2373:                 $tries ++;
 2374:             }
 2375:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2376:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2377:             } else {
 2378:                 my @matches;
 2379:                 if ($reply =~ /\n/) {
 2380:                     @matches = split(/\n/,$reply);
 2381:                 } else {
 2382:                     @matches = split(/\&/,$reply);
 2383:                 }
 2384:                 foreach my $match (@matches) {
 2385:                     my ($uname,$udom,%userhash);
 2386:                     foreach my $entry (split(/:/,$match)) {
 2387:                         my ($key,$value) =
 2388:                             map {&unescape($_);} split(/=/,$entry);
 2389:                         $userhash{$key} = $value;
 2390:                         if ($key eq 'username') {
 2391:                             $uname = $value;
 2392:                         } elsif ($key eq 'domain') {
 2393:                             $udom = $value;
 2394:                         }
 2395:                     }
 2396:                     $results{$uname.':'.$udom} = \%userhash;
 2397:                 }
 2398:             }
 2399:         }
 2400:     }
 2401:     return %results;
 2402: }
 2403: 
 2404: sub get_instuser {
 2405:     my ($udom,$uname,$id) = @_;
 2406:     my $homeserver = &domain($udom,'primary');
 2407:     my ($outcome,%results);
 2408:     if ($homeserver ne '') {
 2409:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2410:                            &escape($id).':'.&escape($udom),$homeserver);
 2411:         my $host=&hostname($homeserver);
 2412:         if ($queryid !~/^\Q$host\E\_/) {
 2413:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2414:             return;
 2415:         }
 2416:         my $response = &get_query_reply($queryid);
 2417:         my $maxtries = 5;
 2418:         my $tries = 1;
 2419:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2420:             $response = &get_query_reply($queryid);
 2421:             $tries ++;
 2422:         }
 2423:         if (!&error($response) && $response ne 'refused') {
 2424:             if ($response eq 'unavailable') {
 2425:                 $outcome = $response;
 2426:             } else {
 2427:                 $outcome = 'ok';
 2428:                 my @matches = split(/\n/,$response);
 2429:                 foreach my $match (@matches) {
 2430:                     my ($key,$value) = split(/=/,$match);
 2431:                     $results{&unescape($key)} = &thaw_unescape($value);
 2432:                 }
 2433:             }
 2434:         }
 2435:     }
 2436:     my %userinfo;
 2437:     if (ref($results{$uname}) eq 'HASH') {
 2438:         %userinfo = %{$results{$uname}};
 2439:     } 
 2440:     return ($outcome,%userinfo);
 2441: }
 2442: 
 2443: sub get_multiple_instusers {
 2444:     my ($udom,$users,$caller) = @_;
 2445:     my ($outcome,$results);
 2446:     if (ref($users) eq 'HASH') {
 2447:         my $count = keys(%{$users}); 
 2448:         my $requested = &freeze_escape($users);
 2449:         my $homeserver = &domain($udom,'primary');
 2450:         if ($homeserver ne '') {
 2451:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2452:             my $host=&hostname($homeserver);
 2453:             if ($queryid !~/^\Q$host\E\_/) {
 2454:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2455:                          ' for host: '.$homeserver.'in domain '.$udom);
 2456:                 return ($outcome,$results);
 2457:             }
 2458:             my $response = &get_query_reply($queryid);
 2459:             my $maxtries = 5;
 2460:             if ($count > 100) {
 2461:                 $maxtries = 1+int($count/20);
 2462:             }
 2463:             my $tries = 1;
 2464:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2465:                 $response = &get_query_reply($queryid);
 2466:                 $tries ++;
 2467:             }
 2468:             if ($response eq '') {
 2469:                 $results = {};
 2470:                 foreach my $key (keys(%{$users})) {
 2471:                     my ($uname,$id);
 2472:                     if ($caller eq 'id') {
 2473:                         $id = $key;
 2474:                     } else {
 2475:                         $uname = $key;
 2476:                     }
 2477:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2478:                     $outcome = $resp;
 2479:                     if ($resp eq 'ok') {
 2480:                         %{$results} = (%{$results}, %info);
 2481:                     } else {
 2482:                         last;
 2483:                     }
 2484:                 }
 2485:             } elsif(!&error($response) && ($response ne 'refused')) {
 2486:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2487:                     $outcome = $response;
 2488:                 } else {
 2489:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2490:                     if ($outcome eq 'ok') {
 2491:                         $results = &thaw_unescape($userdata); 
 2492:                     }
 2493:                 }
 2494:             }
 2495:         }
 2496:     }
 2497:     return ($outcome,$results);
 2498: }
 2499: 
 2500: sub inst_rulecheck {
 2501:     my ($udom,$uname,$id,$item,$rules) = @_;
 2502:     my %returnhash;
 2503:     if ($udom ne '') {
 2504:         if (ref($rules) eq 'ARRAY') {
 2505:             @{$rules} = map {&escape($_);} (@{$rules});
 2506:             my $rulestr = join(':',@{$rules});
 2507:             my $homeserver=&domain($udom,'primary');
 2508:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2509:                 my $response;
 2510:                 if ($item eq 'username') {                
 2511:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2512:                                               ':'.&escape($uname).':'.$rulestr,
 2513:                                               $homeserver));
 2514:                 } elsif ($item eq 'id') {
 2515:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2516:                                               ':'.&escape($id).':'.$rulestr,
 2517:                                               $homeserver));
 2518:                 } elsif ($item eq 'selfcreate') {
 2519:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2520:                                                &escape($udom).':'.&escape($uname).
 2521:                                               ':'.$rulestr,$homeserver));
 2522:                 }
 2523:                 if ($response ne 'refused') {
 2524:                     my @pairs=split(/\&/,$response);
 2525:                     foreach my $item (@pairs) {
 2526:                         my ($key,$value)=split(/=/,$item,2);
 2527:                         $key = &unescape($key);
 2528:                         next if ($key =~ /^error: 2 /);
 2529:                         $returnhash{$key}=&thaw_unescape($value);
 2530:                     }
 2531:                 }
 2532:             }
 2533:         }
 2534:     }
 2535:     return %returnhash;
 2536: }
 2537: 
 2538: sub inst_userrules {
 2539:     my ($udom,$check) = @_;
 2540:     my (%ruleshash,@ruleorder);
 2541:     if ($udom ne '') {
 2542:         my $homeserver=&domain($udom,'primary');
 2543:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2544:             my $response;
 2545:             if ($check eq 'id') {
 2546:                 $response=&reply('instidrules:'.&escape($udom),
 2547:                                  $homeserver);
 2548:             } elsif ($check eq 'email') {
 2549:                 $response=&reply('instemailrules:'.&escape($udom),
 2550:                                  $homeserver);
 2551:             } else {
 2552:                 $response=&reply('instuserrules:'.&escape($udom),
 2553:                                  $homeserver);
 2554:             }
 2555:             if (($response ne 'refused') && ($response ne 'error') && 
 2556:                 ($response ne 'unknown_cmd') && 
 2557:                 ($response ne 'no_such_host')) {
 2558:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2559:                 my @pairs=split(/\&/,$hashitems);
 2560:                 foreach my $item (@pairs) {
 2561:                     my ($key,$value)=split(/=/,$item,2);
 2562:                     $key = &unescape($key);
 2563:                     next if ($key =~ /^error: 2 /);
 2564:                     $ruleshash{$key}=&thaw_unescape($value);
 2565:                 }
 2566:                 my @esc_order = split(/\&/,$orderitems);
 2567:                 foreach my $item (@esc_order) {
 2568:                     push(@ruleorder,&unescape($item));
 2569:                 }
 2570:             }
 2571:         }
 2572:     }
 2573:     return (\%ruleshash,\@ruleorder);
 2574: }
 2575: 
 2576: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2577: 
 2578: sub get_domain_defaults {
 2579:     my ($domain,$ignore_cache) = @_;
 2580:     return if (($domain eq '') || ($domain eq 'public'));
 2581:     my $cachetime = 60*60*24;
 2582:     unless ($ignore_cache) {
 2583:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2584:         if (defined($cached)) {
 2585:             if (ref($result) eq 'HASH') {
 2586:                 return %{$result};
 2587:             }
 2588:         }
 2589:     }
 2590:     my %domdefaults;
 2591:     my %domconfig =
 2592:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2593:                                   'requestcourses','inststatus',
 2594:                                   'coursedefaults','usersessions',
 2595:                                   'requestauthor','selfenrollment',
 2596:                                   'coursecategories','ssl','autoenroll',
 2597:                                   'trust','helpsettings'],$domain);
 2598:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2599:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2600:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2601:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2602:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2603:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2604:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2605:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2606:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2607:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2608:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2609:     } else {
 2610:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2611:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2612:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2613:     }
 2614:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2615:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2616:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2617:         } else {
 2618:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2619:         }
 2620:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2621:         foreach my $item (@usertools) {
 2622:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2623:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2624:             }
 2625:         }
 2626:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2627:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2628:         }
 2629:     }
 2630:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2631:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2632:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2633:         }
 2634:     }
 2635:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2636:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2637:     }
 2638:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2639:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2640:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2641:         }
 2642:     }
 2643:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2644:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2645:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2646:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2647:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2648:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2649:         }
 2650:         foreach my $type (@coursetypes) {
 2651:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2652:                 unless ($type eq 'community') {
 2653:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2654:                 }
 2655:             }
 2656:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2657:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2658:             }
 2659:             if ($domdefaults{'postsubmit'} eq 'on') {
 2660:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2661:                     $domdefaults{$type.'postsubtimeout'} = 
 2662:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2663:                 }
 2664:             }
 2665:         }
 2666:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2667:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2668:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2669:                 if (@clonecodes) {
 2670:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2671:                 }
 2672:             }
 2673:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2674:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2675:         }
 2676:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2677:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2678:         } 
 2679:     }
 2680:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2681:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2682:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2683:         }
 2684:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2685:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2686:         }
 2687:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2688:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2689:         }
 2690:     }
 2691:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2692:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2693:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2694:                             'approval','limit');
 2695:             foreach my $type (@coursetypes) {
 2696:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2697:                     my @mgrdc = ();
 2698:                     foreach my $item (@settings) {
 2699:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2700:                             push(@mgrdc,$item);
 2701:                         }
 2702:                     }
 2703:                     if (@mgrdc) {
 2704:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2705:                     }
 2706:                 }
 2707:             }
 2708:         }
 2709:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2710:             foreach my $type (@coursetypes) {
 2711:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2712:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2713:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2714:                     }
 2715:                 }
 2716:             }
 2717:         }
 2718:     }
 2719:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2720:         $domdefaults{'catauth'} = 'std';
 2721:         $domdefaults{'catunauth'} = 'std';
 2722:         if ($domconfig{'coursecategories'}{'auth'}) {
 2723:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2724:         }
 2725:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2726:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2727:         }
 2728:     }
 2729:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2730:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2731:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2732:         }
 2733:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2734:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2735:         }
 2736:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2737:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2738:         }
 2739:     }
 2740:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2741:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2742:         foreach my $prefix (@prefixes) {
 2743:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2744:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2745:             }
 2746:         }
 2747:     }
 2748:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2749:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2750:     }
 2751:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2752:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2753:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2754:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2755:         }
 2756:     }
 2757:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2758:     return %domdefaults;
 2759: }
 2760: 
 2761: sub get_dom_cats {
 2762:     my ($dom) = @_;
 2763:     return unless (&domain($dom));
 2764:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2765:     unless (defined($cached)) {
 2766:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2767:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2768:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2769:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2770:             } else {
 2771:                 $cats = {};
 2772:             }
 2773:         } else {
 2774:             $cats = {};
 2775:         }
 2776:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2777:     }
 2778:     return $cats;
 2779: }
 2780: 
 2781: sub get_dom_instcats {
 2782:     my ($dom) = @_;
 2783:     return unless (&domain($dom));
 2784:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2785:     unless (defined($cached)) {
 2786:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2787:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2788:         if ($totcodes > 0) {
 2789:             my $caller = 'global';
 2790:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2791:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2792:                 $instcats = {
 2793:                                 codes => \%codes,
 2794:                                 codetitles => \@codetitles,
 2795:                                 cat_titles => \%cat_titles,
 2796:                                 cat_order => \%cat_order,
 2797:                             };
 2798:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2799:             }
 2800:         }
 2801:     }
 2802:     return $instcats;
 2803: }
 2804: 
 2805: sub retrieve_instcodes {
 2806:     my ($coursecodes,$dom) = @_;
 2807:     my $totcodes;
 2808:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2809:     foreach my $course (keys(%courses)) {
 2810:         if (ref($courses{$course}) eq 'HASH') {
 2811:             if ($courses{$course}{'inst_code'} ne '') {
 2812:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2813:                 $totcodes ++;
 2814:             }
 2815:         }
 2816:     }
 2817:     return $totcodes;
 2818: }
 2819: 
 2820: sub course_portal_url {
 2821:     my ($cnum,$cdom) = @_;
 2822:     my $chome = &homeserver($cnum,$cdom);
 2823:     my $hostname = &hostname($chome);
 2824:     my $protocol = $protocol{$chome};
 2825:     $protocol = 'http' if ($protocol ne 'https');
 2826:     my %domdefaults = &get_domain_defaults($cdom);
 2827:     my $firsturl;
 2828:     if ($domdefaults{'portal_def'}) {
 2829:         $firsturl = $domdefaults{'portal_def'};
 2830:     } else {
 2831:         $firsturl = $protocol.'://'.$hostname;
 2832:     }
 2833:     return $firsturl;
 2834: }
 2835: 
 2836: # --------------------------------------------- Get domain config for passwords
 2837: 
 2838: sub get_passwdconf {
 2839:     my ($dom) = @_;
 2840:     my (%passwdconf,$gotconf,$lookup);
 2841:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2842:     if (defined($cached)) {
 2843:         if (ref($result) eq 'HASH') {
 2844:             %passwdconf = %{$result};
 2845:             $gotconf = 1;
 2846:         }
 2847:     }
 2848:     unless ($gotconf) {
 2849:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2850:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2851:             %passwdconf = %{$domconfig{'passwords'}};
 2852:         }
 2853:         my $cachetime = 24*60*60;
 2854:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2855:     }
 2856:     return %passwdconf;
 2857: }
 2858: 
 2859: # --------------------------------------------------- Assign a key to a student
 2860: 
 2861: sub assign_access_key {
 2862: #
 2863: # a valid key looks like uname:udom#comments
 2864: # comments are being appended
 2865: #
 2866:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2867:     $kdom=
 2868:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2869:     $knum=
 2870:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2871:     $cdom=
 2872:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2873:     $cnum=
 2874:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2875:     $udom=$env{'user.name'} unless (defined($udom));
 2876:     $uname=$env{'user.domain'} unless (defined($uname));
 2877:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2878:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2879:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2880:                                                   # assigned to this person
 2881:                                                   # - this should not happen,
 2882:                                                   # unless something went wrong
 2883:                                                   # the first time around
 2884: # ready to assign
 2885:         $logentry=$1.'; '.$logentry;
 2886:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2887:                                                  $kdom,$knum) eq 'ok') {
 2888: # key now belongs to user
 2889: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2890:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2891:                 &appenv({'environment.'.$envkey => $ckey});
 2892:                 return 'ok';
 2893:             } else {
 2894:                 return 
 2895:   'error: Count not permanently assign key, will need to be re-entered later.';
 2896: 	    }
 2897:         } else {
 2898:             return 'error: Could not assign key, try again later.';
 2899:         }
 2900:     } elsif (!$existing{$ckey}) {
 2901: # the key does not exist
 2902: 	return 'error: The key does not exist';
 2903:     } else {
 2904: # the key is somebody else's
 2905: 	return 'error: The key is already in use';
 2906:     }
 2907: }
 2908: 
 2909: # ------------------------------------------ put an additional comment on a key
 2910: 
 2911: sub comment_access_key {
 2912: #
 2913: # a valid key looks like uname:udom#comments
 2914: # comments are being appended
 2915: #
 2916:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2917:     $cdom=
 2918:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2919:     $cnum=
 2920:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2921:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2922:     if ($existing{$ckey}) {
 2923:         $existing{$ckey}.='; '.$logentry;
 2924: # ready to assign
 2925:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2926:                                                  $cdom,$cnum) eq 'ok') {
 2927: 	    return 'ok';
 2928:         } else {
 2929: 	    return 'error: Count not store comment.';
 2930:         }
 2931:     } else {
 2932: # the key does not exist
 2933: 	return 'error: The key does not exist';
 2934:     }
 2935: }
 2936: 
 2937: # ------------------------------------------------------ Generate a set of keys
 2938: 
 2939: sub generate_access_keys {
 2940:     my ($number,$cdom,$cnum,$logentry)=@_;
 2941:     $cdom=
 2942:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2943:     $cnum=
 2944:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2945:     unless (&allowed('mky',$cdom)) { return 0; }
 2946:     unless (($cdom) && ($cnum)) { return 0; }
 2947:     if ($number>10000) { return 0; }
 2948:     sleep(2); # make sure don't get same seed twice
 2949:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2950:     my $total=0;
 2951:     for (my $i=1;$i<=$number;$i++) {
 2952:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2953:                   sprintf("%lx",int(100000*rand)).'-'.
 2954:                   sprintf("%lx",int(100000*rand));
 2955:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2956:        $newkey=~s/0/h/g; # and also 0 and O
 2957:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2958:        if ($existing{$newkey}) {
 2959:            $i--;
 2960:        } else {
 2961: 	  if (&put('accesskeys',
 2962:               { $newkey => '# generated '.localtime().
 2963:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2964:                            '; '.$logentry },
 2965: 		   $cdom,$cnum) eq 'ok') {
 2966:               $total++;
 2967: 	  }
 2968:        }
 2969:     }
 2970:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2971:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2972:     return $total;
 2973: }
 2974: 
 2975: # ------------------------------------------------------- Validate an accesskey
 2976: 
 2977: sub validate_access_key {
 2978:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2979:     $cdom=
 2980:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2981:     $cnum=
 2982:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2983:     $udom=$env{'user.domain'} unless (defined($udom));
 2984:     $uname=$env{'user.name'} unless (defined($uname));
 2985:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2986:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2987: }
 2988: 
 2989: # ------------------------------------- Find the section of student in a course
 2990: sub devalidate_getsection_cache {
 2991:     my ($udom,$unam,$courseid)=@_;
 2992:     my $hashid="$udom:$unam:$courseid";
 2993:     &devalidate_cache_new('getsection',$hashid);
 2994: }
 2995: 
 2996: sub courseid_to_courseurl {
 2997:     my ($courseid) = @_;
 2998:     #already url style courseid
 2999:     return $courseid if ($courseid =~ m{^/});
 3000: 
 3001:     if (exists($env{'course.'.$courseid.'.num'})) {
 3002: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3003: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3004: 	return "/$cdom/$cnum";
 3005:     }
 3006: 
 3007:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 3008:     if (exists($courseinfo{'num'})) {
 3009: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3010:     }
 3011: 
 3012:     return undef;
 3013: }
 3014: 
 3015: sub getsection {
 3016:     my ($udom,$unam,$courseid)=@_;
 3017:     my $cachetime=1800;
 3018: 
 3019:     my $hashid="$udom:$unam:$courseid";
 3020:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3021:     if (defined($cached)) { return $result; }
 3022: 
 3023:     my %Pending; 
 3024:     my %Expired;
 3025:     #
 3026:     # Each role can either have not started yet (pending), be active, 
 3027:     #    or have expired.
 3028:     #
 3029:     # If there is an active role, we are done.
 3030:     #
 3031:     # If there is more than one role which has not started yet, 
 3032:     #     choose the one which will start sooner
 3033:     # If there is one role which has not started yet, return it.
 3034:     #
 3035:     # If there is more than one expired role, choose the one which ended last.
 3036:     # If there is a role which has expired, return it.
 3037:     #
 3038:     $courseid = &courseid_to_courseurl($courseid);
 3039:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3040:     foreach my $key (keys(%roleshash)) {
 3041:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3042:         my $section=$1;
 3043:         if ($key eq $courseid.'_st') { $section=''; }
 3044:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3045:         my $now=time;
 3046:         if (defined($end) && $end && ($now > $end)) {
 3047:             $Expired{$end}=$section;
 3048:             next;
 3049:         }
 3050:         if (defined($start) && $start && ($now < $start)) {
 3051:             $Pending{$start}=$section;
 3052:             next;
 3053:         }
 3054:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3055:     }
 3056:     #
 3057:     # Presumedly there will be few matching roles from the above
 3058:     # loop and the sorting time will be negligible.
 3059:     if (scalar(keys(%Pending))) {
 3060:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3061:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3062:     } 
 3063:     if (scalar(keys(%Expired))) {
 3064:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3065:         my $time = pop(@sorted);
 3066:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3067:     }
 3068:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3069: }
 3070: 
 3071: sub save_cache {
 3072:     &purge_remembered();
 3073:     #&Apache::loncommon::validate_page();
 3074:     undef(%env);
 3075:     undef($env_loaded);
 3076: }
 3077: 
 3078: my $to_remember=-1;
 3079: my %remembered;
 3080: my %accessed;
 3081: my $kicks=0;
 3082: my $hits=0;
 3083: sub make_key {
 3084:     my ($name,$id) = @_;
 3085:     if (length($id) > 65 
 3086: 	&& length(&escape($id)) > 200) {
 3087: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3088:     }
 3089:     return &escape($name.':'.$id);
 3090: }
 3091: 
 3092: sub devalidate_cache_new {
 3093:     my ($name,$id,$debug) = @_;
 3094:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3095:     my $remembered_id=$name.':'.$id;
 3096:     $id=&make_key($name,$id);
 3097:     $memcache->delete($id);
 3098:     delete($remembered{$remembered_id});
 3099:     delete($accessed{$remembered_id});
 3100: }
 3101: 
 3102: sub is_cached_new {
 3103:     my ($name,$id,$debug) = @_;
 3104:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3105:     if (exists($remembered{$remembered_id})) {
 3106: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3107: 	$accessed{$remembered_id}=[&gettimeofday()];
 3108: 	$hits++;
 3109: 	return ($remembered{$remembered_id},1);
 3110:     }
 3111:     $id=&make_key($name,$id);
 3112:     my $value = $memcache->get($id);
 3113:     if (!(defined($value))) {
 3114: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3115: 	return (undef,undef);
 3116:     }
 3117:     if ($value eq '__undef__') {
 3118: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3119: 	$value=undef;
 3120:     }
 3121:     &make_room($remembered_id,$value,$debug);
 3122:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3123:     return ($value,1);
 3124: }
 3125: 
 3126: sub do_cache_new {
 3127:     my ($name,$id,$value,$time,$debug) = @_;
 3128:     my $remembered_id=$name.':'.$id;
 3129:     $id=&make_key($name,$id);
 3130:     my $setvalue=$value;
 3131:     if (!defined($setvalue)) {
 3132: 	$setvalue='__undef__';
 3133:     }
 3134:     if (!defined($time) ) {
 3135: 	$time=600;
 3136:     }
 3137:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3138:     my $result = $memcache->set($id,$setvalue,$time);
 3139:     if (! $result) {
 3140: 	&logthis("caching of id -> $id  failed");
 3141: 	$memcache->disconnect_all();
 3142:     }
 3143:     # need to make a copy of $value
 3144:     &make_room($remembered_id,$value,$debug);
 3145:     return $value;
 3146: }
 3147: 
 3148: sub make_room {
 3149:     my ($remembered_id,$value,$debug)=@_;
 3150: 
 3151:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3152:                                     : $value;
 3153:     if ($to_remember<0) { return; }
 3154:     $accessed{$remembered_id}=[&gettimeofday()];
 3155:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3156:     my $to_kick;
 3157:     my $max_time=0;
 3158:     foreach my $other (keys(%accessed)) {
 3159: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3160: 	    $to_kick=$other;
 3161: 	    $max_time=&tv_interval($accessed{$other});
 3162: 	}
 3163:     }
 3164:     delete($remembered{$to_kick});
 3165:     delete($accessed{$to_kick});
 3166:     $kicks++;
 3167:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3168:     return;
 3169: }
 3170: 
 3171: sub purge_remembered {
 3172:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3173:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3174:     undef(%remembered);
 3175:     undef(%accessed);
 3176: }
 3177: # ------------------------------------- Read an entry from a user's environment
 3178: 
 3179: sub userenvironment {
 3180:     my ($udom,$unam,@what)=@_;
 3181:     my $items;
 3182:     foreach my $item (@what) {
 3183:         $items.=&escape($item).'&';
 3184:     }
 3185:     $items=~s/\&$//;
 3186:     my %returnhash=();
 3187:     my $uhome = &homeserver($unam,$udom);
 3188:     unless ($uhome eq 'no_host') {
 3189:         my @answer=split(/\&/, 
 3190:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3191:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3192:             return %returnhash;
 3193:         }
 3194:         my $i;
 3195:         for ($i=0;$i<=$#what;$i++) {
 3196: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3197:         }
 3198:     }
 3199:     return %returnhash;
 3200: }
 3201: 
 3202: # ---------------------------------------------------------- Get a studentphoto
 3203: sub studentphoto {
 3204:     my ($udom,$unam,$ext) = @_;
 3205:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3206:     if (defined($env{'request.course.id'})) {
 3207:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3208:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3209:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3210:             } else {
 3211:                 my ($result,$perm_reqd)=
 3212: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3213:                 if ($result eq 'ok') {
 3214:                     if (!($perm_reqd eq 'yes')) {
 3215:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3216:                     }
 3217:                 }
 3218:             }
 3219:         }
 3220:     } else {
 3221:         my ($result,$perm_reqd) = 
 3222: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3223:         if ($result eq 'ok') {
 3224:             if (!($perm_reqd eq 'yes')) {
 3225:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3226:             }
 3227:         }
 3228:     }
 3229:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3230: }
 3231: 
 3232: sub retrievestudentphoto {
 3233:     my ($udom,$unam,$ext,$type) = @_;
 3234:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3235:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3236:     if ($ret eq 'ok') {
 3237:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3238:         if ($type eq 'thumbnail') {
 3239:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3240:         }
 3241:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3242:         return $tokenurl;
 3243:     } else {
 3244:         if ($type eq 'thumbnail') {
 3245:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3246:         } else { 
 3247:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3248:         }
 3249:     }
 3250: }
 3251: 
 3252: # -------------------------------------------------------------------- New chat
 3253: 
 3254: sub chatsend {
 3255:     my ($newentry,$anon,$group)=@_;
 3256:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3257:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3258:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3259:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3260: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3261: 		   &escape($newentry)).':'.$group,$chome);
 3262: }
 3263: 
 3264: # ------------------------------------------ Find current version of a resource
 3265: 
 3266: sub getversion {
 3267:     my $fname=&clutter(shift);
 3268:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3269:     return &currentversion(&filelocation('',$fname));
 3270: }
 3271: 
 3272: sub currentversion {
 3273:     my $fname=shift;
 3274:     my $author=$fname;
 3275:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3276:     my ($udom,$uname)=split(/\//,$author);
 3277:     my $home=&homeserver($uname,$udom);
 3278:     if ($home eq 'no_host') { 
 3279:         return -1; 
 3280:     }
 3281:     my $answer=&reply("currentversion:$fname",$home);
 3282:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3283: 	return -1;
 3284:     }
 3285:     return $answer;
 3286: }
 3287: 
 3288: #
 3289: # Return special version number of resource if set by override, empty otherwise
 3290: #
 3291: sub usedversion {
 3292:     my $fname=shift;
 3293:     unless ($fname) { $fname=$env{'request.uri'}; }
 3294:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3295:     if ($urlversion) { return $urlversion; }
 3296:     return '';
 3297: }
 3298: 
 3299: # ----------------------------- Subscribe to a resource, return URL if possible
 3300: 
 3301: sub subscribe {
 3302:     my $fname=shift;
 3303:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3304:     $fname=~s/[\n\r]//g;
 3305:     my $author=$fname;
 3306:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3307:     my ($udom,$uname)=split(/\//,$author);
 3308:     my $home=homeserver($uname,$udom);
 3309:     if ($home eq 'no_host') {
 3310:         return 'not_found';
 3311:     }
 3312:     my $answer=reply("sub:$fname",$home);
 3313:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3314: 	$answer.=' by '.$home;
 3315:     }
 3316:     return $answer;
 3317: }
 3318:     
 3319: # -------------------------------------------------------------- Replicate file
 3320: 
 3321: sub repcopy {
 3322:     my $filename=shift;
 3323:     $filename=~s/\/+/\//g;
 3324:     my $londocroot = $perlvar{'lonDocRoot'};
 3325:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3326:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3327:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3328: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3329: 	return &repcopy_userfile($filename);
 3330:     }
 3331:     $filename=~s/[\n\r]//g;
 3332:     my $transname="$filename.in.transfer";
 3333: # FIXME: this should flock
 3334:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3335:     my $remoteurl=subscribe($filename);
 3336:     if ($remoteurl =~ /^con_lost by/) {
 3337: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3338:            return 'unavailable';
 3339:     } elsif ($remoteurl eq 'not_found') {
 3340: 	   #&logthis("Subscribe returned not_found: $filename");
 3341: 	   return 'not_found';
 3342:     } elsif ($remoteurl =~ /^rejected by/) {
 3343: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3344:            return 'forbidden';
 3345:     } elsif ($remoteurl eq 'directory') {
 3346:            return 'ok';
 3347:     } else {
 3348:         my $author=$filename;
 3349:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3350:         my ($udom,$uname)=split(/\//,$author);
 3351:         my $home=homeserver($uname,$udom);
 3352:         unless ($home eq $perlvar{'lonHostID'}) {
 3353:            my @parts=split(/\//,$filename);
 3354:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3355:            if ($path ne "$londocroot/res") {
 3356:                &logthis("Malconfiguration for replication: $filename");
 3357: 	       return 'bad_request';
 3358:            }
 3359:            my $count;
 3360:            for ($count=5;$count<$#parts;$count++) {
 3361:                $path.="/$parts[$count]";
 3362:                if ((-e $path)!=1) {
 3363: 		   mkdir($path,0777);
 3364:                }
 3365:            }
 3366:            my $request=new HTTP::Request('GET',"$remoteurl");
 3367:            my $response;
 3368:            if ($remoteurl =~ m{/raw/}) {
 3369:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3370:            } else {
 3371:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3372:            }
 3373:            if ($response->is_error()) {
 3374: 	       unlink($transname);
 3375:                my $message=$response->status_line;
 3376:                &logthis("<font color=\"blue\">WARNING:"
 3377:                        ." LWP get: $message: $filename</font>");
 3378:                return 'unavailable';
 3379:            } else {
 3380: 	       if ($remoteurl!~/\.meta$/) {
 3381:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3382:                   my $mresponse;
 3383:                   if ($remoteurl =~ m{/raw/}) {
 3384:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3385:                   } else {
 3386:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3387:                   }
 3388:                   if ($mresponse->is_error()) {
 3389: 		      unlink($filename.'.meta');
 3390:                       &logthis(
 3391:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3392:                   }
 3393: 	       }
 3394:                rename($transname,$filename);
 3395:                return 'ok';
 3396:            }
 3397:        }
 3398:     }
 3399: }
 3400: 
 3401: # ------------------------------------------------- Unsubscribe from a resource
 3402: 
 3403: sub unsubscribe {
 3404:     my ($fname) = @_;
 3405:     my $answer;
 3406:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3407:     $fname=~s/[\n\r]//g;
 3408:     my $author=$fname;
 3409:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3410:     my ($udom,$uname)=split(/\//,$author);
 3411:     my $home=homeserver($uname,$udom);
 3412:     if ($home eq 'no_host') {
 3413:         $answer = 'no_host';
 3414:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3415:         $answer = 'home';
 3416:     } else {
 3417:         my $defdom = $perlvar{'lonDefDomain'};
 3418:         if (&will_trust('content',$defdom,$udom)) {
 3419:             $answer = reply("unsub:$fname",$home);
 3420:         } else {
 3421:             $answer = 'untrusted';
 3422:         }
 3423:     }
 3424:     return $answer;
 3425: }
 3426: 
 3427: # ------------------------------------------------ Get server side include body
 3428: sub ssi_body {
 3429:     my ($filelink,%form)=@_;
 3430:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3431:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3432:     }
 3433:     my $output='';
 3434:     my $response;
 3435:     if ($filelink=~/^https?\:/) {
 3436:        ($output,$response)=&externalssi($filelink);
 3437:     } else {
 3438:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3439:        $filelink .= 'inhibitmenu=yes';
 3440:        ($output,$response)=&ssi($filelink,%form);
 3441:     }
 3442:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3443:     $output=~s/^.*?\<body[^\>]*\>//si;
 3444:     $output=~s/\<\/body\s*\>.*?$//si;
 3445:     if (wantarray) {
 3446:         return ($output, $response);
 3447:     } else {
 3448:         return $output;
 3449:     }
 3450: }
 3451: 
 3452: # --------------------------------------------------------- Server Side Include
 3453: 
 3454: sub absolute_url {
 3455:     my ($host_name) = @_;
 3456:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3457:     if ($host_name eq '') {
 3458: 	$host_name = $ENV{'SERVER_NAME'};
 3459:     }
 3460:     return $protocol.$host_name;
 3461: }
 3462: 
 3463: #
 3464: #   Server side include.
 3465: # Parameters:
 3466: #  fn     Possibly encrypted resource name/id.
 3467: #  form   Hash that describes how the rendering should be done
 3468: #         and other things.
 3469: # Returns:
 3470: #   Scalar context: The content of the response.
 3471: #   Array context:  2 element list of the content and the full response object.
 3472: #     
 3473: sub ssi {
 3474: 
 3475:     my ($fn,%form)=@_;
 3476:     my $request;
 3477: 
 3478:     $form{'no_update_last_known'}=1;
 3479:     &Apache::lonenc::check_encrypt(\$fn);
 3480:     if (%form) {
 3481:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3482:       $request->content(join('&',map { 
 3483:             my $name = escape($_);
 3484:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3485:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3486:             : &escape($form{$_}) );    
 3487:         } keys(%form)));
 3488:     } else {
 3489:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3490:     }
 3491: 
 3492:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3493:     my $lonhost = $perlvar{'lonHostID'};
 3494:     my $islocal;
 3495:     if (($env{'request.course.id'}) &&
 3496:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3497:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3498:         ($form{'grade_symb'} ne '') &&
 3499:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3500:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3501:         $islocal = 1;
 3502:     }
 3503:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3504:                                                 '','','',$islocal);
 3505: 
 3506:     if (wantarray) {
 3507: 	return ($response->content, $response);
 3508:     } else {
 3509: 	return $response->content;
 3510:     }
 3511: }
 3512: 
 3513: sub externalssi {
 3514:     my ($url)=@_;
 3515:     my $request=new HTTP::Request('GET',$url);
 3516:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3517:     if (wantarray) {
 3518:         return ($response->content, $response);
 3519:     } else {
 3520:         return $response->content;
 3521:     }
 3522: }
 3523: 
 3524: 
 3525: # If the local copy of a replicated resource is outdated, trigger a  
 3526: # connection from the homeserver to flush the delayed queue. If no update 
 3527: # happens, remove local copies of outdated resource (and corresponding
 3528: # metadata file).
 3529: 
 3530: sub remove_stale_resfile {
 3531:     my ($url) = @_;
 3532:     my $removed;
 3533:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3534:         my $audom = $1;
 3535:         my $auname = $2;
 3536:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3537:             my $homeserver = &homeserver($auname,$audom);
 3538:             unless (($homeserver eq 'no_host') ||
 3539:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3540:                 my $fname = &filelocation('',$url);
 3541:                 if (-e $fname) {
 3542:                     my $hostname = &hostname($homeserver);
 3543:                     if ($hostname) {
 3544:                         my $protocol = $protocol{$homeserver};
 3545:                         $protocol = 'http' if ($protocol ne 'https');
 3546:                         my $uri = &declutter($url);
 3547:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3548:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3549:                         if ($response->is_success()) {
 3550:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3551:                             my $locmodtime = (stat($fname))[9];
 3552:                             if ($locmodtime < $remmodtime) {
 3553:                                 my $stale;
 3554:                                 my $answer = &reply('pong',$homeserver);
 3555:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3556:                                     sleep(0.2);
 3557:                                     $locmodtime = (stat($fname))[9];
 3558:                                     if ($locmodtime < $remmodtime) {
 3559:                                         my $posstransfer = $fname.'.in.transfer';
 3560:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3561:                                             $removed = 1;
 3562:                                         } else {
 3563:                                             $stale = 1;
 3564:                                         }
 3565:                                     } else {
 3566:                                         $removed = 1;
 3567:                                     }
 3568:                                 } else {
 3569:                                     $stale = 1;
 3570:                                 }
 3571:                                 if ($stale) {
 3572:                                     if (unlink($fname)) {
 3573:                                         if ($uri!~/\.meta$/) {
 3574:                                             if (-e $fname.'.meta') {
 3575:                                                 unlink($fname.'.meta');
 3576:                                             }
 3577:                                         }
 3578:                                         my $unsubresult = &unsubscribe($fname);
 3579:                                         unless ($unsubresult eq 'ok') {
 3580:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3581:                                         }
 3582:                                         $removed = 1;
 3583:                                     }
 3584:                                 }
 3585:                             }
 3586:                         }
 3587:                     }
 3588:                 }
 3589:             }
 3590:         }
 3591:     }
 3592:     return $removed;
 3593: }
 3594: 
 3595: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3596: 
 3597: sub allowuploaded {
 3598:     my ($srcurl,$url)=@_;
 3599:     $url=&clutter(&declutter($url));
 3600:     my $dir=$url;
 3601:     $dir=~s/\/[^\/]+$//;
 3602:     my %httpref=();
 3603:     my $httpurl=&hreflocation('',$url);
 3604:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3605:     &Apache::lonnet::appenv(\%httpref);
 3606: }
 3607: 
 3608: #
 3609: # Determine if the current user should be able to edit a particular resource,
 3610: # when viewing in course context.
 3611: # (a) When viewing resource used to determine if "Edit" item is included in 
 3612: #     Functions.
 3613: # (b) When displaying folder contents in course editor, used to determine if
 3614: #     "Edit" link will be displayed alongside resource.
 3615: #
 3616: #  input: six args -- filename (decluttered), course number, course domain,
 3617: #                   url, symb (if registered) and group (if this is a group
 3618: #                   item -- e.g., bulletin board, group page etc.).
 3619: #  output: array of five scalars -- 
 3620: #          $cfile -- url for file editing if editable on current server
 3621: #          $home -- homeserver of resource (i.e., for author if published,
 3622: #                                           or course if uploaded.).
 3623: #          $switchserver --  1 if server switch will be needed.
 3624: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3625: #          $forceview -- 1 if icon/link should be to go to view mode
 3626: #
 3627: 
 3628: sub can_edit_resource {
 3629:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3630:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3631: #
 3632: # For aboutme pages user can only edit his/her own.
 3633: #
 3634:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3635:         my ($sdom,$sname) = ($1,$2);
 3636:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3637:             $home = $env{'user.home'};
 3638:             $cfile = $resurl;
 3639:             if ($env{'form.forceedit'}) {
 3640:                 $forceview = 1;
 3641:             } else {
 3642:                 $forceedit = 1;
 3643:             }
 3644:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3645:         } else {
 3646:             return;
 3647:         }
 3648:     }
 3649: 
 3650:     if ($env{'request.course.id'}) {
 3651:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3652:         if ($group ne '') {
 3653: # if this is a group homepage or group bulletin board, check group privs
 3654:             my $allowed = 0;
 3655:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3656:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3657:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3658:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3659:                     $allowed = 1;
 3660:                 }
 3661:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3662:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3663:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3664:                     $allowed = 1;
 3665:                 }
 3666:             }
 3667:             if ($allowed) {
 3668:                 $home=&homeserver($cnum,$cdom);
 3669:                 if ($env{'form.forceedit'}) {
 3670:                     $forceview = 1;
 3671:                 } else {
 3672:                     $forceedit = 1;
 3673:                 }
 3674:                 $cfile = $resurl;
 3675:             } else {
 3676:                 return;
 3677:             }
 3678:         } else {
 3679:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3680:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3681:                     return;
 3682:                 }
 3683:             } elsif (!$crsedit) {
 3684: #
 3685: # No edit allowed where CC has switched to student role.
 3686: #
 3687:                 return;
 3688:             }
 3689:         }
 3690:     }
 3691: 
 3692:     if ($file ne '') {
 3693:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3694:             if (&is_course_upload($file,$cnum,$cdom)) {
 3695:                 $uploaded = 1;
 3696:                 $incourse = 1;
 3697:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3698:                     $cfile = &hreflocation('',$file);
 3699:                     if ($env{'form.forceedit'}) {
 3700:                         $forceview = 1;
 3701:                     } else {
 3702:                         $forceedit = 1;
 3703:                     }
 3704:                 }
 3705:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3706:                 $incourse = 1;
 3707:                 if ($env{'form.forceedit'}) {
 3708:                     $forceview = 1;
 3709:                 } else {
 3710:                     $forceedit = 1;
 3711:                 }
 3712:                 $cfile = $resurl;
 3713:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3714:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3715:                     $incourse = 1;
 3716:                     if ($env{'form.forceedit'}) {
 3717:                         $forceview = 1;
 3718:                     } else {
 3719:                         $forceedit = 1;
 3720:                     }
 3721:                     $cfile = $resurl;
 3722:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3723:                     $incourse = 1;
 3724:                     $cfile = $resurl.'/smpedit';
 3725:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3726:                     $incourse = 1;
 3727:                     if ($env{'form.forceedit'}) {
 3728:                         $forceview = 1;
 3729:                     } else {
 3730:                         $forceedit = 1;
 3731:                     }
 3732:                     $cfile = $resurl;
 3733:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3734:                     my ($map,$id,$res) = &decode_symb($symb);
 3735:                     if ($map =~ /\.page$/) {
 3736:                         $incourse = 1;
 3737:                         if ($env{'form.forceedit'}) {
 3738:                             $forceview = 1;
 3739:                             $cfile = $map;
 3740:                         } else {
 3741:                             $forceedit = 1;
 3742:                             $cfile =  '/adm/wrapper'.$resurl;
 3743:                         }
 3744:                     }
 3745:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3746:                     $incourse = 1;
 3747:                     if ($env{'form.forceedit'}) {
 3748:                         $forceview = 1;
 3749:                     } else {
 3750:                         $forceedit = 1;
 3751:                     }
 3752:                     $cfile = $resurl;
 3753:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3754:                     $incourse = 1;
 3755:                     if ($env{'form.forceedit'}) {
 3756:                         $forceview = 1;
 3757:                     } else {
 3758:                         $forceedit = 1;
 3759:                     }
 3760:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3761:                 }
 3762:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3763:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3764:                 if (&is_on_map($template)) { 
 3765:                     $incourse = 1;
 3766:                     $forceview = 1;
 3767:                     $cfile = $template;
 3768:                 }
 3769:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3770:                 $incourse = 1;
 3771:                 if ($env{'form.forceedit'}) {
 3772:                     $forceview = 1;
 3773:                 } else {
 3774:                     $forceedit = 1;
 3775:                 }
 3776:                 $cfile = $resurl;
 3777:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3778:                 $incourse = 1;
 3779:                 if ($env{'form.forceedit'}) {
 3780:                     $forceview = 1;
 3781:                 } else {
 3782:                     $forceedit = 1;
 3783:                 }
 3784:                 $cfile = $resurl;
 3785:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3786:                 $incourse = 1;
 3787:                 $forceview = 1;
 3788:                 if ($symb) {
 3789:                     my ($map,$id,$res)=&decode_symb($symb);
 3790:                     $env{'request.symb'} = $symb;
 3791:                     $cfile = &clutter($res);
 3792:                 } else {
 3793:                     $cfile = $env{'form.suppurl'};
 3794:                     my $escfile = &unescape($cfile);
 3795:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3796:                         $cfile = '/adm/wrapper'.$escfile;
 3797:                     } else {
 3798:                         $escfile =~ s{^http://}{};
 3799:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3800:                     }
 3801:                 }
 3802:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3803:                 if ($env{'form.forceedit'}) {
 3804:                     $forceview = 1;
 3805:                 } else {
 3806:                     $forceedit = 1;
 3807:                 }
 3808:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3809:             }
 3810:         }
 3811:         if ($uploaded || $incourse) {
 3812:             $home=&homeserver($cnum,$cdom);
 3813:         } elsif ($file !~ m{/$}) {
 3814:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3815:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3816:             # Check that the user has permission to edit this resource
 3817:             my $setpriv = 1;
 3818:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3819:             if (defined($cfudom)) {
 3820:                 $home=&homeserver($cfuname,$cfudom);
 3821:                 $cfile=$file;
 3822:             }
 3823:         }
 3824:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3825:             (($home ne '') && ($home ne 'no_host'))) {
 3826:             my @ids=&current_machine_ids();
 3827:             unless (grep(/^\Q$home\E$/,@ids)) {
 3828:                 $switchserver=1;
 3829:             }
 3830:         }
 3831:     }
 3832:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3833: }
 3834: 
 3835: sub is_course_upload {
 3836:     my ($file,$cnum,$cdom) = @_;
 3837:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3838:     $uploadpath =~ s{^\/}{};
 3839:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3840:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3841:         return 1;
 3842:     }
 3843:     return;
 3844: }
 3845: 
 3846: sub in_course {
 3847:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3848:     if ($hideprivileged) {
 3849:         my $skipuser;
 3850:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3851:         my @possdoms = ($cdom);  
 3852:         if ($coursehash{'checkforpriv'}) { 
 3853:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3854:         }
 3855:         if (&privileged($uname,$udom,\@possdoms)) {
 3856:             $skipuser = 1;
 3857:             if ($coursehash{'nothideprivileged'}) {
 3858:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3859:                     my $user;
 3860:                     if ($item =~ /:/) {
 3861:                         $user = $item;
 3862:                     } else {
 3863:                         $user = join(':',split(/[\@]/,$item));
 3864:                     }
 3865:                     if ($user eq $uname.':'.$udom) {
 3866:                         undef($skipuser);
 3867:                         last;
 3868:                     }
 3869:                 }
 3870:             }
 3871:             if ($skipuser) {
 3872:                 return 0;
 3873:             }
 3874:         }
 3875:     }
 3876:     $type ||= 'any';
 3877:     if (!defined($cdom) || !defined($cnum)) {
 3878:         my $cid  = $env{'request.course.id'};
 3879:         $cdom = $env{'course.'.$cid.'.domain'};
 3880:         $cnum = $env{'course.'.$cid.'.num'};
 3881:     }
 3882:     my $typesref;
 3883:     if (($type eq 'any') || ($type eq 'all')) {
 3884:         $typesref = ['active','previous','future'];
 3885:     } elsif ($type eq 'previous' || $type eq 'future') {
 3886:         $typesref = [$type];
 3887:     }
 3888:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3889:                               $typesref,undef,[$cdom]);
 3890:     my ($tmp) = keys(%roles);
 3891:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3892:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3893:     if (@course_roles > 0) {
 3894:         return 1;
 3895:     }
 3896:     return 0;
 3897: }
 3898: 
 3899: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3900: # input: action, courseID, current domain, intended
 3901: #        path to file, source of file, instruction to parse file for objects,
 3902: #        ref to hash for embedded objects,
 3903: #        ref to hash for codebase of java objects.
 3904: #        reference to scalar to accommodate mime type determined
 3905: #          from File::MMagic if $parser = parse.
 3906: #
 3907: # output: url to file (if action was uploaddoc), 
 3908: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3909: #
 3910: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3911: # course.
 3912: #
 3913: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3914: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3915: #          course's home server.
 3916: #
 3917: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3918: #          be copied from $source (current location) to 
 3919: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3920: #         and will then be copied to
 3921: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3922: #         course's home server.
 3923: #
 3924: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3925: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3926: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3927: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3928: #         in course's home server.
 3929: #
 3930: 
 3931: sub process_coursefile {
 3932:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3933:         $mimetype)=@_;
 3934:     my $fetchresult;
 3935:     my $home=&homeserver($docuname,$docudom);
 3936:     if ($action eq 'propagate') {
 3937:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3938: 			     $home);
 3939:     } else {
 3940:         my $fpath = '';
 3941:         my $fname = $file;
 3942:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3943:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3944:         my $filepath = &build_filepath($fpath);
 3945:         if ($action eq 'copy') {
 3946:             if ($source eq '') {
 3947:                 $fetchresult = 'no source file';
 3948:                 return $fetchresult;
 3949:             } else {
 3950:                 my $destination = $filepath.'/'.$fname;
 3951:                 rename($source,$destination);
 3952:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3953:                                  $home);
 3954:             }
 3955:         } elsif ($action eq 'uploaddoc') {
 3956:             open(my $fh,'>',$filepath.'/'.$fname);
 3957:             print $fh $env{'form.'.$source};
 3958:             close($fh);
 3959:             if ($parser eq 'parse') {
 3960:                 my $mm = new File::MMagic;
 3961:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3962:                 if ($type eq 'text/html') {
 3963:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3964:                     unless ($parse_result eq 'ok') {
 3965:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3966:                     }
 3967:                 }
 3968:                 if (ref($mimetype)) {
 3969:                     $$mimetype = $type;
 3970:                 } 
 3971:             }
 3972:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3973:                                  $home);
 3974:             if ($fetchresult eq 'ok') {
 3975:                 return '/uploaded/'.$fpath.'/'.$fname;
 3976:             } else {
 3977:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3978:                         ' to host '.$home.': '.$fetchresult);
 3979:                 return '/adm/notfound.html';
 3980:             }
 3981:         }
 3982:     }
 3983:     unless ( $fetchresult eq 'ok') {
 3984:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3985:              ' to host '.$home.': '.$fetchresult);
 3986:     }
 3987:     return $fetchresult;
 3988: }
 3989: 
 3990: sub build_filepath {
 3991:     my ($fpath) = @_;
 3992:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3993:     unless ($fpath eq '') {
 3994:         my @parts=split('/',$fpath);
 3995:         foreach my $part (@parts) {
 3996:             $filepath.= '/'.$part;
 3997:             if ((-e $filepath)!=1) {
 3998:                 mkdir($filepath,0777);
 3999:             }
 4000:         }
 4001:     }
 4002:     return $filepath;
 4003: }
 4004: 
 4005: sub store_edited_file {
 4006:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4007:     my $file = $primary_url;
 4008:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4009:     my $fpath = '';
 4010:     my $fname = $file;
 4011:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4012:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4013:     my $filepath = &build_filepath($fpath);
 4014:     open(my $fh,'>',$filepath.'/'.$fname);
 4015:     print $fh $content;
 4016:     close($fh);
 4017:     my $home=&homeserver($docuname,$docudom);
 4018:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4019: 			  $home);
 4020:     if ($$fetchresult eq 'ok') {
 4021:         return '/uploaded/'.$fpath.'/'.$fname;
 4022:     } else {
 4023:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4024: 		 ' to host '.$home.': '.$$fetchresult);
 4025:         return '/adm/notfound.html';
 4026:     }
 4027: }
 4028: 
 4029: sub clean_filename {
 4030:     my ($fname,$args)=@_;
 4031: # Replace Windows backslashes by forward slashes
 4032:     $fname=~s/\\/\//g;
 4033:     if (!$args->{'keep_path'}) {
 4034:         # Get rid of everything but the actual filename
 4035: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4036:     }
 4037: # Replace spaces by underscores
 4038:     $fname=~s/\s+/\_/g;
 4039: # Transliterate non-ascii text to ascii
 4040:     my $lang = &Apache::lonlocal::current_language();
 4041:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4042: # Replace all other weird characters by nothing
 4043:     $fname=~s{[^/\w\.\-]}{}g;
 4044: # Replace all .\d. sequences with _\d. so they no longer look like version
 4045: # numbers
 4046:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4047:     return $fname;
 4048: }
 4049: 
 4050: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4051: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4052: # image with the same aspect ratio as the original, but with dimensions which do 
 4053: # not exceed $resizewidth and $resizeheight.
 4054:  
 4055: sub resizeImage {
 4056:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4057:     my $ima = Image::Magick->new;
 4058:     my $resized;
 4059:     if (-e $img_path) {
 4060:         $ima->Read($img_path);
 4061:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4062:             my $width = $ima->Get('width');
 4063:             my $height = $ima->Get('height');
 4064:             if ($width > $resizewidth) {
 4065: 	        my $factor = $width/$resizewidth;
 4066:                 my $newheight = $height/$factor;
 4067:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4068:                 $resized = 1;
 4069:             }
 4070:         }
 4071:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4072:             my $width = $ima->Get('width');
 4073:             my $height = $ima->Get('height');
 4074:             if ($height > $resizeheight) {
 4075:                 my $factor = $height/$resizeheight;
 4076:                 my $newwidth = $width/$factor;
 4077:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4078:                 $resized = 1;
 4079:             }
 4080:         }
 4081:         if ($resized) {
 4082:             $ima->Write($img_path);
 4083:         }
 4084:     }
 4085:     return;
 4086: }
 4087: 
 4088: # --------------- Take an uploaded file and put it into the userfiles directory
 4089: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4090: #                    the desired filename is in $env{"form.$formname.filename"}
 4091: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4092: #                                    canceloverwrite, scantron or ''.
 4093: #                   if 'coursedoc': upload to the current course
 4094: #                   if 'existingfile': write file to tmp/overwrites directory 
 4095: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4096: #                   $context is passed as argument to &finishuserfileupload
 4097: #        $subdir - directory in userfile to store the file into
 4098: #        $parser - instruction to parse file for objects ($parser = parse) or
 4099: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4100: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4101: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4102: #        $allfiles - reference to hash for embedded objects
 4103: #        $codebase - reference to hash for codebase of java objects
 4104: #        $desuname - username for permanent storage of uploaded file
 4105: #        $dsetudom - domain for permanaent storage of uploaded file
 4106: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4107: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4108: #        $resizewidth - width (pixels) to which to resize uploaded image
 4109: #        $resizeheight - height (pixels) to which to resize uploaded image
 4110: #        $mimetype - reference to scalar to accommodate mime type determined
 4111: #                    from File::MMagic.
 4112: # 
 4113: # output: url of file in userspace, or error: <message> 
 4114: #             or /adm/notfound.html if failure to upload occurse
 4115: 
 4116: sub userfileupload {
 4117:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4118:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4119:     if (!defined($subdir)) { $subdir='unknown'; }
 4120:     my $fname=$env{'form.'.$formname.'.filename'};
 4121:     $fname=&clean_filename($fname);
 4122:     # See if there is anything left
 4123:     unless ($fname) { return 'error: no uploaded file'; }
 4124:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4125:     if ($fname =~ /^\./) {
 4126:         my ($s,$usec) = &gettimeofday();
 4127:         while (length($usec) < 6) {
 4128:             $usec = '0'.$usec;
 4129:         }
 4130:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4131:     }
 4132:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4133:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4134:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4135:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4136:         my $now = time;
 4137:         my $filepath;
 4138:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4139:              $filepath = 'tmp/helprequests/'.$now;
 4140:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4141:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4142:                          '_'.$env{'user.domain'}.'/pending';
 4143:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4144:             my ($docuname,$docudom);
 4145:             if ($destudom =~ /^$match_domain$/) {
 4146:                 $docudom = $destudom;
 4147:             } else {
 4148:                 $docudom = $env{'user.domain'};
 4149:             }
 4150:             if ($destuname =~ /^$match_username$/) {
 4151:                 $docuname = $destuname;
 4152:             } else {
 4153:                 $docuname = $env{'user.name'};
 4154:             }
 4155:             if (exists($env{'form.group'})) {
 4156:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4157:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4158:             }
 4159:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4160:             if ($context eq 'canceloverwrite') {
 4161:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4162:                 if (-e  $tempfile) {
 4163:                     my @info = stat($tempfile);
 4164:                     if ($info[9] eq $env{'form.timestamp'}) {
 4165:                         unlink($tempfile);
 4166:                     }
 4167:                 }
 4168:                 return;
 4169:             }
 4170:         }
 4171:         # Create the directory if not present
 4172:         my @parts=split(/\//,$filepath);
 4173:         my $fullpath = $perlvar{'lonDaemons'};
 4174:         for (my $i=0;$i<@parts;$i++) {
 4175:             $fullpath .= '/'.$parts[$i];
 4176:             if ((-e $fullpath)!=1) {
 4177:                 mkdir($fullpath,0777);
 4178:             }
 4179:         }
 4180:         open(my $fh,'>',$fullpath.'/'.$fname);
 4181:         print $fh $env{'form.'.$formname};
 4182:         close($fh);
 4183:         if ($context eq 'existingfile') {
 4184:             my @info = stat($fullpath.'/'.$fname);
 4185:             return ($fullpath.'/'.$fname,$info[9]);
 4186:         } else {
 4187:             return $fullpath.'/'.$fname;
 4188:         }
 4189:     }
 4190:     if ($subdir eq 'scantron') {
 4191:         $fname = 'scantron_orig_'.$fname;
 4192:     } else {
 4193:         $fname="$subdir/$fname";
 4194:     }
 4195:     if ($context eq 'coursedoc') {
 4196: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4197: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4198:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4199:             return &finishuserfileupload($docuname,$docudom,
 4200: 					 $formname,$fname,$parser,$allfiles,
 4201: 					 $codebase,$thumbwidth,$thumbheight,
 4202:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4203:         } else {
 4204:             if ($env{'form.folder'}) {
 4205:                 $fname=$env{'form.folder'}.'/'.$fname;
 4206:             }
 4207:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4208: 				       $fname,$formname,$parser,
 4209: 				       $allfiles,$codebase,$mimetype);
 4210:         }
 4211:     } elsif (defined($destuname)) {
 4212:         my $docuname=$destuname;
 4213:         my $docudom=$destudom;
 4214: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4215: 				     $parser,$allfiles,$codebase,
 4216:                                      $thumbwidth,$thumbheight,
 4217:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4218:     } else {
 4219:         my $docuname=$env{'user.name'};
 4220:         my $docudom=$env{'user.domain'};
 4221:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4222:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4223:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4224:         }
 4225: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4226: 				     $parser,$allfiles,$codebase,
 4227:                                      $thumbwidth,$thumbheight,
 4228:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4229:     }
 4230: }
 4231: 
 4232: sub finishuserfileupload {
 4233:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4234:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4235:     my $path=$docudom.'/'.$docuname.'/';
 4236:     my $filepath=$perlvar{'lonDocRoot'};
 4237:   
 4238:     my ($fnamepath,$file,$fetchthumb);
 4239:     $file=$fname;
 4240:     if ($fname=~m|/|) {
 4241:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4242: 	$path.=$fnamepath.'/';
 4243:     }
 4244:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4245:     my $count;
 4246:     for ($count=4;$count<=$#parts;$count++) {
 4247:         $filepath.="/$parts[$count]";
 4248:         if ((-e $filepath)!=1) {
 4249: 	    mkdir($filepath,0777);
 4250:         }
 4251:     }
 4252: 
 4253: # Save the file
 4254:     {
 4255: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4256: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4257: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4258: 	    return '/adm/notfound.html';
 4259: 	}
 4260:         if ($context eq 'overwrite') {
 4261:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4262:             my $target = $filepath.'/'.$file;
 4263:             if (-e $source) {
 4264:                 my @info = stat($source);
 4265:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4266:                     unless (&File::Copy::move($source,$target)) {
 4267:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4268:                         return "Moving from $source failed";
 4269:                     }
 4270:                 } else {
 4271:                     return "Temporary file: $source had unexpected date/time for last modification";
 4272:                 }
 4273:             } else {
 4274:                 return "Temporary file: $source missing";
 4275:             }
 4276:         } elsif (!print FH ($env{'form.'.$formname})) {
 4277: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4278: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4279: 	    return '/adm/notfound.html';
 4280: 	}
 4281: 	close(FH);
 4282:         if ($resizewidth && $resizeheight) {
 4283:             my $mm = new File::MMagic;
 4284:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4285:             if ($mime_type =~ m{^image/}) {
 4286: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4287:             }  
 4288: 	}
 4289:     }
 4290:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4291:         if (ref($mimetype)) {
 4292:             if ($$mimetype eq '') {
 4293:                 my $mm = new File::MMagic;
 4294:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4295:                 $$mimetype = $type;
 4296:             }
 4297:         }
 4298:     }
 4299:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4300:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4301:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4302:                                                        $allfiles,$codebase);
 4303:             unless ($parse_result eq 'ok') {
 4304:                 &logthis('Failed to parse '.$filepath.$file.
 4305: 	   	         ' for embedded media: '.$parse_result); 
 4306:             }
 4307:         }
 4308:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4309:         my $format = $env{'form.scantron_format'};
 4310:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4311:     }
 4312:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4313:         my $input = $filepath.'/'.$file;
 4314:         my $output = $filepath.'/'.'tn-'.$file;
 4315:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4316:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4317:         system({$args[0]} @args);
 4318:         if (-e $filepath.'/'.'tn-'.$file) {
 4319:             $fetchthumb  = 1; 
 4320:         }
 4321:     }
 4322:  
 4323: # Notify homeserver to grep it
 4324: #
 4325:     my $docuhome=&homeserver($docuname,$docudom);	
 4326:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4327:     if ($fetchresult eq 'ok') {
 4328:         if ($fetchthumb) {
 4329:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4330:             if ($thumbresult ne 'ok') {
 4331:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4332:                          $docuhome.': '.$thumbresult);
 4333:             }
 4334:         }
 4335: #
 4336: # Return the URL to it
 4337:         return '/uploaded/'.$path.$file;
 4338:     } else {
 4339:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4340: 		 ': '.$fetchresult);
 4341:         return '/adm/notfound.html';
 4342:     }
 4343: }
 4344: 
 4345: sub extract_embedded_items {
 4346:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4347:     my @state = ();
 4348:     my (%lastids,%related,%shockwave,%flashvars);
 4349:     my %javafiles = (
 4350:                       codebase => '',
 4351:                       code => '',
 4352:                       archive => ''
 4353:                     );
 4354:     my %mediafiles = (
 4355:                       src => '',
 4356:                       movie => '',
 4357:                      );
 4358:     my $p;
 4359:     if ($content) {
 4360:         $p = HTML::LCParser->new($content);
 4361:     } else {
 4362:         $p = HTML::LCParser->new($fullpath);
 4363:     }
 4364:     while (my $t=$p->get_token()) {
 4365: 	if ($t->[0] eq 'S') {
 4366: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4367: 	    push(@state, $tagname);
 4368:             if (lc($tagname) eq 'allow') {
 4369:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4370:             }
 4371: 	    if (lc($tagname) eq 'img') {
 4372: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4373: 	    }
 4374: 	    if (lc($tagname) eq 'a') {
 4375:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4376:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4377:                 }
 4378: 	    }
 4379:             if (lc($tagname) eq 'script') {
 4380:                 my $src;
 4381:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4382:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4383:                 } else {
 4384:                     if ($attr->{'src'} ne '') {
 4385:                         $src = $attr->{'src'};
 4386:                         &add_filetype($allfiles,$src,'src');
 4387:                     }
 4388:                 }
 4389:                 my $text = $p->get_trimmed_text();
 4390:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4391:                     my @swfargs = split(/,/,$1);
 4392:                     foreach my $item (@swfargs) {
 4393:                         $item =~ s/["']//g;
 4394:                         $item =~ s/^\s+//;
 4395:                         $item =~ s/\s+$//;
 4396:                     }
 4397:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4398:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4399:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4400:                         } else {
 4401:                             $related{$swfargs[0]} = [$swfargs[2]];
 4402:                         }
 4403:                     }
 4404:                 }
 4405:             }
 4406:             if (lc($tagname) eq 'link') {
 4407:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4408:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4409:                 }
 4410:             }
 4411: 	    if (lc($tagname) eq 'object' ||
 4412: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4413: 		foreach my $item (keys(%javafiles)) {
 4414: 		    $javafiles{$item} = '';
 4415: 		}
 4416:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4417:                     $lastids{lc($tagname)} = $attr->{'id'};
 4418:                 }
 4419: 	    }
 4420: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4421: 		my $name = lc($attr->{'name'});
 4422: 		foreach my $item (keys(%javafiles)) {
 4423: 		    if ($name eq $item) {
 4424: 			$javafiles{$item} = $attr->{'value'};
 4425: 			last;
 4426: 		    }
 4427: 		}
 4428:                 my $pathfrom;
 4429: 		foreach my $item (keys(%mediafiles)) {
 4430: 		    if ($name eq $item) {
 4431:                         $pathfrom = $attr->{'value'};
 4432:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4433: 			&add_filetype($allfiles,$pathfrom,$name);
 4434: 			last;
 4435: 		    }
 4436: 		}
 4437:                 if ($name eq 'flashvars') {
 4438:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4439:                 }
 4440:                 if ($pathfrom ne '') {
 4441:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4442:                                          $pathfrom);
 4443:                 }
 4444: 	    }
 4445: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4446: 		foreach my $item (keys(%javafiles)) {
 4447: 		    if ($attr->{$item}) {
 4448: 			$javafiles{$item} = $attr->{$item};
 4449: 			last;
 4450: 		    }
 4451: 		}
 4452: 		foreach my $item (keys(%mediafiles)) {
 4453: 		    if ($attr->{$item}) {
 4454: 			&add_filetype($allfiles,$attr->{$item},$item);
 4455: 			last;
 4456: 		    }
 4457: 		}
 4458:                 if (lc($tagname) eq 'embed') {
 4459:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4460:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4461:                                              $attr->{'src'});
 4462:                     }
 4463:                 }
 4464: 	    }
 4465:             if (lc($tagname) eq 'iframe') {
 4466:                 my $src = $attr->{'src'} ;
 4467:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4468:                     &add_filetype($allfiles,$src,'src');
 4469:                 } elsif ($src =~ m{^/}) {
 4470:                     if ($env{'request.course.id'}) {
 4471:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4472:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4473:                         my $url = &hreflocation('',$fullpath);
 4474:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4475:                             my $relpath = $1;
 4476:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4477:                                 &add_filetype($allfiles,$1,'src');
 4478:                             }
 4479:                         }
 4480:                     }
 4481:                 }
 4482:             }
 4483:             if ($t->[4] =~ m{/>$}) {
 4484:                 pop(@state);
 4485:             }
 4486: 	} elsif ($t->[0] eq 'E') {
 4487: 	    my ($tagname) = ($t->[1]);
 4488: 	    if ($javafiles{'codebase'} ne '') {
 4489: 		$javafiles{'codebase'} .= '/';
 4490: 	    }  
 4491: 	    if (lc($tagname) eq 'applet' ||
 4492: 		lc($tagname) eq 'object' ||
 4493: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4494: 		) {
 4495: 		foreach my $item (keys(%javafiles)) {
 4496: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4497: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4498: 			&add_filetype($allfiles,$file,$item);
 4499: 		    }
 4500: 		}
 4501: 	    } 
 4502: 	    pop @state;
 4503: 	}
 4504:     }
 4505:     foreach my $id (sort(keys(%flashvars))) {
 4506:         if ($shockwave{$id} ne '') {
 4507:             my @pairs = split(/\&/,$flashvars{$id});
 4508:             foreach my $pair (@pairs) {
 4509:                 my ($key,$value) = split(/\=/,$pair);
 4510:                 if ($key eq 'thumb') {
 4511:                     &add_filetype($allfiles,$value,$key);
 4512:                 } elsif ($key eq 'content') {
 4513:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4514:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4515:                     if ($ext ne '') {
 4516:                         &add_filetype($allfiles,$path.$value,$ext);
 4517:                     }
 4518:                 }
 4519:             }
 4520:         }
 4521:     }
 4522:     return 'ok';
 4523: }
 4524: 
 4525: sub add_filetype {
 4526:     my ($allfiles,$file,$type)=@_;
 4527:     if (exists($allfiles->{$file})) {
 4528: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4529: 	    push(@{$allfiles->{$file}}, &escape($type));
 4530: 	}
 4531:     } else {
 4532: 	@{$allfiles->{$file}} = (&escape($type));
 4533:     }
 4534: }
 4535: 
 4536: sub embedded_dependency {
 4537:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4538:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4539:         if (($identifier ne '') &&
 4540:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4541:             ($pathfrom ne '')) {
 4542:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4543:             foreach my $dep (@{$related->{$identifier}}) {
 4544:                 &add_filetype($allfiles,$path.$dep,'object');
 4545:             }
 4546:         }
 4547:     }
 4548:     return;
 4549: }
 4550: 
 4551: sub bubblesheet_converter {
 4552:     my ($cdom,$fullpath,$config,$format) = @_;
 4553:     if ((&domain($cdom) ne '') &&
 4554:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4555:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4556:         my (%csvcols,%csvoptions);
 4557:         if (ref($config->{'fields'}) eq 'HASH') {  
 4558:             %csvcols = %{$config->{'fields'}};
 4559:         }
 4560:         if (ref($config->{'options'}) eq 'HASH') {
 4561:             %csvoptions = %{$config->{'options'}};
 4562:         }
 4563:         my %csvbynum = reverse(%csvcols);
 4564:         my %scantronconf = &get_scantron_config($format,$cdom);
 4565:         if (keys(%scantronconf)) {
 4566:             my %bynum = (
 4567:                           $scantronconf{CODEstart} => 'CODEstart',
 4568:                           $scantronconf{IDstart}   => 'IDstart',
 4569:                           $scantronconf{PaperID}   => 'PaperID',
 4570:                           $scantronconf{FirstName} => 'FirstName',
 4571:                           $scantronconf{LastName}  => 'LastName',
 4572:                           $scantronconf{Qstart}    => 'Qstart',
 4573:                         );
 4574:             my @ordered;
 4575:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4576:                 push(@ordered,$bynum{$item});
 4577:             }
 4578:             my %mapstart = (
 4579:                               CODEstart => 'CODE',
 4580:                               IDstart   => 'ID',
 4581:                               PaperID   => 'PaperID',
 4582:                               FirstName => 'FirstName',
 4583:                               LastName  => 'LastName',
 4584:                               Qstart    => 'FirstQuestion',
 4585:                            );
 4586:             my %maplength = (
 4587:                               CODEstart => 'CODElength',
 4588:                               IDstart   => 'IDlength',
 4589:                               PaperID   => 'PaperIDlength',
 4590:                               FirstName => 'FirstNamelength',
 4591:                               LastName  => 'LastNamelength',
 4592:             );
 4593:             if (open(my $fh,'<',$fullpath)) {
 4594:                 my $output;
 4595:                 my %lettdig = &letter_to_digits();
 4596:                 my %diglett = reverse(%lettdig);
 4597:                 my $numletts = scalar(keys(%lettdig));
 4598:                 my $num = 0;
 4599:                 while (my $line=<$fh>) {
 4600:                     $num ++;
 4601:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4602:                     $line =~ s{[\r\n]+$}{};
 4603:                     my %found;
 4604:                     my @values = split(/,/,$line);
 4605:                     my ($qstart,$record);
 4606:                     for (my $i=0; $i<@values; $i++) {
 4607:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4608:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4609:                             if ($values[$i] eq '') {
 4610:                                 $values[$i] = $scantronconf{'Qoff'};
 4611:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4612:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4613:                                     $values[$i] = $lettdig{uc($values[$i])};
 4614:                                 }
 4615:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4616:                                 if ($values[$i] =~ /^[0-9]$/) {
 4617:                                     $values[$i] = $diglett{$values[$i]};
 4618:                                 }
 4619:                             } else {
 4620:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4621:                                     my $digit;
 4622:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4623:                                         $digit = $lettdig{uc($values[$i])}-1;
 4624:                                         if ($values[$i] eq 'J') {
 4625:                                             $digit += $numletts;
 4626:                                         }
 4627:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4628:                                         $digit = $values[$i]-1;
 4629:                                         if ($values[$i] eq '0') {
 4630:                                             $digit += $numletts;
 4631:                                         }
 4632:                                     }
 4633:                                     my $qval='';
 4634:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4635:                                         if ($j == $digit) {
 4636:                                             $qval .= $scantronconf{'Qon'};
 4637:                                         } else {
 4638:                                             $qval .= $scantronconf{'Qoff'};
 4639:                                         }
 4640:                                     }
 4641:                                     $values[$i] = $qval;
 4642:                                 }
 4643:                             }
 4644:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4645:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4646:                             }
 4647:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4648:                             if ($numblank > 0) {
 4649:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4650:                             }
 4651:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4652:                                 $qstart = $i;
 4653:                                 $found{$csvbynum{$i}} = $values[$i];
 4654:                             } else {
 4655:                                 $found{'FirstQuestion'} .= $values[$i];
 4656:                             }
 4657:                         } elsif (exists($csvbynum{$i})) {
 4658:                             if ($csvoptions{'rem'}) {
 4659:                                 $values[$i] =~ s/^\s+//;
 4660:                             }
 4661:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4662:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4663:                                     $values[$i] = '0'.$values[$i];
 4664:                                 }
 4665:                             }
 4666:                             $found{$csvbynum{$i}} = $values[$i];
 4667:                         }
 4668:                     }
 4669:                     foreach my $item (@ordered) {
 4670:                         my $currlength = 1+length($record);
 4671:                         my $numspaces = $scantronconf{$item} - $currlength;
 4672:                         if ($numspaces > 0) {
 4673:                             $record .= (' ' x $numspaces);
 4674:                         }
 4675:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4676:                             unless ($item eq 'Qstart') {
 4677:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4678:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4679:                                 }
 4680:                             }
 4681:                             $record .= $found{$mapstart{$item}};
 4682:                         }
 4683:                     }
 4684:                     $output .= "$record\n";
 4685:                 }
 4686:                 close($fh);
 4687:                 if ($output) {
 4688:                     if (open(my $fh,'>',$fullpath)) {
 4689:                         print $fh $output;
 4690:                         close($fh);
 4691:                     }
 4692:                 }
 4693:             }
 4694:         }
 4695:         return;
 4696:     }
 4697: }
 4698: 
 4699: sub letter_to_digits {
 4700:     my %lettdig = (
 4701:                     A => 1,
 4702:                     B => 2,
 4703:                     C => 3,
 4704:                     D => 4,
 4705:                     E => 5,
 4706:                     F => 6,
 4707:                     G => 7,
 4708:                     H => 8,
 4709:                     I => 9,
 4710:                     J => 0,
 4711:                   );
 4712:     return %lettdig;
 4713: }
 4714: 
 4715: sub get_scantron_config {
 4716:     my ($which,$cdom) = @_;
 4717:     my @lines = &get_scantronformat_file($cdom);
 4718:     my %config;
 4719:     #FIXME probably should move to XML it has already gotten a bit much now
 4720:     foreach my $line (@lines) {
 4721:         my ($name,$descrip)=split(/:/,$line);
 4722:         if ($name ne $which ) { next; }
 4723:         chomp($line);
 4724:         my @config=split(/:/,$line);
 4725:         $config{'name'}=$config[0];
 4726:         $config{'description'}=$config[1];
 4727:         $config{'CODElocation'}=$config[2];
 4728:         $config{'CODEstart'}=$config[3];
 4729:         $config{'CODElength'}=$config[4];
 4730:         $config{'IDstart'}=$config[5];
 4731:         $config{'IDlength'}=$config[6];
 4732:         $config{'Qstart'}=$config[7];
 4733:         $config{'Qlength'}=$config[8];
 4734:         $config{'Qoff'}=$config[9];
 4735:         $config{'Qon'}=$config[10];
 4736:         $config{'PaperID'}=$config[11];
 4737:         $config{'PaperIDlength'}=$config[12];
 4738:         $config{'FirstName'}=$config[13];
 4739:         $config{'FirstNamelength'}=$config[14];
 4740:         $config{'LastName'}=$config[15];
 4741:         $config{'LastNamelength'}=$config[16];
 4742:         $config{'BubblesPerRow'}=$config[17];
 4743:         last;
 4744:     }
 4745:     return %config;
 4746: }
 4747: 
 4748: sub get_scantronformat_file {
 4749:     my ($cdom) = @_;
 4750:     if ($cdom eq '') {
 4751:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4752:     }
 4753:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4754:     my $gottab = 0;
 4755:     my @lines;
 4756:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4757:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4758:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4759:             if ($formatfile ne '-1') {
 4760:                 @lines = split("\n",$formatfile,-1);
 4761:                 $gottab = 1;
 4762:             }
 4763:         }
 4764:     }
 4765:     if (!$gottab) {
 4766:         my $confname = $cdom.'-domainconfig';
 4767:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4768:         my $formatfile = &getfile($default);
 4769:         if ($formatfile ne '-1') {
 4770:             @lines = split("\n",$formatfile,-1);
 4771:             $gottab = 1;
 4772:         }
 4773:     }
 4774:     if (!$gottab) {
 4775:         my @domains = &current_machine_domains();
 4776:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4777:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4778:                 @lines = <$fh>;
 4779:                 close($fh);
 4780:             }
 4781:         } else {
 4782:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4783:                 @lines = <$fh>;
 4784:                 close($fh);
 4785:             }
 4786:         }
 4787:     }
 4788:     return @lines;
 4789: }
 4790: 
 4791: sub removeuploadedurl {
 4792:     my ($url)=@_;	
 4793:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4794:     return &removeuserfile($uname,$udom,$fname);
 4795: }
 4796: 
 4797: sub removeuserfile {
 4798:     my ($docuname,$docudom,$fname)=@_;
 4799:     my $home=&homeserver($docuname,$docudom);    
 4800:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4801:     if ($result eq 'ok') {	
 4802:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4803:             my $metafile = $fname.'.meta';
 4804:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4805: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4806:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4807:             my $sqlresult = 
 4808:                 &update_portfolio_table($docuname,$docudom,$file,
 4809:                                         'portfolio_metadata',$group,
 4810:                                         'delete');
 4811:         }
 4812:     }
 4813:     return $result;
 4814: }
 4815: 
 4816: sub mkdiruserfile {
 4817:     my ($docuname,$docudom,$dir)=@_;
 4818:     my $home=&homeserver($docuname,$docudom);
 4819:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4820: }
 4821: 
 4822: sub renameuserfile {
 4823:     my ($docuname,$docudom,$old,$new)=@_;
 4824:     my $home=&homeserver($docuname,$docudom);
 4825:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4826:                         &escape("$old").':'.&escape("$new"),$home);
 4827:     if ($result eq 'ok') {
 4828:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4829:             my $oldmeta = $old.'.meta';
 4830:             my $newmeta = $new.'.meta';
 4831:             my $metaresult = 
 4832:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4833: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4834:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4835:             my $sqlresult = 
 4836:                 &update_portfolio_table($docuname,$docudom,$file,
 4837:                                         'portfolio_metadata',$group,
 4838:                                         'delete');
 4839:         }
 4840:     }
 4841:     return $result;
 4842: }
 4843: 
 4844: # ------------------------------------------------------------------------- Log
 4845: 
 4846: sub log {
 4847:     my ($dom,$nam,$hom,$what)=@_;
 4848:     return critical("log:$dom:$nam:$what",$hom);
 4849: }
 4850: 
 4851: # ------------------------------------------------------------------ Course Log
 4852: #
 4853: # This routine flushes several buffers of non-mission-critical nature
 4854: #
 4855: 
 4856: sub flushcourselogs {
 4857:     &logthis('Flushing log buffers');
 4858: #
 4859: # course logs
 4860: # This is a log of all transactions in a course, which can be used
 4861: # for data mining purposes
 4862: #
 4863: # It also collects the courseid database, which lists last transaction
 4864: # times and course titles for all courseids
 4865: #
 4866:     my %courseidbuffer=();
 4867:     foreach my $crsid (keys(%courselogs)) {
 4868:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4869: 		          &escape($courselogs{$crsid}),
 4870: 		          $coursehombuf{$crsid}) eq 'ok') {
 4871: 	    delete $courselogs{$crsid};
 4872:         } else {
 4873:             &logthis('Failed to flush log buffer for '.$crsid);
 4874:             if (length($courselogs{$crsid})>40000) {
 4875:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4876:                         " exceeded maximum size, deleting.</font>");
 4877:                delete $courselogs{$crsid};
 4878:             }
 4879:         }
 4880:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4881:             'description' => $coursedescrbuf{$crsid},
 4882:             'inst_code'    => $courseinstcodebuf{$crsid},
 4883:             'type'        => $coursetypebuf{$crsid},
 4884:             'owner'       => $courseownerbuf{$crsid},
 4885:         };
 4886:     }
 4887: #
 4888: # Write course id database (reverse lookup) to homeserver of courses 
 4889: # Is used in pickcourse
 4890: #
 4891:     foreach my $crs_home (keys(%courseidbuffer)) {
 4892:         my $response = &courseidput(&host_domain($crs_home),
 4893:                                     $courseidbuffer{$crs_home},
 4894:                                     $crs_home,'timeonly');
 4895:     }
 4896: #
 4897: # File accesses
 4898: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4899: #
 4900:     foreach my $entry (keys(%accesshash)) {
 4901:         if ($entry =~ /___count$/) {
 4902:             my ($dom,$name);
 4903:             ($dom,$name,undef)=
 4904: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4905:             if (! defined($dom) || $dom eq '' || 
 4906:                 ! defined($name) || $name eq '') {
 4907:                 my $cid = $env{'request.course.id'};
 4908:                 $dom  = $env{'request.'.$cid.'.domain'};
 4909:                 $name = $env{'request.'.$cid.'.num'};
 4910:             }
 4911:             my $value = $accesshash{$entry};
 4912:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4913:             my %temphash=($url => $value);
 4914:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4915:             if ($result eq 'ok') {
 4916:                 delete $accesshash{$entry};
 4917:             }
 4918:         } else {
 4919:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4920:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4921:             my %temphash=($entry => $accesshash{$entry});
 4922:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4923:                 delete $accesshash{$entry};
 4924:             }
 4925:         }
 4926:     }
 4927: #
 4928: # Roles
 4929: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4930: #
 4931:     foreach my $entry (keys(%userrolehash)) {
 4932:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4933: 	    split(/\:/,$entry);
 4934:         if (&Apache::lonnet::put('nohist_userroles',
 4935:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4936:                 $rudom,$runame) eq 'ok') {
 4937: 	    delete $userrolehash{$entry};
 4938:         }
 4939:     }
 4940: #
 4941: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4942: #
 4943:     my %domrolebuffer = ();
 4944:     foreach my $entry (keys(%domainrolehash)) {
 4945:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4946:         if ($domrolebuffer{$rudom}) {
 4947:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4948:                       '='.&escape($domainrolehash{$entry});
 4949:         } else {
 4950:             $domrolebuffer{$rudom}.=&escape($entry).
 4951:                       '='.&escape($domainrolehash{$entry});
 4952:         }
 4953:         delete $domainrolehash{$entry};
 4954:     }
 4955:     foreach my $dom (keys(%domrolebuffer)) {
 4956: 	my %servers;
 4957: 	if (defined(&domain($dom,'primary'))) {
 4958: 	    my $primary=&domain($dom,'primary');
 4959: 	    my $hostname=&hostname($primary);
 4960: 	    $servers{$primary} = $hostname;
 4961: 	} else { 
 4962: 	    %servers = &get_servers($dom,'library');
 4963: 	}
 4964: 	foreach my $tryserver (keys(%servers)) {
 4965: 	    if (&reply('domroleput:'.$dom.':'.
 4966: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4967: 		last;
 4968: 	    } else {  
 4969: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4970: 	    }
 4971:         }
 4972:     }
 4973:     $dumpcount++;
 4974: }
 4975: 
 4976: sub courselog {
 4977:     my $what=shift;
 4978:     $what=time.':'.$what;
 4979:     unless ($env{'request.course.id'}) { return ''; }
 4980:     $coursedombuf{$env{'request.course.id'}}=
 4981:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4982:     $coursenumbuf{$env{'request.course.id'}}=
 4983:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4984:     $coursehombuf{$env{'request.course.id'}}=
 4985:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4986:     $coursedescrbuf{$env{'request.course.id'}}=
 4987:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4988:     $courseinstcodebuf{$env{'request.course.id'}}=
 4989:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4990:     $courseownerbuf{$env{'request.course.id'}}=
 4991:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4992:     $coursetypebuf{$env{'request.course.id'}}=
 4993:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4994:     if (defined $courselogs{$env{'request.course.id'}}) {
 4995: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4996:     } else {
 4997: 	$courselogs{$env{'request.course.id'}}.=$what;
 4998:     }
 4999:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5000: 	&flushcourselogs();
 5001:     }
 5002: }
 5003: 
 5004: sub courseacclog {
 5005:     my $fnsymb=shift;
 5006:     unless ($env{'request.course.id'}) { return ''; }
 5007:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5008:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5009:         $what.=':POST';
 5010:         # FIXME: Probably ought to escape things....
 5011: 	foreach my $key (keys(%env)) {
 5012:             if ($key=~/^form\.(.*)/) {
 5013:                 my $formitem = $1;
 5014:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5015:                     $what.=':'.$formitem.'='.$env{$key};
 5016:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5017:                     if ($formitem eq 'proctorpassword') {
 5018:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5019:                     } else {
 5020:                         $what.=':'.$formitem.'='.$env{$key};
 5021:                     }
 5022:                 }
 5023:             }
 5024:         }
 5025:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5026:         # FIXME: We should not be depending on a form parameter that someone
 5027:         # editing lonsearchcat.pm might change in the future.
 5028:         if ($env{'form.phase'} eq 'course_search') {
 5029:             $what.= ':POST';
 5030:             # FIXME: Probably ought to escape things....
 5031:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5032:                                  'crsdiscuss') {
 5033:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5034:             }
 5035:         }
 5036:     }
 5037:     &courselog($what);
 5038: }
 5039: 
 5040: sub countacc {
 5041:     my $url=&declutter(shift);
 5042:     return if (! defined($url) || $url eq '');
 5043:     unless ($env{'request.course.id'}) { return ''; }
 5044: #
 5045: # Mark that this url was used in this course
 5046: #
 5047:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5048: #
 5049: # Increase the access count for this resource in this child process
 5050: #
 5051:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5052:     $accesshash{$key}++;
 5053: }
 5054: 
 5055: sub linklog {
 5056:     my ($from,$to)=@_;
 5057:     $from=&declutter($from);
 5058:     $to=&declutter($to);
 5059:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5060:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5061: }
 5062: 
 5063: sub statslog {
 5064:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5065:     if ($users<2) { return; }
 5066:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5067:             'course'       => $env{'request.course.id'},
 5068:             'sections'     => '"all"',
 5069:             'num_students' => $users,
 5070:             'part'         => $part,
 5071:             'symb'         => $symb,
 5072:             'mean_tries'   => $av_attempts,
 5073:             'deg_of_diff'  => $degdiff});
 5074:     foreach my $key (keys(%dynstore)) {
 5075:         $accesshash{$key}=$dynstore{$key};
 5076:     }
 5077: }
 5078:   
 5079: sub userrolelog {
 5080:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5081:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5082:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5083:        $userrolehash
 5084:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5085:                     =$tend.':'.$tstart;
 5086:     }
 5087:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5088:        $userrolehash
 5089:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5090:                     =$tend.':'.$tstart;
 5091:     }
 5092:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5093:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5094:        $domainrolehash
 5095:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5096:                     = $tend.':'.$tstart;
 5097:     }
 5098: }
 5099: 
 5100: sub courserolelog {
 5101:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5102:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5103:         my $cdom = $1;
 5104:         my $cnum = $2;
 5105:         my $sec = $3;
 5106:         my $namespace = 'rolelog';
 5107:         my %storehash = (
 5108:                            role    => $trole,
 5109:                            start   => $tstart,
 5110:                            end     => $tend,
 5111:                            selfenroll => $selfenroll,
 5112:                            context    => $context,
 5113:                         );
 5114:         if ($trole eq 'gr') {
 5115:             $namespace = 'groupslog';
 5116:             $storehash{'group'} = $sec;
 5117:         } else {
 5118:             $storehash{'section'} = $sec;
 5119:         }
 5120:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5121:                    $domain,$cnum,$cdom);
 5122:         if (($trole ne 'st') || ($sec ne '')) {
 5123:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5124:         }
 5125:     }
 5126:     return;
 5127: }
 5128: 
 5129: sub domainrolelog {
 5130:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5131:     if ($area =~ m{^/($match_domain)/$}) {
 5132:         my $cdom = $1;
 5133:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5134:         my $namespace = 'rolelog';
 5135:         my %storehash = (
 5136:                            role    => $trole,
 5137:                            start   => $tstart,
 5138:                            end     => $tend,
 5139:                            context => $context,
 5140:                         );
 5141:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5142:                    $domain,$domconfiguser,$cdom);
 5143:     }
 5144:     return;
 5145: 
 5146: }
 5147: 
 5148: sub coauthorrolelog {
 5149:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5150:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5151:         my $audom = $1;
 5152:         my $auname = $2;
 5153:         my $namespace = 'rolelog';
 5154:         my %storehash = (
 5155:                            role    => $trole,
 5156:                            start   => $tstart,
 5157:                            end     => $tend,
 5158:                            context => $context,
 5159:                         );
 5160:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5161:                    $domain,$auname,$audom);
 5162:     }
 5163:     return;
 5164: }
 5165: 
 5166: sub get_course_adv_roles {
 5167:     my ($cid,$codes) = @_;
 5168:     $cid=$env{'request.course.id'} unless (defined($cid));
 5169:     my %coursehash=&coursedescription($cid);
 5170:     my $crstype = &Apache::loncommon::course_type($cid);
 5171:     my %nothide=();
 5172:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5173:         if ($user !~ /:/) {
 5174: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5175:         } else {
 5176:             $nothide{$user}=1;
 5177:         }
 5178:     }
 5179:     my @possdoms = ($coursehash{'domain'});
 5180:     if ($coursehash{'checkforpriv'}) {
 5181:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5182:     }
 5183:     my %returnhash=();
 5184:     my %dumphash=
 5185:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5186:     my $now=time;
 5187:     my %privileged;
 5188:     foreach my $entry (keys(%dumphash)) {
 5189: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5190:         if (($tstart) && ($tstart<0)) { next; }
 5191:         if (($tend) && ($tend<$now)) { next; }
 5192:         if (($tstart) && ($now<$tstart)) { next; }
 5193:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5194: 	if ($username eq '' || $domain eq '') { next; }
 5195:         if ((&privileged($username,$domain,\@possdoms)) &&
 5196:             (!$nothide{$username.':'.$domain})) { next; }
 5197: 	if ($role eq 'cr') { next; }
 5198:         if ($codes) {
 5199:             if ($section) { $role .= ':'.$section; }
 5200:             if ($returnhash{$role}) {
 5201:                 $returnhash{$role}.=','.$username.':'.$domain;
 5202:             } else {
 5203:                 $returnhash{$role}=$username.':'.$domain;
 5204:             }
 5205:         } else {
 5206:             my $key=&plaintext($role,$crstype);
 5207:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5208:             if ($returnhash{$key}) {
 5209: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5210:             } else {
 5211:                 $returnhash{$key}=$username.':'.$domain;
 5212:             }
 5213:         }
 5214:     }
 5215:     return %returnhash;
 5216: }
 5217: 
 5218: sub get_my_roles {
 5219:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5220:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5221:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5222:     my (%dumphash,%nothide);
 5223:     if ($context eq 'userroles') {
 5224:         %dumphash = &dump('roles',$udom,$uname);
 5225:     } else {
 5226:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5227:         if ($hidepriv) {
 5228:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5229:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5230:                 if ($user !~ /:/) {
 5231:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5232:                 } else {
 5233:                     $nothide{$user} = 1;
 5234:                 }
 5235:             }
 5236:         }
 5237:     }
 5238:     my %returnhash=();
 5239:     my $now=time;
 5240:     my %privileged;
 5241:     foreach my $entry (keys(%dumphash)) {
 5242:         my ($role,$tend,$tstart);
 5243:         if ($context eq 'userroles') {
 5244:             next if ($entry =~ /^rolesdef/);
 5245: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5246:         } else {
 5247:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5248:         }
 5249:         if (($tstart) && ($tstart<0)) { next; }
 5250:         my $status = 'active';
 5251:         if (($tend) && ($tend<=$now)) {
 5252:             $status = 'previous';
 5253:         } 
 5254:         if (($tstart) && ($now<$tstart)) {
 5255:             $status = 'future';
 5256:         }
 5257:         if (ref($types) eq 'ARRAY') {
 5258:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5259:                 next;
 5260:             } 
 5261:         } else {
 5262:             if ($status ne 'active') {
 5263:                 next;
 5264:             }
 5265:         }
 5266:         my ($rolecode,$username,$domain,$section,$area);
 5267:         if ($context eq 'userroles') {
 5268:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5269:             (undef,$domain,$username,$section) = split(/\//,$area);
 5270:         } else {
 5271:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5272:         }
 5273:         if (ref($roledoms) eq 'ARRAY') {
 5274:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5275:                 next;
 5276:             }
 5277:         }
 5278:         if (ref($roles) eq 'ARRAY') {
 5279:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5280:                 if ($role =~ /^cr\//) {
 5281:                     if (!grep(/^cr$/,@{$roles})) {
 5282:                         next;
 5283:                     }
 5284:                 } elsif ($role =~ /^gr\//) {
 5285:                     if (!grep(/^gr$/,@{$roles})) {
 5286:                         next;
 5287:                     }
 5288:                 } else {
 5289:                     next;
 5290:                 }
 5291:             }
 5292:         }
 5293:         if ($hidepriv) {
 5294:             my @privroles = ('dc','su');
 5295:             if ($context eq 'userroles') {
 5296:                 next if (grep(/^\Q$role\E$/,@privroles));
 5297:             } else {
 5298:                 my $possdoms = [$domain];
 5299:                 if (ref($roledoms) eq 'ARRAY') {
 5300:                    push(@{$possdoms},@{$roledoms}); 
 5301:                 }
 5302:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5303:                     if (!$nothide{$username.':'.$domain}) {
 5304:                         next;
 5305:                     }
 5306:                 }
 5307:             }
 5308:         }
 5309:         if ($withsec) {
 5310:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5311:                 $tstart.':'.$tend;
 5312:         } else {
 5313:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5314:         }
 5315:     }
 5316:     return %returnhash;
 5317: }
 5318: 
 5319: sub get_all_adhocroles {
 5320:     my ($dom) = @_;
 5321:     my @roles_by_num = ();
 5322:     my %domdefaults = &get_domain_defaults($dom);
 5323:     my (%description,%access_in_dom,%access_info);
 5324:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5325:         my $count = 0;
 5326:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5327:         my %ordered;
 5328:         foreach my $role (sort(keys(%domcurrent))) {
 5329:             my ($order,$desc,$access_in_dom);
 5330:             if (ref($domcurrent{$role}) eq 'HASH') {
 5331:                 $order = $domcurrent{$role}{'order'};
 5332:                 $desc = $domcurrent{$role}{'desc'};
 5333:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5334:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5335:             }
 5336:             if ($order eq '') {
 5337:                 $order = $count;
 5338:             }
 5339:             $ordered{$order} = $role;
 5340:             if ($desc ne '') {
 5341:                 $description{$role} = $desc;
 5342:             } else {
 5343:                 $description{$role}= $role;
 5344:             }
 5345:             $count++;
 5346:         }
 5347:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5348:             push(@roles_by_num,$ordered{$item});
 5349:         }
 5350:     }
 5351:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5352: }
 5353: 
 5354: sub get_my_adhocroles {
 5355:     my ($cid,$checkreg) = @_;
 5356:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5357:     if ($env{'request.course.id'} eq $cid) {
 5358:         $cdom = $env{'course.'.$cid.'.domain'};
 5359:         $cnum = $env{'course.'.$cid.'.num'};
 5360:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5361:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5362:         $cdom = $1;
 5363:         $cnum = $2;
 5364:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5365:                                      $cdom,$cnum);
 5366:     }
 5367:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5368:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5369:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5370:         if ($rosterhash{$user} ne '') {
 5371:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5372:             return ([],{}) if ($type eq 'auto');
 5373:         }
 5374:     }
 5375:     if (($cdom ne '') && ($cnum ne ''))  {
 5376:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5377:             my $then=$env{'user.login.time'};
 5378:             my $update=$env{'user.update.time'};
 5379:             if (!$update) {
 5380:                 $update = $then;
 5381:             }
 5382:             my @liveroles;
 5383:             foreach my $role ('dh','da') {
 5384:                 if ($env{"user.role.$role./$cdom/"}) {
 5385:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5386:                     my $limit = $update;
 5387:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5388:                         $limit = $then;
 5389:                     }
 5390:                     my $activerole = 1;
 5391:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5392:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5393:                     if ($activerole) {
 5394:                         push(@liveroles,$role);
 5395:                     }
 5396:                 }
 5397:             }
 5398:             if (@liveroles) {
 5399:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5400:                     my ($accessref,$accessinfo,%access_in_dom);
 5401:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5402:                     if (ref($roles_by_num) eq 'ARRAY') {
 5403:                         if (@{$roles_by_num}) {
 5404:                             my %settings;
 5405:                             if ($env{'request.course.id'} eq $cid) {
 5406:                                 foreach my $envkey (keys(%env)) {
 5407:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5408:                                         $settings{$1} = $env{$envkey};
 5409:                                     }
 5410:                                 }
 5411:                             } else {
 5412:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5413:                             }
 5414:                             my %setincrs;
 5415:                             if ($settings{'internal.adhocaccess'}) {
 5416:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5417:                             }
 5418:                             my @statuses;
 5419:                             if ($env{'environment.inststatus'}) {
 5420:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5421:                             }
 5422:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5423:                             if (ref($accessref) eq 'HASH') {
 5424:                                 %access_in_dom = %{$accessref};
 5425:                             }
 5426:                             foreach my $role (@{$roles_by_num}) {
 5427:                                 my ($curraccess,@okstatus,@personnel);
 5428:                                 if ($setincrs{$role}) {
 5429:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5430:                                     if ($curraccess eq 'status') {
 5431:                                         @okstatus = split(/\&/,$rest);
 5432:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5433:                                         @personnel = split(/\&/,$rest);
 5434:                                     }
 5435:                                 } else {
 5436:                                     $curraccess = $access_in_dom{$role};
 5437:                                     if (ref($accessinfo) eq 'HASH') {
 5438:                                         if ($curraccess eq 'status') {
 5439:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5440:                                                 @okstatus = @{$accessinfo->{$role}};
 5441:                                             }
 5442:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5443:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5444:                                                 @personnel = @{$accessinfo->{$role}};
 5445:                                             }
 5446:                                         }
 5447:                                     }
 5448:                                 }
 5449:                                 if ($curraccess eq 'none') {
 5450:                                     next;
 5451:                                 } elsif ($curraccess eq 'all') {
 5452:                                     push(@possroles,$role);
 5453:                                 } elsif ($curraccess eq 'dh') {
 5454:                                     if (grep(/^dh$/,@liveroles)) {
 5455:                                         push(@possroles,$role);
 5456:                                     } else {
 5457:                                         next;
 5458:                                     }
 5459:                                 } elsif ($curraccess eq 'da') {
 5460:                                     if (grep(/^da$/,@liveroles)) {
 5461:                                         push(@possroles,$role);
 5462:                                     } else {
 5463:                                         next;
 5464:                                     }
 5465:                                 } elsif ($curraccess eq 'status') {
 5466:                                     if (@okstatus) {
 5467:                                         if (!@statuses) {
 5468:                                             if (grep(/^default$/,@okstatus)) {
 5469:                                                 push(@possroles,$role);
 5470:                                             }
 5471:                                         } else {
 5472:                                             foreach my $status (@okstatus) {
 5473:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5474:                                                     push(@possroles,$role);
 5475:                                                     last;
 5476:                                                 }
 5477:                                             }
 5478:                                         }
 5479:                                     }
 5480:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5481:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5482:                                         if ($curraccess eq 'exc') {
 5483:                                             push(@possroles,$role);
 5484:                                         }
 5485:                                     } elsif ($curraccess eq 'inc') {
 5486:                                         push(@possroles,$role);
 5487:                                     }
 5488:                                 }
 5489:                             }
 5490:                         }
 5491:                     }
 5492:                 }
 5493:             }
 5494:         }
 5495:     }
 5496:     unless (ref($description) eq 'HASH') {
 5497:         if (ref($roles_by_num) eq 'ARRAY') {
 5498:             my %desc;
 5499:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5500:             $description = \%desc;
 5501:         } else {
 5502:             $description = {};
 5503:         }
 5504:     }
 5505:     return (\@possroles,$description);
 5506: }
 5507: 
 5508: # ----------------------------------------------------- Frontpage Announcements
 5509: #
 5510: #
 5511: 
 5512: sub postannounce {
 5513:     my ($server,$text)=@_;
 5514:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5515:     unless ($text=~/\w/) { $text=''; }
 5516:     return &reply('setannounce:'.&escape($text),$server);
 5517: }
 5518: 
 5519: sub getannounce {
 5520: 
 5521:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5522: 	my $announcement='';
 5523: 	while (my $line = <$fh>) { $announcement .= $line; }
 5524: 	close($fh);
 5525: 	if ($announcement=~/\w/) { 
 5526: 	    return 
 5527:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5528:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5529: 	} else {
 5530: 	    return '';
 5531: 	}
 5532:     } else {
 5533: 	return '';
 5534:     }
 5535: }
 5536: 
 5537: # ---------------------------------------------------------- Course ID routines
 5538: # Deal with domain's nohist_courseid.db files
 5539: #
 5540: 
 5541: sub courseidput {
 5542:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5543:     return unless (ref($storehash) eq 'HASH');
 5544:     my $outcome;
 5545:     if ($caller eq 'timeonly') {
 5546:         my $cids = '';
 5547:         foreach my $item (keys(%$storehash)) {
 5548:             $cids.=&escape($item).'&';
 5549:         }
 5550:         $cids=~s/\&$//;
 5551:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5552:                           $coursehome);       
 5553:     } else {
 5554:         my $items = '';
 5555:         foreach my $item (keys(%$storehash)) {
 5556:             $items.= &escape($item).'='.
 5557:                      &freeze_escape($$storehash{$item}).'&';
 5558:         }
 5559:         $items=~s/\&$//;
 5560:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5561:                           $coursehome);
 5562:     }
 5563:     if ($outcome eq 'unknown_cmd') {
 5564:         my $what;
 5565:         foreach my $cid (keys(%$storehash)) {
 5566:             $what .= &escape($cid).'=';
 5567:             foreach my $item ('description','inst_code','owner','type') {
 5568:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5569:             }
 5570:             $what =~ s/\:$/&/;
 5571:         }
 5572:         $what =~ s/\&$//;  
 5573:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5574:     } else {
 5575:         return $outcome;
 5576:     }
 5577: }
 5578: 
 5579: sub courseiddump {
 5580:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5581:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5582:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5583:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5584:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5585:     my $as_hash = 1;
 5586:     my %returnhash;
 5587:     if (!$domfilter) { $domfilter=''; }
 5588:     my %libserv = &all_library();
 5589:     foreach my $tryserver (keys(%libserv)) {
 5590:         if ( (  $hostidflag == 1 
 5591: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5592: 	     || (!defined($hostidflag)) ) {
 5593: 
 5594: 	    if (($domfilter eq '') ||
 5595: 		(&host_domain($tryserver) eq $domfilter)) {
 5596:                 my $rep;
 5597:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5598:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5599:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5600:                                 &escape($descfilter), &escape($instcodefilter), 
 5601:                                 &escape($ownerfilter), &escape($coursefilter),
 5602:                                 &escape($typefilter), &escape($regexp_ok), 
 5603:                                 $as_hash, &escape($selfenrollonly), 
 5604:                                 &escape($catfilter), $showhidden, $caller, 
 5605:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5606:                                 &escape($createdbefore), &escape($createdafter), 
 5607:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5608:                                 $reqcrsdom,&escape($reqinstcode))));
 5609:                 } else {
 5610:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5611:                              $sincefilter.':'.&escape($descfilter).':'.
 5612:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5613:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5614:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5615:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5616:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5617:                              &escape($cc_clone).':'.$cloneonly.':'.
 5618:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5619:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5620:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5621:                 }
 5622:                      
 5623:                 my @pairs=split(/\&/,$rep);
 5624:                 foreach my $item (@pairs) {
 5625:                     my ($key,$value)=split(/\=/,$item,2);
 5626:                     $key = &unescape($key);
 5627:                     next if ($key =~ /^error: 2 /);
 5628:                     my $result = &thaw_unescape($value);
 5629:                     if (ref($result) eq 'HASH') {
 5630:                         $returnhash{$key}=$result;
 5631:                     } else {
 5632:                         my @responses = split(/:/,$value);
 5633:                         my @items = ('description','inst_code','owner','type');
 5634:                         for (my $i=0; $i<@responses; $i++) {
 5635:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5636:                         }
 5637:                     }
 5638:                 }
 5639:             }
 5640:         }
 5641:     }
 5642:     return %returnhash;
 5643: }
 5644: 
 5645: sub courselastaccess {
 5646:     my ($cdom,$cnum,$hostidref) = @_;
 5647:     my %returnhash;
 5648:     if ($cdom && $cnum) {
 5649:         my $chome = &homeserver($cnum,$cdom);
 5650:         if ($chome ne 'no_host') {
 5651:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5652:             &extract_lastaccess(\%returnhash,$rep);
 5653:         }
 5654:     } else {
 5655:         if (!$cdom) { $cdom=''; }
 5656:         my %libserv = &all_library();
 5657:         foreach my $tryserver (keys(%libserv)) {
 5658:             if (ref($hostidref) eq 'ARRAY') {
 5659:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5660:             } 
 5661:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5662:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5663:                 &extract_lastaccess(\%returnhash,$rep);
 5664:             }
 5665:         }
 5666:     }
 5667:     return %returnhash;
 5668: }
 5669: 
 5670: sub extract_lastaccess {
 5671:     my ($returnhash,$rep) = @_;
 5672:     if (ref($returnhash) eq 'HASH') {
 5673:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5674:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5675:                  $rep eq '') {
 5676:             my @pairs=split(/\&/,$rep);
 5677:             foreach my $item (@pairs) {
 5678:                 my ($key,$value)=split(/\=/,$item,2);
 5679:                 $key = &unescape($key);
 5680:                 next if ($key =~ /^error: 2 /);
 5681:                 $returnhash->{$key} = &thaw_unescape($value);
 5682:             }
 5683:         }
 5684:     }
 5685:     return;
 5686: }
 5687: 
 5688: # ---------------------------------------------------------- DC e-mail
 5689: 
 5690: sub dcmailput {
 5691:     my ($domain,$msgid,$message,$server)=@_;
 5692:     my $status = &Apache::lonnet::critical(
 5693:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5694:        &escape($message),$server);
 5695:     return $status;
 5696: }
 5697: 
 5698: sub dcmaildump {
 5699:     my ($dom,$startdate,$enddate,$senders) = @_;
 5700:     my %returnhash=();
 5701: 
 5702:     if (defined(&domain($dom,'primary'))) {
 5703:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5704:                                                          &escape($enddate).':';
 5705: 	my @esc_senders=map { &escape($_)} @$senders;
 5706: 	$cmd.=&escape(join('&',@esc_senders));
 5707: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5708:             my ($key,$value) = split(/\=/,$line,2);
 5709:             if (($key) && ($value)) {
 5710:                 $returnhash{&unescape($key)} = &unescape($value);
 5711:             }
 5712:         }
 5713:     }
 5714:     return %returnhash;
 5715: }
 5716: # ---------------------------------------------------------- Domain roles
 5717: 
 5718: sub get_domain_roles {
 5719:     my ($dom,$roles,$startdate,$enddate)=@_;
 5720:     if ((!defined($startdate)) || ($startdate eq '')) {
 5721:         $startdate = '.';
 5722:     }
 5723:     if ((!defined($enddate)) || ($enddate eq '')) {
 5724:         $enddate = '.';
 5725:     }
 5726:     my $rolelist;
 5727:     if (ref($roles) eq 'ARRAY') {
 5728:         $rolelist = join('&',@{$roles});
 5729:     }
 5730:     my %personnel = ();
 5731: 
 5732:     my %servers = &get_servers($dom,'library');
 5733:     foreach my $tryserver (keys(%servers)) {
 5734: 	%{$personnel{$tryserver}}=();
 5735: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5736: 					    &escape($startdate).':'.
 5737: 					    &escape($enddate).':'.
 5738: 					    &escape($rolelist), $tryserver))) {
 5739: 	    my ($key,$value) = split(/\=/,$line,2);
 5740: 	    if (($key) && ($value)) {
 5741: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5742: 	    }
 5743: 	}
 5744:     }
 5745:     return %personnel;
 5746: }
 5747: 
 5748: sub get_active_domroles {
 5749:     my ($dom,$roles) = @_;
 5750:     return () unless (ref($roles) eq 'ARRAY');
 5751:     my $now = time;
 5752:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5753:     my %domroles;
 5754:     foreach my $server (keys(%dompersonnel)) {
 5755:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5756:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5757:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5758:         }
 5759:     }
 5760:     return %domroles;
 5761: }
 5762: 
 5763: # ----------------------------------------------------------- Interval timing 
 5764: 
 5765: {
 5766: # Caches needed for speedup of navmaps
 5767: # We don't want to cache this for very long at all (5 seconds at most)
 5768: # 
 5769: # The user for whom we cache
 5770: my $cachedkey='';
 5771: # The cached times for this user
 5772: my %cachedtimes=();
 5773: # When this was last done
 5774: my $cachedtime='';
 5775: 
 5776: sub load_all_first_access {
 5777:     my ($uname,$udom,$ignorecache)=@_;
 5778:     if (($cachedkey eq $uname.':'.$udom) &&
 5779:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5780:         (!$ignorecache)) {
 5781:         return;
 5782:     }
 5783:     $cachedtime=time;
 5784:     $cachedkey=$uname.':'.$udom;
 5785:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5786: }
 5787: 
 5788: sub get_first_access {
 5789:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5790:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5791:     if ($argsymb) { $symb=$argsymb; }
 5792:     my ($map,$id,$res)=&decode_symb($symb);
 5793:     if ($argmap) { $map = $argmap; }
 5794:     if ($type eq 'course') {
 5795: 	$res='course';
 5796:     } elsif ($type eq 'map') {
 5797: 	$res=&symbread($map);
 5798:     } else {
 5799: 	$res=$symb;
 5800:     }
 5801:     &load_all_first_access($uname,$udom,$ignorecache);
 5802:     return $cachedtimes{"$courseid\0$res"};
 5803: }
 5804: 
 5805: sub set_first_access {
 5806:     my ($type,$interval)=@_;
 5807:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5808:     my ($map,$id,$res)=&decode_symb($symb);
 5809:     if ($type eq 'course') {
 5810: 	$res='course';
 5811:     } elsif ($type eq 'map') {
 5812: 	$res=&symbread($map);
 5813:     } else {
 5814: 	$res=$symb;
 5815:     }
 5816:     $cachedkey='';
 5817:     my $firstaccess=&get_first_access($type,$symb,$map);
 5818:     if ($firstaccess) {
 5819:         &logthis("First access time already set ($firstaccess) when attempting ".
 5820:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5821:                  "in $courseid");
 5822:         return 'already_set';
 5823:     } else {
 5824:         my $start = time;
 5825: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5826:                           $udom,$uname);
 5827:         if ($putres eq 'ok') {
 5828:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5829:                  $udom,$uname); 
 5830:             &appenv(
 5831:                      {
 5832:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5833:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5834:                      }
 5835:                   );
 5836:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5837:                 $cachedtimes{"$courseid\0$res"} = $start;
 5838:             }
 5839:         } elsif ($putres ne 'refused') {
 5840:             &logthis("Result: $putres when attempting to set first access time ".
 5841:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5842:         }
 5843:         return $putres;
 5844:     }
 5845:     return 'already_set';
 5846: }
 5847: }
 5848: 
 5849: # --------------------------------------------- Set Expire Date for Spreadsheet
 5850: 
 5851: sub expirespread {
 5852:     my ($uname,$udom,$stype,$usymb)=@_;
 5853:     my $cid=$env{'request.course.id'}; 
 5854:     if ($cid) {
 5855:        my $now=time;
 5856:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5857:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5858:                             $env{'course.'.$cid.'.num'}.
 5859: 	        	    ':nohist_expirationdates:'.
 5860:                             &escape($key).'='.$now,
 5861:                             $env{'course.'.$cid.'.home'})
 5862:     }
 5863:     return 'ok';
 5864: }
 5865: 
 5866: # ----------------------------------------------------- Devalidate Spreadsheets
 5867: 
 5868: sub devalidate {
 5869:     my ($symb,$uname,$udom)=@_;
 5870:     my $cid=$env{'request.course.id'}; 
 5871:     if ($cid) {
 5872:         # delete the stored spreadsheets for
 5873:         # - the student level sheet of this user in course's homespace
 5874:         # - the assessment level sheet for this resource 
 5875:         #   for this user in user's homespace
 5876: 	# - current conditional state info
 5877: 	my $key=$uname.':'.$udom.':';
 5878:         my $status=
 5879: 	    &del('nohist_calculatedsheets',
 5880: 		 [$key.'studentcalc:'],
 5881: 		 $env{'course.'.$cid.'.domain'},
 5882: 		 $env{'course.'.$cid.'.num'})
 5883: 		.' '.
 5884: 	    &del('nohist_calculatedsheets_'.$cid,
 5885: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5886:         unless ($status eq 'ok ok') {
 5887:            &logthis('Could not devalidate spreadsheet '.
 5888:                     $uname.' at '.$udom.' for '.
 5889: 		    $symb.': '.$status);
 5890:         }
 5891: 	&delenv('user.state.'.$cid);
 5892:     }
 5893: }
 5894: 
 5895: sub get_scalar {
 5896:     my ($string,$end) = @_;
 5897:     my $value;
 5898:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5899: 	$value = $1;
 5900:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5901: 	$value = $1;
 5902:     }
 5903:     return &unescape($value);
 5904: }
 5905: 
 5906: sub array2str {
 5907:   my (@array) = @_;
 5908:   my $result=&arrayref2str(\@array);
 5909:   $result=~s/^__ARRAY_REF__//;
 5910:   $result=~s/__END_ARRAY_REF__$//;
 5911:   return $result;
 5912: }
 5913: 
 5914: sub arrayref2str {
 5915:   my ($arrayref) = @_;
 5916:   my $result='__ARRAY_REF__';
 5917:   foreach my $elem (@$arrayref) {
 5918:     if(ref($elem) eq 'ARRAY') {
 5919:       $result.=&arrayref2str($elem).'&';
 5920:     } elsif(ref($elem) eq 'HASH') {
 5921:       $result.=&hashref2str($elem).'&';
 5922:     } elsif(ref($elem)) {
 5923:       #print("Got a ref of ".(ref($elem))." skipping.");
 5924:     } else {
 5925:       $result.=&escape($elem).'&';
 5926:     }
 5927:   }
 5928:   $result=~s/\&$//;
 5929:   $result .= '__END_ARRAY_REF__';
 5930:   return $result;
 5931: }
 5932: 
 5933: sub hash2str {
 5934:   my (%hash) = @_;
 5935:   my $result=&hashref2str(\%hash);
 5936:   $result=~s/^__HASH_REF__//;
 5937:   $result=~s/__END_HASH_REF__$//;
 5938:   return $result;
 5939: }
 5940: 
 5941: sub hashref2str {
 5942:   my ($hashref)=@_;
 5943:   my $result='__HASH_REF__';
 5944:   foreach my $key (sort(keys(%$hashref))) {
 5945:     if (ref($key) eq 'ARRAY') {
 5946:       $result.=&arrayref2str($key).'=';
 5947:     } elsif (ref($key) eq 'HASH') {
 5948:       $result.=&hashref2str($key).'=';
 5949:     } elsif (ref($key)) {
 5950:       $result.='=';
 5951:       #print("Got a ref of ".(ref($key))." skipping.");
 5952:     } else {
 5953: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5954:     }
 5955: 
 5956:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5957:       $result.=&arrayref2str($hashref->{$key}).'&';
 5958:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5959:       $result.=&hashref2str($hashref->{$key}).'&';
 5960:     } elsif(ref($hashref->{$key})) {
 5961:        $result.='&';
 5962:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5963:     } else {
 5964:       $result.=&escape($hashref->{$key}).'&';
 5965:     }
 5966:   }
 5967:   $result=~s/\&$//;
 5968:   $result .= '__END_HASH_REF__';
 5969:   return $result;
 5970: }
 5971: 
 5972: sub str2hash {
 5973:     my ($string)=@_;
 5974:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5975:     return %$hash;
 5976: }
 5977: 
 5978: sub str2hashref {
 5979:   my ($string) = @_;
 5980: 
 5981:   my %hash;
 5982: 
 5983:   if($string !~ /^__HASH_REF__/) {
 5984:       if (! ($string eq '' || !defined($string))) {
 5985: 	  $hash{'error'}='Not hash reference';
 5986:       }
 5987:       return (\%hash, $string);
 5988:   }
 5989: 
 5990:   $string =~ s/^__HASH_REF__//;
 5991: 
 5992:   while($string !~ /^__END_HASH_REF__/) {
 5993:       #key
 5994:       my $key='';
 5995:       if($string =~ /^__HASH_REF__/) {
 5996:           ($key, $string)=&str2hashref($string);
 5997:           if(defined($key->{'error'})) {
 5998:               $hash{'error'}='Bad data';
 5999:               return (\%hash, $string);
 6000:           }
 6001:       } elsif($string =~ /^__ARRAY_REF__/) {
 6002:           ($key, $string)=&str2arrayref($string);
 6003:           if($key->[0] eq 'Array reference error') {
 6004:               $hash{'error'}='Bad data';
 6005:               return (\%hash, $string);
 6006:           }
 6007:       } else {
 6008:           $string =~ s/^(.*?)=//;
 6009: 	  $key=&unescape($1);
 6010:       }
 6011:       $string =~ s/^=//;
 6012: 
 6013:       #value
 6014:       my $value='';
 6015:       if($string =~ /^__HASH_REF__/) {
 6016:           ($value, $string)=&str2hashref($string);
 6017:           if(defined($value->{'error'})) {
 6018:               $hash{'error'}='Bad data';
 6019:               return (\%hash, $string);
 6020:           }
 6021:       } elsif($string =~ /^__ARRAY_REF__/) {
 6022:           ($value, $string)=&str2arrayref($string);
 6023:           if($value->[0] eq 'Array reference error') {
 6024:               $hash{'error'}='Bad data';
 6025:               return (\%hash, $string);
 6026:           }
 6027:       } else {
 6028: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6029:       }
 6030:       $string =~ s/^&//;
 6031: 
 6032:       $hash{$key}=$value;
 6033:   }
 6034: 
 6035:   $string =~ s/^__END_HASH_REF__//;
 6036: 
 6037:   return (\%hash, $string);
 6038: }
 6039: 
 6040: sub str2array {
 6041:     my ($string)=@_;
 6042:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6043:     return @$array;
 6044: }
 6045: 
 6046: sub str2arrayref {
 6047:   my ($string) = @_;
 6048:   my @array;
 6049: 
 6050:   if($string !~ /^__ARRAY_REF__/) {
 6051:       if (! ($string eq '' || !defined($string))) {
 6052: 	  $array[0]='Array reference error';
 6053:       }
 6054:       return (\@array, $string);
 6055:   }
 6056: 
 6057:   $string =~ s/^__ARRAY_REF__//;
 6058: 
 6059:   while($string !~ /^__END_ARRAY_REF__/) {
 6060:       my $value='';
 6061:       if($string =~ /^__HASH_REF__/) {
 6062:           ($value, $string)=&str2hashref($string);
 6063:           if(defined($value->{'error'})) {
 6064:               $array[0] ='Array reference error';
 6065:               return (\@array, $string);
 6066:           }
 6067:       } elsif($string =~ /^__ARRAY_REF__/) {
 6068:           ($value, $string)=&str2arrayref($string);
 6069:           if($value->[0] eq 'Array reference error') {
 6070:               $array[0] ='Array reference error';
 6071:               return (\@array, $string);
 6072:           }
 6073:       } else {
 6074: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6075:       }
 6076:       $string =~ s/^&//;
 6077: 
 6078:       push(@array, $value);
 6079:   }
 6080: 
 6081:   $string =~ s/^__END_ARRAY_REF__//;
 6082: 
 6083:   return (\@array, $string);
 6084: }
 6085: 
 6086: # -------------------------------------------------------------------Temp Store
 6087: 
 6088: sub tmpreset {
 6089:   my ($symb,$namespace,$domain,$stuname) = @_;
 6090:   if (!$symb) {
 6091:     $symb=&symbread();
 6092:     if (!$symb) { $symb= $env{'request.url'}; }
 6093:   }
 6094:   $symb=escape($symb);
 6095: 
 6096:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6097:   $namespace=~s/\//\_/g;
 6098:   $namespace=~s/\W//g;
 6099: 
 6100:   if (!$domain) { $domain=$env{'user.domain'}; }
 6101:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6102:   if ($domain eq 'public' && $stuname eq 'public') {
 6103:       $stuname=$ENV{'REMOTE_ADDR'};
 6104:   }
 6105:   my $path=LONCAPA::tempdir();
 6106:   my %hash;
 6107:   if (tie(%hash,'GDBM_File',
 6108: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6109: 	  &GDBM_WRCREAT(),0640)) {
 6110:     foreach my $key (keys(%hash)) {
 6111:       if ($key=~ /:$symb/) {
 6112: 	delete($hash{$key});
 6113:       }
 6114:     }
 6115:   }
 6116: }
 6117: 
 6118: sub tmpstore {
 6119:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6120: 
 6121:   if (!$symb) {
 6122:     $symb=&symbread();
 6123:     if (!$symb) { $symb= $env{'request.url'}; }
 6124:   }
 6125:   $symb=escape($symb);
 6126: 
 6127:   if (!$namespace) {
 6128:     # I don't think we would ever want to store this for a course.
 6129:     # it seems this will only be used if we don't have a course.
 6130:     #$namespace=$env{'request.course.id'};
 6131:     #if (!$namespace) {
 6132:       $namespace=$env{'request.state'};
 6133:     #}
 6134:   }
 6135:   $namespace=~s/\//\_/g;
 6136:   $namespace=~s/\W//g;
 6137:   if (!$domain) { $domain=$env{'user.domain'}; }
 6138:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6139:   if ($domain eq 'public' && $stuname eq 'public') {
 6140:       $stuname=$ENV{'REMOTE_ADDR'};
 6141:   }
 6142:   my $now=time;
 6143:   my %hash;
 6144:   my $path=LONCAPA::tempdir();
 6145:   if (tie(%hash,'GDBM_File',
 6146: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6147: 	  &GDBM_WRCREAT(),0640)) {
 6148:     $hash{"version:$symb"}++;
 6149:     my $version=$hash{"version:$symb"};
 6150:     my $allkeys=''; 
 6151:     foreach my $key (keys(%$storehash)) {
 6152:       $allkeys.=$key.':';
 6153:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6154:     }
 6155:     $hash{"$version:$symb:timestamp"}=$now;
 6156:     $allkeys.='timestamp';
 6157:     $hash{"$version:keys:$symb"}=$allkeys;
 6158:     if (untie(%hash)) {
 6159:       return 'ok';
 6160:     } else {
 6161:       return "error:$!";
 6162:     }
 6163:   } else {
 6164:     return "error:$!";
 6165:   }
 6166: }
 6167: 
 6168: # -----------------------------------------------------------------Temp Restore
 6169: 
 6170: sub tmprestore {
 6171:   my ($symb,$namespace,$domain,$stuname) = @_;
 6172: 
 6173:   if (!$symb) {
 6174:     $symb=&symbread();
 6175:     if (!$symb) { $symb= $env{'request.url'}; }
 6176:   }
 6177:   $symb=escape($symb);
 6178: 
 6179:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6180: 
 6181:   if (!$domain) { $domain=$env{'user.domain'}; }
 6182:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6183:   if ($domain eq 'public' && $stuname eq 'public') {
 6184:       $stuname=$ENV{'REMOTE_ADDR'};
 6185:   }
 6186:   my %returnhash;
 6187:   $namespace=~s/\//\_/g;
 6188:   $namespace=~s/\W//g;
 6189:   my %hash;
 6190:   my $path=LONCAPA::tempdir();
 6191:   if (tie(%hash,'GDBM_File',
 6192: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6193: 	  &GDBM_READER(),0640)) {
 6194:     my $version=$hash{"version:$symb"};
 6195:     $returnhash{'version'}=$version;
 6196:     my $scope;
 6197:     for ($scope=1;$scope<=$version;$scope++) {
 6198:       my $vkeys=$hash{"$scope:keys:$symb"};
 6199:       my @keys=split(/:/,$vkeys);
 6200:       my $key;
 6201:       $returnhash{"$scope:keys"}=$vkeys;
 6202:       foreach $key (@keys) {
 6203: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6204: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6205:       }
 6206:     }
 6207:     if (!(untie(%hash))) {
 6208:       return "error:$!";
 6209:     }
 6210:   } else {
 6211:     return "error:$!";
 6212:   }
 6213:   return %returnhash;
 6214: }
 6215: 
 6216: # ----------------------------------------------------------------------- Store
 6217: 
 6218: sub store {
 6219:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6220:     my $home='';
 6221: 
 6222:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6223: 
 6224:     $symb=&symbclean($symb);
 6225:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6226: 
 6227:     if (!$domain) { $domain=$env{'user.domain'}; }
 6228:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6229: 
 6230:     &devalidate($symb,$stuname,$domain);
 6231: 
 6232:     $symb=escape($symb);
 6233:     if (!$namespace) { 
 6234:        unless ($namespace=$env{'request.course.id'}) { 
 6235:           return ''; 
 6236:        } 
 6237:     }
 6238:     if (!$home) { $home=$env{'user.home'}; }
 6239: 
 6240:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6241:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6242: 
 6243:     my $namevalue='';
 6244:     foreach my $key (keys(%$storehash)) {
 6245:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6246:     }
 6247:     $namevalue=~s/\&$//;
 6248:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6249:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6250: }
 6251: 
 6252: # -------------------------------------------------------------- Critical Store
 6253: 
 6254: sub cstore {
 6255:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6256:     my $home='';
 6257: 
 6258:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6259: 
 6260:     $symb=&symbclean($symb);
 6261:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6262: 
 6263:     if (!$domain) { $domain=$env{'user.domain'}; }
 6264:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6265: 
 6266:     &devalidate($symb,$stuname,$domain);
 6267: 
 6268:     $symb=escape($symb);
 6269:     if (!$namespace) { 
 6270:        unless ($namespace=$env{'request.course.id'}) { 
 6271:           return ''; 
 6272:        } 
 6273:     }
 6274:     if (!$home) { $home=$env{'user.home'}; }
 6275: 
 6276:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6277:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6278: 
 6279:     my $namevalue='';
 6280:     foreach my $key (keys(%$storehash)) {
 6281:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6282:     }
 6283:     $namevalue=~s/\&$//;
 6284:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6285:     return critical
 6286:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6287: }
 6288: 
 6289: # --------------------------------------------------------------------- Restore
 6290: 
 6291: sub restore {
 6292:     my ($symb,$namespace,$domain,$stuname) = @_;
 6293:     my $home='';
 6294: 
 6295:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6296: 
 6297:     if (!$symb) {
 6298:         return if ($namespace eq 'courserequests');
 6299:         unless ($symb=escape(&symbread())) { return ''; }
 6300:     } else {
 6301:         unless ($namespace eq 'courserequests') {
 6302:             $symb=&escape(&symbclean($symb));
 6303:         }
 6304:     }
 6305:     if (!$namespace) { 
 6306:        unless ($namespace=$env{'request.course.id'}) { 
 6307:           return ''; 
 6308:        } 
 6309:     }
 6310:     if (!$domain) { $domain=$env{'user.domain'}; }
 6311:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6312:     if (!$home) { $home=$env{'user.home'}; }
 6313:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6314: 
 6315:     my %returnhash=();
 6316:     foreach my $line (split(/\&/,$answer)) {
 6317: 	my ($name,$value)=split(/\=/,$line);
 6318:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6319:     }
 6320:     my $version;
 6321:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6322:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6323:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6324:        }
 6325:     }
 6326:     return %returnhash;
 6327: }
 6328: 
 6329: # ---------------------------------------------------------- Course Description
 6330: #
 6331: #  
 6332: 
 6333: sub coursedescription {
 6334:     my ($courseid,$args)=@_;
 6335:     $courseid=~s/^\///;
 6336:     $courseid=~s/\_/\//g;
 6337:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6338:     my $chome=&homeserver($cnum,$cdomain);
 6339:     my $normalid=$cdomain.'_'.$cnum;
 6340:     # need to always cache even if we get errors otherwise we keep 
 6341:     # trying and trying and trying to get the course description.
 6342:     my %envhash=();
 6343:     my %returnhash=();
 6344:     
 6345:     my $expiretime=600;
 6346:     if ($env{'request.course.id'} eq $normalid) {
 6347: 	$expiretime=120;
 6348:     }
 6349: 
 6350:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6351:     if (!$args->{'freshen_cache'}
 6352: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6353: 	foreach my $key (keys(%env)) {
 6354: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6355: 	    my ($setting) = $1;
 6356: 	    $returnhash{$setting} = $env{$key};
 6357: 	}
 6358: 	return %returnhash;
 6359:     }
 6360: 
 6361:     # get the data again
 6362: 
 6363:     if (!$args->{'one_time'}) {
 6364: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6365:     }
 6366: 
 6367:     if ($chome ne 'no_host') {
 6368:        %returnhash=&dump('environment',$cdomain,$cnum);
 6369:        if (!exists($returnhash{'con_lost'})) {
 6370: 	   my $username = $env{'user.name'}; # Defult username
 6371: 	   if(defined $args->{'user'}) {
 6372: 	       $username = $args->{'user'};
 6373: 	   }
 6374:            $returnhash{'home'}= $chome;
 6375: 	   $returnhash{'domain'} = $cdomain;
 6376: 	   $returnhash{'num'} = $cnum;
 6377:            if (!defined($returnhash{'type'})) {
 6378:                $returnhash{'type'} = 'Course';
 6379:            }
 6380:            while (my ($name,$value) = each %returnhash) {
 6381:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6382:            }
 6383:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6384:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6385: 	       $username.'_'.$cdomain.'_'.$cnum;
 6386:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6387:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6388:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6389:        }
 6390:     }
 6391:     if (!$args->{'one_time'}) {
 6392: 	&appenv(\%envhash);
 6393:     }
 6394:     return %returnhash;
 6395: }
 6396: 
 6397: sub update_released_required {
 6398:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6399:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6400:         $cid = $env{'request.course.id'};
 6401:         $cdom = $env{'course.'.$cid.'.domain'};
 6402:         $cnum = $env{'course.'.$cid.'.num'};
 6403:         $chome = $env{'course.'.$cid.'.home'};
 6404:     }
 6405:     if ($needsrelease) {
 6406:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6407:         my $needsupdate;
 6408:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6409:             $needsupdate = 1;
 6410:         } else {
 6411:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6412:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6413:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6414:                 $needsupdate = 1;
 6415:             }
 6416:         }
 6417:         if ($needsupdate) {
 6418:             my %needshash = (
 6419:                              'internal.releaserequired' => $needsrelease,
 6420:                             );
 6421:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6422:             if ($putresult eq 'ok') {
 6423:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6424:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6425:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6426:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6427:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6428:                 }
 6429:             }
 6430:         }
 6431:     }
 6432:     return;
 6433: }
 6434: 
 6435: # -------------------------------------------------See if a user is privileged
 6436: 
 6437: sub privileged {
 6438:     my ($username,$domain,$possdomains,$possroles)=@_;
 6439:     my $now = time;
 6440:     my $roles;
 6441:     if (ref($possroles) eq 'ARRAY') {
 6442:         $roles = $possroles; 
 6443:     } else {
 6444:         $roles = ['dc','su'];
 6445:     }
 6446:     if (ref($possdomains) eq 'ARRAY') {
 6447:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6448:         foreach my $dom (@{$possdomains}) {
 6449:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6450:                 (ref($privileged{$dom}) eq 'HASH')) {
 6451:                 foreach my $role (@{$roles}) {
 6452:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6453:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6454:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6455:                             return 1 unless (($end && $end < $now) ||
 6456:                                              ($start && $start > $now));
 6457:                         }
 6458:                     }
 6459:                 }
 6460:             }
 6461:         }
 6462:     } else {
 6463:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6464:         my $now = time;
 6465: 
 6466:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6467:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6468:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6469:                 return 1 unless ($tend && $tend < $now) 
 6470:                         or ($tstart && $tstart > $now);
 6471:             }
 6472:         }
 6473:     }
 6474:     return 0;
 6475: }
 6476: 
 6477: sub privileged_by_domain {
 6478:     my ($domains,$roles) = @_;
 6479:     my %privileged = ();
 6480:     my $cachetime = 60*60*24;
 6481:     my $now = time;
 6482:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6483:         return %privileged;
 6484:     }
 6485:     foreach my $dom (@{$domains}) {
 6486:         next if (ref($privileged{$dom}) eq 'HASH');
 6487:         my $needroles;
 6488:         foreach my $role (@{$roles}) {
 6489:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6490:             if (defined($cached)) {
 6491:                 if (ref($result) eq 'HASH') {
 6492:                     $privileged{$dom}{$role} = $result;
 6493:                 }
 6494:             } else {
 6495:                 $needroles = 1;
 6496:             }
 6497:         }
 6498:         if ($needroles) {
 6499:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6500:             $privileged{$dom} = {};
 6501:             foreach my $server (keys(%dompersonnel)) {
 6502:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6503:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6504:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6505:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6506:                         next if ($end && $end < $now);
 6507:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6508:                             $dompersonnel{$server}{$item};
 6509:                     }
 6510:                 }
 6511:             }
 6512:             if (ref($privileged{$dom}) eq 'HASH') {
 6513:                 foreach my $role (@{$roles}) {
 6514:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6515:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6516:                     } else {
 6517:                         my %hash = ();
 6518:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6519:                     }
 6520:                 }
 6521:             }
 6522:         }
 6523:     }
 6524:     return %privileged;
 6525: }
 6526: 
 6527: # -------------------------------------------------------- Get user privileges
 6528: 
 6529: sub rolesinit {
 6530:     my ($domain, $username) = @_;
 6531:     my %userroles = ('user.login.time' => time);
 6532:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6533: 
 6534:     # firstaccess and timerinterval are related to timed maps/resources. 
 6535:     # also, blocking can be triggered by an activating timer
 6536:     # it's saved in the user's %env.
 6537:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6538:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6539:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6540:         %timerintchk, %timerintenv);
 6541: 
 6542:     foreach my $key (keys(%firstaccess)) {
 6543:         my ($cid, $rest) = split(/\0/, $key);
 6544:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6545:     }
 6546: 
 6547:     foreach my $key (keys(%timerinterval)) {
 6548:         my ($cid,$rest) = split(/\0/,$key);
 6549:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6550:     }
 6551: 
 6552:     my %allroles=();
 6553:     my %allgroups=();
 6554: 
 6555:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6556:         my $role = $rolesdump{$area};
 6557:         $area =~ s/\_\w\w$//;
 6558: 
 6559:         my ($trole, $tend, $tstart, $group_privs);
 6560: 
 6561:         if ($role =~ /^cr/) {
 6562:         # Custom role, defined by a user 
 6563:         # e.g., user.role.cr/msu/smith/mynewrole
 6564:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6565:                 $trole = $1;
 6566:                 ($tend, $tstart) = split('_', $2);
 6567:             } else {
 6568:                 $trole = $role;
 6569:             }
 6570:         } elsif ($role =~ m|^gr/|) {
 6571:         # Role of member in a group, defined within a course/community
 6572:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6573:             ($trole, $tend, $tstart) = split(/_/, $role);
 6574:             next if $tstart eq '-1';
 6575:             ($trole, $group_privs) = split(/\//, $trole);
 6576:             $group_privs = &unescape($group_privs);
 6577:         } else {
 6578:         # Just a normal role, defined in roles.tab
 6579:             ($trole, $tend, $tstart) = split(/_/,$role);
 6580:         }
 6581: 
 6582:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6583:                  $username);
 6584:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6585: 
 6586:         # role expired or not available yet?
 6587:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6588:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6589: 
 6590:         next if $area eq '' or $trole eq '';
 6591: 
 6592:         my $spec = "$trole.$area";
 6593:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6594: 
 6595:         if ($trole =~ /^cr\//) {
 6596:         # Custom role, defined by a user
 6597:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6598:         } elsif ($trole eq 'gr') {
 6599:         # Role of a member in a group, defined within a course/community
 6600:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6601:             next;
 6602:         } else {
 6603:         # Normal role, defined in roles.tab
 6604:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6605:         }
 6606: 
 6607:         my $cid = $tdomain.'_'.$trest;
 6608:         unless ($firstaccchk{$cid}) {
 6609:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6610:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6611:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6612:                         $coursetimerstarts{$cid}{$item}; 
 6613:                 }
 6614:             }
 6615:             $firstaccchk{$cid} = 1;
 6616:         }
 6617:         unless ($timerintchk{$cid}) {
 6618:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6619:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6620:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6621:                        $coursetimerintervals{$cid}{$item};
 6622:                 }
 6623:             }
 6624:             $timerintchk{$cid} = 1;
 6625:         }
 6626:     }
 6627: 
 6628:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6629:                                                           \%allroles, \%allgroups);
 6630:     $env{'user.adv'} = $userroles{'user.adv'};
 6631:     $env{'user.rar'} = $userroles{'user.rar'};
 6632: 
 6633:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6634: }
 6635: 
 6636: sub set_arearole {
 6637:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6638:     unless ($nolog) {
 6639: # log the associated role with the area
 6640:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6641:     }
 6642:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6643: }
 6644: 
 6645: sub custom_roleprivs {
 6646:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6647:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6648:     my $homsvr = &homeserver($rauthor,$rdomain);
 6649:     if (&hostname($homsvr) ne '') {
 6650:         my ($rdummy,$roledef)=
 6651:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6652:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6653:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6654:             if (defined($syspriv)) {
 6655:                 if ($trest =~ /^$match_community$/) {
 6656:                     $syspriv =~ s/bre\&S//; 
 6657:                 }
 6658:                 $$allroles{'cm./'}.=':'.$syspriv;
 6659:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6660:             }
 6661:             if ($tdomain ne '') {
 6662:                 if (defined($dompriv)) {
 6663:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6664:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6665:                 }
 6666:                 if (($trest ne '') && (defined($coursepriv))) {
 6667:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6668:                         my $rolename = $1;
 6669:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6670:                     }
 6671:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6672:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6673:                 }
 6674:             }
 6675:         }
 6676:     }
 6677: }
 6678: 
 6679: sub course_adhocrole_privs {
 6680:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6681:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6682:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6683:         my (%currprivs,%storeprivs);
 6684:         foreach my $item (split(/:/,$coursepriv)) {
 6685:             my ($priv,$restrict) = split(/\&/,$item);
 6686:             $currprivs{$priv} = $restrict;
 6687:         }
 6688:         my (%possadd,%possremove,%full);
 6689:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6690:             my ($priv,$restrict)=split(/\&/,$item);
 6691:             $full{$priv} = $restrict;
 6692:         }
 6693:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6694:              next if ($item eq '');
 6695:              my ($rule,$rest) = split(/=/,$item);
 6696:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6697:              foreach my $priv (split(/:/,$rest)) {
 6698:                  if ($priv ne '') {
 6699:                      if ($rule eq 'off') {
 6700:                          $possremove{$priv} = 1;
 6701:                      } else {
 6702:                          $possadd{$priv} = 1;
 6703:                      }
 6704:                  }
 6705:              }
 6706:          }
 6707:          foreach my $priv (sort(keys(%full))) {
 6708:              if (exists($currprivs{$priv})) {
 6709:                  unless (exists($possremove{$priv})) {
 6710:                      $storeprivs{$priv} = $currprivs{$priv};
 6711:                  }
 6712:              } elsif (exists($possadd{$priv})) {
 6713:                  $storeprivs{$priv} = $full{$priv};
 6714:              }
 6715:          }
 6716:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6717:      }
 6718:      return $coursepriv;
 6719: }
 6720: 
 6721: sub group_roleprivs {
 6722:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6723:     my $access = 1;
 6724:     my $now = time;
 6725:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6726:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6727:     if ($access) {
 6728:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6729:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6730:     }
 6731: }
 6732: 
 6733: sub standard_roleprivs {
 6734:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6735:     if (defined($pr{$trole.':s'})) {
 6736:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6737:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6738:     }
 6739:     if ($tdomain ne '') {
 6740:         if (defined($pr{$trole.':d'})) {
 6741:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6742:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6743:         }
 6744:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6745:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6746:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6747:         }
 6748:     }
 6749: }
 6750: 
 6751: sub set_userprivs {
 6752:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6753:     my $author=0;
 6754:     my $adv=0;
 6755:     my $rar=0;
 6756:     my %grouproles = ();
 6757:     if (keys(%{$allgroups}) > 0) {
 6758:         my @groupkeys; 
 6759:         foreach my $role (keys(%{$allroles})) {
 6760:             push(@groupkeys,$role);
 6761:         }
 6762:         if (ref($groups_roles) eq 'HASH') {
 6763:             foreach my $key (keys(%{$groups_roles})) {
 6764:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6765:                     push(@groupkeys,$key);
 6766:                 }
 6767:             }
 6768:         }
 6769:         if (@groupkeys > 0) {
 6770:             foreach my $role (@groupkeys) {
 6771:                 my ($trole,$area,$sec,$extendedarea);
 6772:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6773:                     $trole = $1;
 6774:                     $area = $2;
 6775:                     $sec = $3;
 6776:                     $extendedarea = $area.$sec;
 6777:                     if (exists($$allgroups{$area})) {
 6778:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6779:                             my $spec = $trole.'.'.$extendedarea;
 6780:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6781:                                                 $$allgroups{$area}{$group};
 6782:                         }
 6783:                     }
 6784:                 }
 6785:             }
 6786:         }
 6787:     }
 6788:     foreach my $group (keys(%grouproles)) {
 6789:         $$allroles{$group} = $grouproles{$group};
 6790:     }
 6791:     foreach my $role (keys(%{$allroles})) {
 6792:         my %thesepriv;
 6793:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6794:         foreach my $item (split(/:/,$$allroles{$role})) {
 6795:             if ($item ne '') {
 6796:                 my ($privilege,$restrictions)=split(/&/,$item);
 6797:                 if ($restrictions eq '') {
 6798:                     $thesepriv{$privilege}='F';
 6799:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6800:                     $thesepriv{$privilege}.=$restrictions;
 6801:                 }
 6802:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6803:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6804:             }
 6805:         }
 6806:         my $thesestr='';
 6807:         foreach my $priv (sort(keys(%thesepriv))) {
 6808: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6809: 	}
 6810:         $userroles->{'user.priv.'.$role} = $thesestr;
 6811:     }
 6812:     return ($author,$adv,$rar);
 6813: }
 6814: 
 6815: sub role_status {
 6816:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6817:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6818:         my ($one,$two) = split(m{\./},$rolekey,2);
 6819:         (undef,undef,$$role) = split(/\./,$one,3);
 6820:         unless (!defined($$role) || $$role eq '') {
 6821:             $$where = '/'.$two;
 6822:             $$trolecode=$$role.'.'.$$where;
 6823:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6824:             $$tstatus='is';
 6825:             if ($$tstart && $$tstart>$update) {
 6826:                 $$tstatus='future';
 6827:                 if ($$tstart<$now) {
 6828:                     if ($$tstart && $$tstart>$refresh) {
 6829:                         if (($$where ne '') && ($$role ne '')) {
 6830:                             my (%allroles,%allgroups,$group_privs,
 6831:                                 %groups_roles,@rolecodes);
 6832:                             my %userroles = (
 6833:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6834:                             );
 6835:                             @rolecodes = ('cm'); 
 6836:                             my $spec=$$role.'.'.$$where;
 6837:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6838:                             if ($$role =~ /^cr\//) {
 6839:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6840:                                 push(@rolecodes,'cr');
 6841:                             } elsif ($$role eq 'gr') {
 6842:                                 push(@rolecodes,$$role);
 6843:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6844:                                                     $env{'user.name'});
 6845:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6846:                                 (undef,my $group_privs) = split(/\//,$trole);
 6847:                                 $group_privs = &unescape($group_privs);
 6848:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6849:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6850:                                 &get_groups_roles($tdomain,$trest,
 6851:                                                   \%course_roles,\@rolecodes,
 6852:                                                   \%groups_roles);
 6853:                             } else {
 6854:                                 push(@rolecodes,$$role);
 6855:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6856:                             }
 6857:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6858:                                                                    \%groups_roles);
 6859:                             &appenv(\%userroles,\@rolecodes);
 6860:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6861:                         }
 6862:                     }
 6863:                     $$tstatus = 'is';
 6864:                 }
 6865:             }
 6866:             if ($$tend) {
 6867:                 if ($$tend<$update) {
 6868:                     $$tstatus='expired';
 6869:                 } elsif ($$tend<$now) {
 6870:                     $$tstatus='will_not';
 6871:                 }
 6872:             }
 6873:         }
 6874:     }
 6875: }
 6876: 
 6877: sub get_groups_roles {
 6878:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6879:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6880:                   (ref($rolecodes) eq 'ARRAY') && 
 6881:                   (ref($groups_roles) eq 'HASH')); 
 6882:     if (keys(%{$cdom_courseroles}) > 0) {
 6883:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6884:         if ($cdom ne '' && $cnum ne '') {
 6885:             foreach my $key (keys(%{$cdom_courseroles})) {
 6886:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6887:                     my $crsrole = $1;
 6888:                     my $crssec = $2;
 6889:                     if ($crsrole =~ /^cr/) {
 6890:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6891:                             push(@{$rolecodes},'cr');
 6892:                         }
 6893:                     } else {
 6894:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6895:                             push(@{$rolecodes},$crsrole);
 6896:                         }
 6897:                     }
 6898:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6899:                     if ($crssec ne '') {
 6900:                         $rolekey .= "/$crssec";
 6901:                     }
 6902:                     $rolekey .= './';
 6903:                     $groups_roles->{$rolekey} = $rolecodes;
 6904:                 }
 6905:             }
 6906:         }
 6907:     }
 6908:     return;
 6909: }
 6910: 
 6911: sub delete_env_groupprivs {
 6912:     my ($where,$courseroles,$possroles) = @_;
 6913:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6914:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6915:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6916:         %{$courseroles->{$udom}} =
 6917:             &get_my_roles('','','userroles',['active'],
 6918:                           $possroles,[$udom],1);
 6919:     }
 6920:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6921:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6922:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6923:             my $area = '/'.$cdom.'/'.$cnum;
 6924:             my $privkey = "user.priv.$crsrole.$area";
 6925:             if ($crssec ne '') {
 6926:                 $privkey .= '/'.$crssec;
 6927:             }
 6928:             $privkey .= ".$area/$group";
 6929:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6930:         }
 6931:     }
 6932:     return;
 6933: }
 6934: 
 6935: sub check_adhoc_privs {
 6936:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6937:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6938:     if ($sec) {
 6939:         $cckey .= '/'.$sec;
 6940:     } 
 6941:     my $setprivs;
 6942:     if ($env{$cckey}) {
 6943:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6944:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6945:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6946:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6947:             $setprivs = 1;
 6948:         }
 6949:     } else {
 6950:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6951:         $setprivs = 1;
 6952:     }
 6953:     return $setprivs;
 6954: }
 6955: 
 6956: sub set_adhoc_privileges {
 6957: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6958:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6959:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6960:     if ($sec ne '') {
 6961:         $area .= '/'.$sec;
 6962:     }
 6963:     my $spec = $role.'.'.$area;
 6964:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6965:                                   $env{'user.name'},1);
 6966:     my %rolehash = ();
 6967:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6968:         my $rolename = $1;
 6969:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6970:         my %domdef = &get_domain_defaults($dcdom);
 6971:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6972:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6973:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6974:             }
 6975:         }
 6976:     } else {
 6977:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6978:     }
 6979:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6980:     &appenv(\%userroles,[$role,'cm']);
 6981:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6982:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 6983:             ($caller eq 'tiny')) {
 6984:         &appenv( {'request.role'        => $spec,
 6985:                   'request.role.domain' => $dcdom,
 6986:                   'request.course.sec'  => $sec,
 6987:                  }
 6988:                );
 6989:         my $tadv=0;
 6990:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6991:         &appenv({'request.role.adv'    => $tadv});
 6992:     }
 6993: }
 6994: 
 6995: # --------------------------------------------------------------- get interface
 6996: 
 6997: sub get {
 6998:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6999:    my $items='';
 7000:    foreach my $item (@$storearr) {
 7001:        $items.=&escape($item).'&';
 7002:    }
 7003:    $items=~s/\&$//;
 7004:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7005:    if (!$uname) { $uname=$env{'user.name'}; }
 7006:    my $uhome=&homeserver($uname,$udomain);
 7007: 
 7008:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7009:    my @pairs=split(/\&/,$rep);
 7010:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7011:      return @pairs;
 7012:    }
 7013:    my %returnhash=();
 7014:    my $i=0;
 7015:    foreach my $item (@$storearr) {
 7016:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7017:       $i++;
 7018:    }
 7019:    return %returnhash;
 7020: }
 7021: 
 7022: # --------------------------------------------------------------- del interface
 7023: 
 7024: sub del {
 7025:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7026:    my $items='';
 7027:    foreach my $item (@$storearr) {
 7028:        $items.=&escape($item).'&';
 7029:    }
 7030: 
 7031:    $items=~s/\&$//;
 7032:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7033:    if (!$uname) { $uname=$env{'user.name'}; }
 7034:    my $uhome=&homeserver($uname,$udomain);
 7035:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7036: }
 7037: 
 7038: # -------------------------------------------------------------- dump interface
 7039: 
 7040: sub unserialize {
 7041:     my ($rep, $escapedkeys) = @_;
 7042: 
 7043:     return {} if $rep =~ /^error/;
 7044: 
 7045:     my %returnhash=();
 7046: 	foreach my $item (split(/\&/,$rep)) {
 7047: 	    my ($key, $value) = split(/=/, $item, 2);
 7048: 	    $key = unescape($key) unless $escapedkeys;
 7049: 	    next if $key =~ /^error: 2 /;
 7050: 	    $returnhash{$key} = &thaw_unescape($value);
 7051: 	}
 7052:     #return %returnhash;
 7053:     return \%returnhash;
 7054: }        
 7055: 
 7056: # see Lond::dump_with_regexp
 7057: # if $escapedkeys hash keys won't get unescaped.
 7058: sub dump {
 7059:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 7060:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7061:     if (!$uname) { $uname=$env{'user.name'}; }
 7062:     my $uhome=&homeserver($uname,$udomain);
 7063: 
 7064:     if ($regexp) {
 7065:         $regexp=&escape($regexp);
 7066:     } else {
 7067:         $regexp='.';
 7068:     }
 7069:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7070:         # user is hosted on this machine
 7071:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7072:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7073:         return %{unserialize($reply, $escapedkeys)};
 7074:     }
 7075:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7076:     my @pairs=split(/\&/,$rep);
 7077:     my %returnhash=();
 7078:     if (!($rep =~ /^error/ )) {
 7079: 	foreach my $item (@pairs) {
 7080: 	    my ($key,$value)=split(/=/,$item,2);
 7081:         $key = unescape($key) unless $escapedkeys;
 7082:         #$key = &unescape($key);
 7083: 	    next if ($key =~ /^error: 2 /);
 7084: 	    $returnhash{$key}=&thaw_unescape($value);
 7085: 	}
 7086:     }
 7087:     return %returnhash;
 7088: }
 7089: 
 7090: 
 7091: # --------------------------------------------------------- dumpstore interface
 7092: 
 7093: sub dumpstore {
 7094:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7095:    # same as dump but keys must be escaped. They may contain colon separated
 7096:    # lists of values that may themself contain colons (e.g. symbs).
 7097:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7098: }
 7099: 
 7100: # -------------------------------------------------------------- keys interface
 7101: 
 7102: sub getkeys {
 7103:    my ($namespace,$udomain,$uname)=@_;
 7104:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7105:    if (!$uname) { $uname=$env{'user.name'}; }
 7106:    my $uhome=&homeserver($uname,$udomain);
 7107:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7108:    my @keyarray=();
 7109:    foreach my $key (split(/\&/,$rep)) {
 7110:       next if ($key =~ /^error: 2 /);
 7111:       push(@keyarray,&unescape($key));
 7112:    }
 7113:    return @keyarray;
 7114: }
 7115: 
 7116: # --------------------------------------------------------------- currentdump
 7117: sub currentdump {
 7118:    my ($courseid,$sdom,$sname)=@_;
 7119:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7120:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7121:    $sname    = $env{'user.name'}         if (! defined($sname));
 7122:    my $uhome = &homeserver($sname,$sdom);
 7123:    my $rep;
 7124: 
 7125:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7126:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7127:                    $courseid)));
 7128:    } else {
 7129:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7130:    }
 7131: 
 7132:    return if ($rep =~ /^(error:|no_such_host)/);
 7133:    #
 7134:    my %returnhash=();
 7135:    #
 7136:    if ($rep eq 'unknown_cmd') {
 7137:        # an old lond will not know currentdump
 7138:        # Do a dump and make it look like a currentdump
 7139:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7140:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7141:        my %hash = @tmp;
 7142:        @tmp=();
 7143:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7144:    } else {
 7145:        my @pairs=split(/\&/,$rep);
 7146:        foreach my $pair (@pairs) {
 7147:            my ($key,$value)=split(/=/,$pair,2);
 7148:            my ($symb,$param) = split(/:/,$key);
 7149:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7150:                                                         &thaw_unescape($value);
 7151:        }
 7152:    }
 7153:    return %returnhash;
 7154: }
 7155: 
 7156: sub convert_dump_to_currentdump{
 7157:     my %hash = %{shift()};
 7158:     my %returnhash;
 7159:     # Code ripped from lond, essentially.  The only difference
 7160:     # here is the unescaping done by lonnet::dump().  Conceivably
 7161:     # we might run in to problems with parameter names =~ /^v\./
 7162:     while (my ($key,$value) = each(%hash)) {
 7163:         my ($v,$symb,$param) = split(/:/,$key);
 7164: 	$symb  = &unescape($symb);
 7165: 	$param = &unescape($param);
 7166:         next if ($v eq 'version' || $symb eq 'keys');
 7167:         next if (exists($returnhash{$symb}) &&
 7168:                  exists($returnhash{$symb}->{$param}) &&
 7169:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7170:         $returnhash{$symb}->{$param}=$value;
 7171:         $returnhash{$symb}->{'v.'.$param}=$v;
 7172:     }
 7173:     #
 7174:     # Remove all of the keys in the hashes which keep track of
 7175:     # the version of the parameter.
 7176:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7177:         # use a foreach because we are going to delete from the hash.
 7178:         foreach my $key (keys(%$param_hash)) {
 7179:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7180:         }
 7181:     }
 7182:     return \%returnhash;
 7183: }
 7184: 
 7185: # ------------------------------------------------------ critical inc interface
 7186: 
 7187: sub cinc {
 7188:     return &inc(@_,'critical');
 7189: }
 7190: 
 7191: # --------------------------------------------------------------- inc interface
 7192: 
 7193: sub inc {
 7194:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7195:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7196:     if (!$uname) { $uname=$env{'user.name'}; }
 7197:     my $uhome=&homeserver($uname,$udomain);
 7198:     my $items='';
 7199:     if (! ref($store)) {
 7200:         # got a single value, so use that instead
 7201:         $items = &escape($store).'=&';
 7202:     } elsif (ref($store) eq 'SCALAR') {
 7203:         $items = &escape($$store).'=&';        
 7204:     } elsif (ref($store) eq 'ARRAY') {
 7205:         $items = join('=&',map {&escape($_);} @{$store});
 7206:     } elsif (ref($store) eq 'HASH') {
 7207:         while (my($key,$value) = each(%{$store})) {
 7208:             $items.= &escape($key).'='.&escape($value).'&';
 7209:         }
 7210:     }
 7211:     $items=~s/\&$//;
 7212:     if ($critical) {
 7213: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7214:     } else {
 7215: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7216:     }
 7217: }
 7218: 
 7219: # --------------------------------------------------------------- put interface
 7220: 
 7221: sub put {
 7222:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7223:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7224:    if (!$uname) { $uname=$env{'user.name'}; }
 7225:    my $uhome=&homeserver($uname,$udomain);
 7226:    my $items='';
 7227:    foreach my $item (keys(%$storehash)) {
 7228:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7229:    }
 7230:    $items=~s/\&$//;
 7231:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7232: }
 7233: 
 7234: # ------------------------------------------------------------ newput interface
 7235: 
 7236: sub newput {
 7237:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7238:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7239:    if (!$uname) { $uname=$env{'user.name'}; }
 7240:    my $uhome=&homeserver($uname,$udomain);
 7241:    my $items='';
 7242:    foreach my $key (keys(%$storehash)) {
 7243:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7244:    }
 7245:    $items=~s/\&$//;
 7246:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7247: }
 7248: 
 7249: # ---------------------------------------------------------  putstore interface
 7250: 
 7251: sub putstore {
 7252:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7253:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7254:    if (!$uname) { $uname=$env{'user.name'}; }
 7255:    my $uhome=&homeserver($uname,$udomain);
 7256:    my $items='';
 7257:    foreach my $key (keys(%$storehash)) {
 7258:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7259:    }
 7260:    $items=~s/\&$//;
 7261:    my $esc_symb=&escape($symb);
 7262:    my $esc_v=&escape($version);
 7263:    my $reply =
 7264:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7265: 	      $uhome);
 7266:    if (($tolog) && ($reply eq 'ok')) {
 7267:        my $namevalue='';
 7268:        foreach my $key (keys(%{$storehash})) {
 7269:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7270:        }
 7271:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 7272:                      '&host='.&escape($perlvar{'lonHostID'}).
 7273:                      '&version='.$esc_v.
 7274:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7275:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7276:    }
 7277:    if ($reply eq 'unknown_cmd') {
 7278:        # gfall back to way things use to be done
 7279:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7280: 			    $uname);
 7281:    }
 7282:    return $reply;
 7283: }
 7284: 
 7285: sub old_putstore {
 7286:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7287:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7288:     if (!$uname) { $uname=$env{'user.name'}; }
 7289:     my $uhome=&homeserver($uname,$udomain);
 7290:     my %newstorehash;
 7291:     foreach my $item (keys(%$storehash)) {
 7292: 	my $key = $version.':'.&escape($symb).':'.$item;
 7293: 	$newstorehash{$key} = $storehash->{$item};
 7294:     }
 7295:     my $items='';
 7296:     my %allitems = ();
 7297:     foreach my $item (keys(%newstorehash)) {
 7298: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7299: 	    my $key = $1.':keys:'.$2;
 7300: 	    $allitems{$key} .= $3.':';
 7301: 	}
 7302: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7303:     }
 7304:     foreach my $item (keys(%allitems)) {
 7305: 	$allitems{$item} =~ s/\:$//;
 7306: 	$items.= $item.'='.$allitems{$item}.'&';
 7307:     }
 7308:     $items=~s/\&$//;
 7309:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7310: }
 7311: 
 7312: # ------------------------------------------------------ critical put interface
 7313: 
 7314: sub cput {
 7315:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7316:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7317:    if (!$uname) { $uname=$env{'user.name'}; }
 7318:    my $uhome=&homeserver($uname,$udomain);
 7319:    my $items='';
 7320:    foreach my $item (keys(%$storehash)) {
 7321:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7322:    }
 7323:    $items=~s/\&$//;
 7324:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7325: }
 7326: 
 7327: # -------------------------------------------------------------- eget interface
 7328: 
 7329: sub eget {
 7330:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7331:    my $items='';
 7332:    foreach my $item (@$storearr) {
 7333:        $items.=&escape($item).'&';
 7334:    }
 7335:    $items=~s/\&$//;
 7336:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7337:    if (!$uname) { $uname=$env{'user.name'}; }
 7338:    my $uhome=&homeserver($uname,$udomain);
 7339:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7340:    my @pairs=split(/\&/,$rep);
 7341:    my %returnhash=();
 7342:    my $i=0;
 7343:    foreach my $item (@$storearr) {
 7344:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7345:       $i++;
 7346:    }
 7347:    return %returnhash;
 7348: }
 7349: 
 7350: # ------------------------------------------------------------ tmpput interface
 7351: sub tmpput {
 7352:     my ($storehash,$server,$context)=@_;
 7353:     my $items='';
 7354:     foreach my $item (keys(%$storehash)) {
 7355: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7356:     }
 7357:     $items=~s/\&$//;
 7358:     if (defined($context)) {
 7359:         $items .= ':'.&escape($context);
 7360:     }
 7361:     return &reply("tmpput:$items",$server);
 7362: }
 7363: 
 7364: # ------------------------------------------------------------ tmpget interface
 7365: sub tmpget {
 7366:     my ($token,$server)=@_;
 7367:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7368:     my $rep=&reply("tmpget:$token",$server);
 7369:     my %returnhash;
 7370:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7371:         return %returnhash;
 7372:     }
 7373:     foreach my $item (split(/\&/,$rep)) {
 7374: 	my ($key,$value)=split(/=/,$item);
 7375: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7376:     }
 7377:     return %returnhash;
 7378: }
 7379: 
 7380: # ------------------------------------------------------------ tmpdel interface
 7381: sub tmpdel {
 7382:     my ($token,$server)=@_;
 7383:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7384:     return &reply("tmpdel:$token",$server);
 7385: }
 7386: 
 7387: # ------------------------------------------------------------ get_timebased_id 
 7388: 
 7389: sub get_timebased_id {
 7390:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7391:         $maxtries) = @_;
 7392:     my ($newid,$error,$dellock);
 7393:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7394:         return ('','ok','invalid call to get suffix');
 7395:     }
 7396: 
 7397: # set defaults for any optional args for which values were not supplied
 7398:     if ($who eq '') {
 7399:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7400:     }
 7401:     if (!$locktries) {
 7402:         $locktries = 3;
 7403:     }
 7404:     if (!$maxtries) {
 7405:         $maxtries = 10;
 7406:     }
 7407:     
 7408:     if (($cdom eq '') || ($cnum eq '')) {
 7409:         if ($env{'request.course.id'}) {
 7410:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7411:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7412:         }
 7413:         if (($cdom eq '') || ($cnum eq '')) {
 7414:             return ('','ok','call to get suffix not in course context');
 7415:         }
 7416:     }
 7417: 
 7418: # construct locking item
 7419:     my $lockhash = {
 7420:                       $prefix."\0".'locked_'.$keyid => $who,
 7421:                    };
 7422:     my $tries = 0;
 7423: 
 7424: # attempt to get lock on nohist_$namespace file
 7425:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7426:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7427:         $tries ++;
 7428:         sleep 1;
 7429:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7430:     }
 7431: 
 7432: # attempt to get unique identifier, based on current timestamp
 7433:     if ($gotlock eq 'ok') {
 7434:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7435:         my $id = time;
 7436:         $newid = $id;
 7437:         if ($idtype eq 'addcode') {
 7438:             $newid .= &sixnum_code();
 7439:         }
 7440:         my $idtries = 0;
 7441:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7442:             if ($idtype eq 'concat') {
 7443:                 $newid = $id.$idtries;
 7444:             } elsif ($idtype eq 'addcode') {
 7445:                 $newid = $newid.&sixnum_code();
 7446:             } else {
 7447:                 $newid ++;
 7448:             }
 7449:             $idtries ++;
 7450:         }
 7451:         if (!exists($inuse{$prefix."\0".$newid})) {
 7452:             my %new_item =  (
 7453:                               $prefix."\0".$newid => $who,
 7454:                             );
 7455:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7456:                                                  $cdom,$cnum);
 7457:             if ($putresult ne 'ok') {
 7458:                 undef($newid);
 7459:                 $error = 'error saving new item: '.$putresult;
 7460:             }
 7461:         } else {
 7462:              undef($newid);
 7463:              $error = ('error: no unique suffix available for the new item ');
 7464:         }
 7465: #  remove lock
 7466:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7467:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7468:     } else {
 7469:         $error = "error: could not obtain lockfile\n";
 7470:         $dellock = 'ok';
 7471:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7472:             $dellock = 'nolock';
 7473:         }
 7474:     }
 7475:     return ($newid,$dellock,$error);
 7476: }
 7477: 
 7478: sub sixnum_code {
 7479:     my $code;
 7480:     for (0..6) {
 7481:         $code .= int( rand(9) );
 7482:     }
 7483:     return $code;
 7484: }
 7485: 
 7486: # -------------------------------------------------- portfolio access checking
 7487: 
 7488: sub portfolio_access {
 7489:     my ($requrl,$clientip) = @_;
 7490:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7491:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7492:     if ($result) {
 7493:         my %setters;
 7494:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7495:             my ($startblock,$endblock) =
 7496:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7497:             if ($startblock && $endblock) {
 7498:                 return 'B';
 7499:             }
 7500:         } else {
 7501:             my ($startblock,$endblock) =
 7502:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7503:             if ($startblock && $endblock) {
 7504:                 return 'B';
 7505:             }
 7506:         }
 7507:     }
 7508:     if ($result eq 'ok') {
 7509:        return 'F';
 7510:     } elsif ($result =~ /^[^:]+:guest_/) {
 7511:        return 'A';
 7512:     }
 7513:     return '';
 7514: }
 7515: 
 7516: sub get_portfolio_access {
 7517:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7518: 
 7519:     if (!ref($access_hash)) {
 7520: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7521: 	my %access_controls = &get_access_controls($current_perms,$group,
 7522: 						   $file_name);
 7523: 	$access_hash = $access_controls{$file_name};
 7524:     }
 7525: 
 7526:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7527:     my $now = time;
 7528:     if (ref($access_hash) eq 'HASH') {
 7529:         foreach my $key (keys(%{$access_hash})) {
 7530:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7531:             if ($start > $now) {
 7532:                 next;
 7533:             }
 7534:             if ($end && $end<$now) {
 7535:                 next;
 7536:             }
 7537:             if ($scope eq 'public') {
 7538:                 $public = $key;
 7539:                 last;
 7540:             } elsif ($scope eq 'guest') {
 7541:                 $guest = $key;
 7542:             } elsif ($scope eq 'domains') {
 7543:                 push(@domains,$key);
 7544:             } elsif ($scope eq 'users') {
 7545:                 push(@users,$key);
 7546:             } elsif ($scope eq 'course') {
 7547:                 push(@courses,$key);
 7548:             } elsif ($scope eq 'group') {
 7549:                 push(@groups,$key);
 7550:             } elsif ($scope eq 'ip') {
 7551:                 push(@ips,$key);
 7552:             }
 7553:         }
 7554:         if ($public) {
 7555:             return 'ok';
 7556:         } elsif (@ips > 0) {
 7557:             my $allowed;
 7558:             foreach my $ipkey (@ips) {
 7559:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7560:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7561:                         $allowed = 1;
 7562:                         last; 
 7563:                     }
 7564:                 }
 7565:             }
 7566:             if ($allowed) {
 7567:                 return 'ok';
 7568:             }
 7569:         }
 7570:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7571:             if ($guest) {
 7572:                 return $guest;
 7573:             }
 7574:         } else {
 7575:             if (@domains > 0) {
 7576:                 foreach my $domkey (@domains) {
 7577:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7578:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7579:                             return 'ok';
 7580:                         }
 7581:                     }
 7582:                 }
 7583:             }
 7584:             if (@users > 0) {
 7585:                 foreach my $userkey (@users) {
 7586:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7587:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7588:                             if (ref($item) eq 'HASH') {
 7589:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7590:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7591:                                     return 'ok';
 7592:                                 }
 7593:                             }
 7594:                         }
 7595:                     } 
 7596:                 }
 7597:             }
 7598:             my %roleshash;
 7599:             my @courses_and_groups = @courses;
 7600:             push(@courses_and_groups,@groups); 
 7601:             if (@courses_and_groups > 0) {
 7602:                 my (%allgroups,%allroles); 
 7603:                 my ($start,$end,$role,$sec,$group);
 7604:                 foreach my $envkey (%env) {
 7605:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7606:                         my $cid = $2.'_'.$3; 
 7607:                         if ($1 eq 'gr') {
 7608:                             $group = $4;
 7609:                             $allgroups{$cid}{$group} = $env{$envkey};
 7610:                         } else {
 7611:                             if ($4 eq '') {
 7612:                                 $sec = 'none';
 7613:                             } else {
 7614:                                 $sec = $4;
 7615:                             }
 7616:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7617:                         }
 7618:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7619:                         my $cid = $2.'_'.$3;
 7620:                         if ($4 eq '') {
 7621:                             $sec = 'none';
 7622:                         } else {
 7623:                             $sec = $4;
 7624:                         }
 7625:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7626:                     }
 7627:                 }
 7628:                 if (keys(%allroles) == 0) {
 7629:                     return;
 7630:                 }
 7631:                 foreach my $key (@courses_and_groups) {
 7632:                     my %content = %{$$access_hash{$key}};
 7633:                     my $cnum = $content{'number'};
 7634:                     my $cdom = $content{'domain'};
 7635:                     my $cid = $cdom.'_'.$cnum;
 7636:                     if (!exists($allroles{$cid})) {
 7637:                         next;
 7638:                     }    
 7639:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7640:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7641:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7642:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7643:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7644:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7645:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7646:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7647:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7648:                                         if (grep/^all$/,@sections) {
 7649:                                             return 'ok';
 7650:                                         } else {
 7651:                                             if (grep/^$sec$/,@sections) {
 7652:                                                 return 'ok';
 7653:                                             }
 7654:                                         }
 7655:                                     }
 7656:                                 }
 7657:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7658:                                     if (grep/^none$/,@groups) {
 7659:                                         return 'ok';
 7660:                                     }
 7661:                                 } else {
 7662:                                     if (grep/^all$/,@groups) {
 7663:                                         return 'ok';
 7664:                                     } 
 7665:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7666:                                         if (grep/^$group$/,@groups) {
 7667:                                             return 'ok';
 7668:                                         }
 7669:                                     }
 7670:                                 } 
 7671:                             }
 7672:                         }
 7673:                     }
 7674:                 }
 7675:             }
 7676:             if ($guest) {
 7677:                 return $guest;
 7678:             }
 7679:         }
 7680:     }
 7681:     return;
 7682: }
 7683: 
 7684: sub course_group_datechecker {
 7685:     my ($dates,$now,$status) = @_;
 7686:     my ($start,$end) = split(/\./,$dates);
 7687:     if (!$start && !$end) {
 7688:         return 'ok';
 7689:     }
 7690:     if (grep/^active$/,@{$status}) {
 7691:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7692:             return 'ok';
 7693:         }
 7694:     }
 7695:     if (grep/^previous$/,@{$status}) {
 7696:         if ($end > $now ) {
 7697:             return 'ok';
 7698:         }
 7699:     }
 7700:     if (grep/^future$/,@{$status}) {
 7701:         if ($start > $now) {
 7702:             return 'ok';
 7703:         }
 7704:     }
 7705:     return; 
 7706: }
 7707: 
 7708: sub parse_portfolio_url {
 7709:     my ($url) = @_;
 7710: 
 7711:     my ($type,$udom,$unum,$group,$file_name);
 7712:     
 7713:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7714: 	$type = 1;
 7715:         $udom = $1;
 7716:         $unum = $2;
 7717:         $file_name = $3;
 7718:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7719: 	$type = 2;
 7720:         $udom = $1;
 7721:         $unum = $2;
 7722:         $group = $3;
 7723:         $file_name = $3.'/'.$4;
 7724:     }
 7725:     if (wantarray) {
 7726: 	return ($type,$udom,$unum,$file_name,$group);
 7727:     }
 7728:     return $type;
 7729: }
 7730: 
 7731: sub is_portfolio_url {
 7732:     my ($url) = @_;
 7733:     return scalar(&parse_portfolio_url($url));
 7734: }
 7735: 
 7736: sub is_portfolio_file {
 7737:     my ($file) = @_;
 7738:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7739:         return 1;
 7740:     }
 7741:     return;
 7742: }
 7743: 
 7744: sub usertools_access {
 7745:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7746:     my ($access,%tools);
 7747:     if ($context eq '') {
 7748:         $context = 'tools';
 7749:     }
 7750:     if ($context eq 'requestcourses') {
 7751:         %tools = (
 7752:                       official   => 1,
 7753:                       unofficial => 1,
 7754:                       community  => 1,
 7755:                       textbook   => 1,
 7756:                       placement  => 1,
 7757:                       lti        => 1,
 7758:                  );
 7759:     } elsif ($context eq 'requestauthor') {
 7760:         %tools = (
 7761:                       requestauthor => 1,
 7762:                  );
 7763:     } else {
 7764:         %tools = (
 7765:                       aboutme   => 1,
 7766:                       blog      => 1,
 7767:                       webdav    => 1,
 7768:                       portfolio => 1,
 7769:                  );
 7770:     }
 7771:     return if (!defined($tools{$tool}));
 7772: 
 7773:     if (($udom eq '') || ($uname eq '')) {
 7774:         $udom = $env{'user.domain'};
 7775:         $uname = $env{'user.name'};
 7776:     }
 7777: 
 7778:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7779:         if ($action ne 'reload') {
 7780:             if ($context eq 'requestcourses') {
 7781:                 return $env{'environment.canrequest.'.$tool};
 7782:             } elsif ($context eq 'requestauthor') {
 7783:                 return $env{'environment.canrequest.author'};
 7784:             } else {
 7785:                 return $env{'environment.availabletools.'.$tool};
 7786:             }
 7787:         }
 7788:     }
 7789: 
 7790:     my ($toolstatus,$inststatus,$envkey);
 7791:     if ($context eq 'requestauthor') {
 7792:         $envkey = $context; 
 7793:     } else {
 7794:         $envkey = $context.'.'.$tool;
 7795:     }
 7796: 
 7797:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7798:          ($action ne 'reload')) {
 7799:         $toolstatus = $env{'environment.'.$envkey};
 7800:         $inststatus = $env{'environment.inststatus'};
 7801:     } else {
 7802:         if (ref($userenvref) eq 'HASH') {
 7803:             $toolstatus = $userenvref->{$envkey};
 7804:             $inststatus = $userenvref->{'inststatus'};
 7805:         } else {
 7806:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7807:             $toolstatus = $userenv{$envkey};
 7808:             $inststatus = $userenv{'inststatus'};
 7809:         }
 7810:     }
 7811: 
 7812:     if ($toolstatus ne '') {
 7813:         if ($toolstatus) {
 7814:             $access = 1;
 7815:         } else {
 7816:             $access = 0;
 7817:         }
 7818:         return $access;
 7819:     }
 7820: 
 7821:     my ($is_adv,%domdef);
 7822:     if (ref($is_advref) eq 'HASH') {
 7823:         $is_adv = $is_advref->{'is_adv'};
 7824:     } else {
 7825:         $is_adv = &is_advanced_user($udom,$uname);
 7826:     }
 7827:     if (ref($domdefref) eq 'HASH') {
 7828:         %domdef = %{$domdefref};
 7829:     } else {
 7830:         %domdef = &get_domain_defaults($udom);
 7831:     }
 7832:     if (ref($domdef{$tool}) eq 'HASH') {
 7833:         if ($is_adv) {
 7834:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7835:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7836:                     $access = 1;
 7837:                 } else {
 7838:                     $access = 0;
 7839:                 }
 7840:                 return $access;
 7841:             }
 7842:         }
 7843:         if ($inststatus ne '') {
 7844:             my ($hasaccess,$hasnoaccess);
 7845:             foreach my $affiliation (split(/:/,$inststatus)) {
 7846:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7847:                     if ($domdef{$tool}{$affiliation}) {
 7848:                         $hasaccess = 1;
 7849:                     } else {
 7850:                         $hasnoaccess = 1;
 7851:                     }
 7852:                 }
 7853:             }
 7854:             if ($hasaccess || $hasnoaccess) {
 7855:                 if ($hasaccess) {
 7856:                     $access = 1;
 7857:                 } elsif ($hasnoaccess) {
 7858:                     $access = 0; 
 7859:                 }
 7860:                 return $access;
 7861:             }
 7862:         } else {
 7863:             if ($domdef{$tool}{'default'} ne '') {
 7864:                 if ($domdef{$tool}{'default'}) {
 7865:                     $access = 1;
 7866:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7867:                     $access = 0;
 7868:                 }
 7869:                 return $access;
 7870:             }
 7871:         }
 7872:     } else {
 7873:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7874:             $access = 1;
 7875:         } else {
 7876:             $access = 0;
 7877:         }
 7878:         return $access;
 7879:     }
 7880: }
 7881: 
 7882: sub is_course_owner {
 7883:     my ($cdom,$cnum,$udom,$uname) = @_;
 7884:     if (($udom eq '') || ($uname eq '')) {
 7885:         $udom = $env{'user.domain'};
 7886:         $uname = $env{'user.name'};
 7887:     }
 7888:     unless (($udom eq '') || ($uname eq '')) {
 7889:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7890:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7891:                 return 1;
 7892:             } else {
 7893:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7894:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7895:                     return 1;
 7896:                 }
 7897:             }
 7898:         }
 7899:     }
 7900:     return;
 7901: }
 7902: 
 7903: sub is_advanced_user {
 7904:     my ($udom,$uname) = @_;
 7905:     if ($udom ne '' && $uname ne '') {
 7906:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7907:             if (wantarray) {
 7908:                 return ($env{'user.adv'},$env{'user.author'});
 7909:             } else {
 7910:                 return $env{'user.adv'};
 7911:             }
 7912:         }
 7913:     }
 7914:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7915:     my %allroles;
 7916:     my ($is_adv,$is_author);
 7917:     foreach my $role (keys(%roleshash)) {
 7918:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7919:         my $area = '/'.$tdomain.'/'.$trest;
 7920:         if ($sec ne '') {
 7921:             $area .= '/'.$sec;
 7922:         }
 7923:         if (($area ne '') && ($trole ne '')) {
 7924:             my $spec=$trole.'.'.$area;
 7925:             if ($trole =~ /^cr\//) {
 7926:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7927:             } elsif ($trole ne 'gr') {
 7928:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7929:             }
 7930:             if ($trole eq 'au') {
 7931:                 $is_author = 1;
 7932:             }
 7933:         }
 7934:     }
 7935:     foreach my $role (keys(%allroles)) {
 7936:         last if ($is_adv);
 7937:         foreach my $item (split(/:/,$allroles{$role})) {
 7938:             if ($item ne '') {
 7939:                 my ($privilege,$restrictions)=split(/&/,$item);
 7940:                 if ($privilege eq 'adv') {
 7941:                     $is_adv = 1;
 7942:                     last;
 7943:                 }
 7944:             }
 7945:         }
 7946:     }
 7947:     if (wantarray) {
 7948:         return ($is_adv,$is_author);
 7949:     }
 7950:     return $is_adv;
 7951: }
 7952: 
 7953: sub check_can_request {
 7954:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7955:     my $canreq = 0;
 7956:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7957:         $uname = $env{'user.name'};
 7958:         $udom = $env{'user.domain'};
 7959:     }
 7960:     my ($types,$typename) = &Apache::loncommon::course_types();
 7961:     my @options = ('approval','validate','autolimit');
 7962:     my $optregex = join('|',@options);
 7963:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7964:         foreach my $type (@{$types}) {
 7965:             if (&usertools_access($uname,$udom,$type,undef,
 7966:                                   'requestcourses')) {
 7967:                 $canreq ++;
 7968:                 if (ref($request_domains) eq 'HASH') {
 7969:                     push(@{$request_domains->{$type}},$udom);
 7970:                 }
 7971:                 if ($dom eq $udom) {
 7972:                     $can_request->{$type} = 1;
 7973:                 }
 7974:             }
 7975:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7976:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7977:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7978:                 if (@curr > 0) {
 7979:                     foreach my $item (@curr) {
 7980:                         if (ref($request_domains) eq 'HASH') {
 7981:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7982:                             if ($otherdom ne '') {
 7983:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7984:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7985:                                         push(@{$request_domains->{$type}},$otherdom);
 7986:                                     }
 7987:                                 } else {
 7988:                                     push(@{$request_domains->{$type}},$otherdom);
 7989:                                 }
 7990:                             }
 7991:                         }
 7992:                     }
 7993:                     unless ($dom eq $env{'user.domain'}) {
 7994:                         $canreq ++;
 7995:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7996:                             $can_request->{$type} = 1;
 7997:                         }
 7998:                     }
 7999:                 }
 8000:             }
 8001:         }
 8002:     }
 8003:     return $canreq;
 8004: }
 8005: 
 8006: # ---------------------------------------------- Custom access rule evaluation
 8007: 
 8008: sub customaccess {
 8009:     my ($priv,$uri)=@_;
 8010:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8011:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8012:     $udom = &LONCAPA::clean_domain($udom);
 8013:     $ucrs = &LONCAPA::clean_username($ucrs);
 8014:     my $access=0;
 8015:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8016: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8017: 	if ($type eq 'user') {
 8018: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8019: 		my ($tdom,$tuname)=split(m{/},$scope);
 8020: 		if ($tdom) {
 8021: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8022: 		}
 8023: 		if ($tuname) {
 8024: 		    if ($tuname ne $env{'user.name'}) { next; }
 8025: 		}
 8026: 		$access=($effect eq 'allow');
 8027: 		last;
 8028: 	    }
 8029: 	} else {
 8030: 	    if ($role) {
 8031: 		if ($role ne $urole) { next; }
 8032: 	    }
 8033: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8034: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8035: 		if ($tdom) {
 8036: 		    if ($tdom ne $udom) { next; }
 8037: 		}
 8038: 		if ($tcrs) {
 8039: 		    if ($tcrs ne $ucrs) { next; }
 8040: 		}
 8041: 		if ($tsec) {
 8042: 		    if ($tsec ne $usec) { next; }
 8043: 		}
 8044: 		$access=($effect eq 'allow');
 8045: 		last;
 8046: 	    }
 8047: 	    if ($realm eq '' && $role eq '') {
 8048: 		$access=($effect eq 'allow');
 8049: 	    }
 8050: 	}
 8051:     }
 8052:     return $access;
 8053: }
 8054: 
 8055: # ------------------------------------------------- Check for a user privilege
 8056: 
 8057: sub allowed {
 8058:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
 8059:     my $ver_orguri=$uri;
 8060:     $uri=&deversion($uri);
 8061:     my $orguri=$uri;
 8062:     $uri=&declutter($uri);
 8063: 
 8064:     if ($priv eq 'evb') {
 8065: # Evade communication block restrictions for specified role in a course
 8066:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8067:             return $1;
 8068:         } else {
 8069:             return;
 8070:         }
 8071:     }
 8072: 
 8073:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8074: # Free bre access to adm and meta resources
 8075:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 8076: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8077: 	&& ($priv eq 'bre')) {
 8078: 	return 'F';
 8079:     }
 8080: 
 8081: # Free bre access to user's own portfolio contents
 8082:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8083:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8084: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8085:         my %setters;
 8086:         my ($startblock,$endblock) = 
 8087:             &Apache::loncommon::blockcheck(\%setters,'port');
 8088:         if ($startblock && $endblock) {
 8089:             return 'B';
 8090:         } else {
 8091:             return 'F';
 8092:         }
 8093:     }
 8094: 
 8095: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8096:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8097:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8098:         if (exists($env{'request.course.id'})) {
 8099:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8100:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8101:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8102:                 my $courseprivid=$env{'request.course.id'};
 8103:                 $courseprivid=~s/\_/\//;
 8104:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8105:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8106:                     return $1; 
 8107:                 } else {
 8108:                     if ($env{'request.course.sec'}) {
 8109:                         $courseprivid.='/'.$env{'request.course.sec'};
 8110:                     }
 8111:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8112:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8113:                         return $2;
 8114:                     }
 8115:                 }
 8116:             }
 8117:         }
 8118:     }
 8119: 
 8120: # Free bre to public access
 8121: 
 8122:     if ($priv eq 'bre') {
 8123:         my $copyright;
 8124:         unless ($uri =~ /ext\.tool/) {
 8125:             $copyright=&metadata($uri,'copyright');
 8126:         }
 8127: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8128:            return 'F'; 
 8129:         }
 8130:         if ($copyright eq 'priv') {
 8131:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8132: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8133: 		return '';
 8134:             }
 8135:         }
 8136:         if ($copyright eq 'domain') {
 8137:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8138: 	    unless (($env{'user.domain'} eq $1) ||
 8139:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8140: 		return '';
 8141:             }
 8142:         }
 8143:         if ($env{'request.role'}=~ /li\.\//) {
 8144:             # Library role, so allow browsing of resources in this domain.
 8145:             return 'F';
 8146:         }
 8147:         if ($copyright eq 'custom') {
 8148: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8149:         }
 8150:     }
 8151:     # Domain coordinator is trying to create a course
 8152:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8153:         # uri is the requested domain in this case.
 8154:         # comparison to 'request.role.domain' shows if the user has selected
 8155:         # a role of dc for the domain in question.
 8156:         return 'F' if ($uri eq $env{'request.role.domain'});
 8157:     }
 8158: 
 8159:     my $thisallowed='';
 8160:     my $statecond=0;
 8161:     my $courseprivid='';
 8162: 
 8163:     my $ownaccess;
 8164:     # Community Coordinator or Assistant Co-author browsing resource space.
 8165:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8166:         if ($uri eq '') {
 8167:             $ownaccess = 1;
 8168:         } else {
 8169:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8170:                 my $udom = $env{'user.domain'};
 8171:                 my $uname = $env{'user.name'};
 8172:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8173:                     $ownaccess = 1;
 8174:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8175:                     unless ($uri =~ m{\.\./}) {
 8176:                         $ownaccess = 1;
 8177:                     }
 8178:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8179:                     my $now = time;
 8180:                     if ($uri =~ m{^([^/]+)/?$}) {
 8181:                         my $adom = $1;
 8182:                         foreach my $key (keys(%env)) {
 8183:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8184:                                 my ($start,$end) = split('.',$env{$key});
 8185:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8186:                                     $ownaccess = 1;
 8187:                                     last;
 8188:                                 }
 8189:                             }
 8190:                         }
 8191:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8192:                         my $adom = $1;
 8193:                         my $aname = $2;
 8194:                         foreach my $role ('ca','aa') { 
 8195:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8196:                                 my ($start,$end) =
 8197:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8198:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8199:                                     $ownaccess = 1;
 8200:                                     last;
 8201:                                 }
 8202:                             }
 8203:                         }
 8204:                     }
 8205:                 }
 8206:             }
 8207:         }
 8208:     }
 8209: 
 8210: # Course
 8211: 
 8212:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8213:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8214:             $thisallowed.=$1;
 8215:         }
 8216:     }
 8217: 
 8218: # Domain
 8219: 
 8220:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8221:        =~/\Q$priv\E\&([^\:]*)/) {
 8222:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8223:             $thisallowed.=$1;
 8224:         }
 8225:     }
 8226: 
 8227: # User who is not author or co-author might still be able to edit
 8228: # resource of an author in the domain (e.g., if Domain Coordinator).
 8229:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8230:         (&allowed('mdc',$env{'request.course.id'}))) {
 8231:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8232:             $thisallowed.=$1;
 8233:         }
 8234:     }
 8235: 
 8236: # Course: uri itself is a course
 8237:     my $courseuri=$uri;
 8238:     $courseuri=~s/\_(\d)/\/$1/;
 8239:     $courseuri=~s/^([^\/])/\/$1/;
 8240: 
 8241:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8242:        =~/\Q$priv\E\&([^\:]*)/) {
 8243:         if ($priv eq 'mip') {
 8244:             my $rem = $1;
 8245:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8246:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8247:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8248:                 if ($cdom ne '') {
 8249:                     my %passwdconf = &get_passwdconf($cdom);
 8250:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8251:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8252:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8253:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8254:                                 unless (@inststatuses) {
 8255:                                     @inststatuses = ('default');
 8256:                                 }
 8257:                                 foreach my $status (@inststatuses) {
 8258:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8259:                                         $thisallowed.=$rem;
 8260:                                     }
 8261:                                 }
 8262:                             }
 8263:                         }
 8264:                     }
 8265:                 }
 8266:             }
 8267:         } else {
 8268:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8269:                 $thisallowed.=$1;
 8270:             }
 8271:         }
 8272:     }
 8273: 
 8274: # URI is an uploaded document for this course, default permissions don't matter
 8275: # not allowing 'edit' access (editupload) to uploaded course docs
 8276:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8277: 	$thisallowed='';
 8278:         my ($match)=&is_on_map($uri);
 8279:         if ($match) {
 8280:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8281:                   =~/\Q$priv\E\&([^\:]*)/) {
 8282:                 my $value = $1;
 8283:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8284:                 if ($deeplinkblock) {
 8285:                     $thisallowed='D';
 8286:                 } elsif ($noblockcheck) {
 8287:                     $thisallowed.=$value;
 8288:                 } else {
 8289:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8290:                     if (@blockers > 0) {
 8291:                         $thisallowed = 'B';
 8292:                     } else {
 8293:                         $thisallowed.=$value;
 8294:                     }
 8295:                 }
 8296:             }
 8297:         } else {
 8298:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8299:             if ($refuri) {
 8300:                 if ($refuri =~ m|^/adm/|) {
 8301:                     $thisallowed='F';
 8302:                 } else {
 8303:                     $refuri=&declutter($refuri);
 8304:                     my ($match) = &is_on_map($refuri);
 8305:                     if ($match) {
 8306:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8307:                         if ($deeplinkblock) {
 8308:                             $thisallowed='D';
 8309:                         } elsif ($noblockcheck) {
 8310:                             $thisallowed='F';
 8311:                         } else {
 8312:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8313:                             if (@blockers > 0) {
 8314:                                 $thisallowed = 'B';
 8315:                             } else {
 8316:                                 $thisallowed='F';
 8317:                             }
 8318:                         }
 8319:                     }
 8320:                 }
 8321:             }
 8322:         }
 8323:     }
 8324: 
 8325:     if ($priv eq 'bre'
 8326: 	&& $thisallowed ne 'F' 
 8327: 	&& $thisallowed ne '2'
 8328: 	&& &is_portfolio_url($uri)) {
 8329: 	$thisallowed = &portfolio_access($uri,$clientip);
 8330:     }
 8331: 
 8332: # Full access at system, domain or course-wide level? Exit.
 8333:     if ($thisallowed=~/F/) {
 8334: 	return 'F';
 8335:     }
 8336: 
 8337: # If this is generating or modifying users, exit with special codes
 8338: 
 8339:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8340: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8341: 	    my ($audom,$auname)=split('/',$uri);
 8342: # no author name given, so this just checks on the general right to make a co-author in this domain
 8343: 	    unless ($auname) { return $thisallowed; }
 8344: # an author name is given, so we are about to actually make a co-author for a certain account
 8345: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8346: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8347: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8348: 	}
 8349: 	return $thisallowed;
 8350:     }
 8351: #
 8352: # Gathered so far: system, domain and course wide privileges
 8353: #
 8354: # Course: See if uri or referer is an individual resource that is part of 
 8355: # the course
 8356: 
 8357:     if ($env{'request.course.id'}) {
 8358: 
 8359: # If this is modifying password (internal auth) domains must match for user and user's role.
 8360: 
 8361:         if ($priv eq 'mip') {
 8362:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8363:                 return $thisallowed;
 8364:             } else {
 8365:                 return '';
 8366:             }
 8367:         }
 8368: 
 8369:        $courseprivid=$env{'request.course.id'};
 8370:        if ($env{'request.course.sec'}) {
 8371:           $courseprivid.='/'.$env{'request.course.sec'};
 8372:        }
 8373:        $courseprivid=~s/\_/\//;
 8374:        my $checkreferer=1;
 8375:        my ($match,$cond)=&is_on_map($uri);
 8376:        if ($match) {
 8377:            $statecond=$cond;
 8378:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8379:                =~/\Q$priv\E\&([^\:]*)/) {
 8380:                my $value = $1;
 8381:                if ($priv eq 'bre') {
 8382:                    if ($noblockcheck) {
 8383:                        $thisallowed.=$value;
 8384:                    } else {
 8385:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8386:                        if (@blockers > 0) {
 8387:                            $thisallowed = 'B';
 8388:                        } else {
 8389:                            $thisallowed.=$value;
 8390:                        }
 8391:                    }
 8392:                } else {
 8393:                    $thisallowed.=$value;
 8394:                }
 8395:                $checkreferer=0;
 8396:            }
 8397:        }
 8398: 
 8399:        if ($checkreferer) {
 8400: 	  my $refuri=$env{'httpref.'.$orguri};
 8401:             unless ($refuri) {
 8402:                 foreach my $key (keys(%env)) {
 8403: 		    if ($key=~/^httpref\..*\*/) {
 8404: 			my $pattern=$key;
 8405:                         $pattern=~s/^httpref\.\/res\///;
 8406:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8407:                         $pattern=~s/\//\\\//g;
 8408:                         if ($orguri=~/$pattern/) {
 8409: 			    $refuri=$env{$key};
 8410:                         }
 8411:                     }
 8412:                 }
 8413:             }
 8414: 
 8415:          if ($refuri) { 
 8416: 	  $refuri=&declutter($refuri);
 8417:           my ($match,$cond)=&is_on_map($refuri);
 8418:             if ($match) {
 8419:               my $refstatecond=$cond;
 8420:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8421:                   =~/\Q$priv\E\&([^\:]*)/) {
 8422:                   my $value = $1;
 8423:                   if ($priv eq 'bre') {
 8424:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8425:                       if ($deeplinkblock) {
 8426:                           $thisallowed = 'D';
 8427:                       } elsif ($noblockcheck) {
 8428:                           $thisallowed.=$value;
 8429:                       } else {
 8430:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8431:                           if (@blockers > 0) {
 8432:                               $thisallowed = 'B';
 8433:                           } else {
 8434:                               $thisallowed.=$value;
 8435:                           }
 8436:                       }
 8437:                   } else {
 8438:                       $thisallowed.=$value;
 8439:                   }
 8440:                   $uri=$refuri;
 8441:                   $statecond=$refstatecond;
 8442:               }
 8443:           }
 8444:         }
 8445:        }
 8446:    }
 8447: 
 8448: #
 8449: # Gathered now: all privileges that could apply, and condition number
 8450: # 
 8451: #
 8452: # Full or no access?
 8453: #
 8454: 
 8455:     if ($thisallowed=~/F/) {
 8456: 	return 'F';
 8457:     }
 8458: 
 8459:     unless ($thisallowed) {
 8460:         return '';
 8461:     }
 8462: 
 8463: # Restrictions exist, deal with them
 8464: #
 8465: #   C:according to course preferences
 8466: #   R:according to resource settings
 8467: #   L:unless locked
 8468: #   X:according to user session state
 8469: #
 8470: 
 8471: # Possibly locked functionality, check all courses
 8472: # Locks might take effect only after 10 minutes cache expiration for other
 8473: # courses, and 2 minutes for current course
 8474: 
 8475:     my $envkey;
 8476:     if ($thisallowed=~/L/) {
 8477:         foreach $envkey (keys(%env)) {
 8478:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8479:                my $courseid=$2;
 8480:                my $roleid=$1.'.'.$2;
 8481:                $courseid=~s/^\///;
 8482:                my $expiretime=600;
 8483:                if ($env{'request.role'} eq $roleid) {
 8484: 		  $expiretime=120;
 8485:                }
 8486: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8487:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8488:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8489: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8490:                }
 8491:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8492:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8493: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8494:                        &log($env{'user.domain'},$env{'user.name'},
 8495:                             $env{'user.home'},
 8496:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8497:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8498:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8499: 		       return '';
 8500:                    }
 8501:                }
 8502:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8503:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8504: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8505:                        &log($env{'user.domain'},$env{'user.name'},
 8506:                             $env{'user.home'},
 8507:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8508:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8509:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8510: 		       return '';
 8511:                    }
 8512:                }
 8513: 	   }
 8514:        }
 8515:     }
 8516: 
 8517: #
 8518: # Rest of the restrictions depend on selected course
 8519: #
 8520: 
 8521:     unless ($env{'request.course.id'}) {
 8522: 	if ($thisallowed eq 'A') {
 8523: 	    return 'A';
 8524:         } elsif ($thisallowed eq 'B') {
 8525:             return 'B';
 8526: 	} else {
 8527: 	    return '1';
 8528: 	}
 8529:     }
 8530: 
 8531: #
 8532: # Now user is definitely in a course
 8533: #
 8534: 
 8535: 
 8536: # Course preferences
 8537: 
 8538:    if ($thisallowed=~/C/) {
 8539:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8540:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8541:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8542: 	   =~/\Q$rolecode\E/) {
 8543: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8544: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8545: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8546: 			$env{'request.course.id'});
 8547: 	   }
 8548:            return '';
 8549:        }
 8550: 
 8551:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8552: 	   =~/\Q$unamedom\E/) {
 8553: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8554: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8555: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8556: 			$env{'request.course.id'});
 8557: 	   }
 8558:            return '';
 8559:        }
 8560:    }
 8561: 
 8562: # Resource preferences
 8563: 
 8564:    if ($thisallowed=~/R/) {
 8565:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8566:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8567: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8568: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8569: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8570: 	   }
 8571: 	   return '';
 8572:        }
 8573:    }
 8574: 
 8575: # Restricted by state or randomout?
 8576: 
 8577:    if ($thisallowed=~/X/) {
 8578:       if ($env{'acc.randomout'}) {
 8579: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8580:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8581:             return ''; 
 8582:          }
 8583:       }
 8584:       if (&condval($statecond)) {
 8585: 	 return '2';
 8586:       } else {
 8587:          return '';
 8588:       }
 8589:    }
 8590: 
 8591:     if ($thisallowed eq 'A') {
 8592: 	return 'A';
 8593:     } elsif ($thisallowed eq 'B') {
 8594:         return 'B';
 8595:     } elsif ($thisallowed eq 'D') {
 8596:         return 'D';
 8597:     }
 8598:    return 'F';
 8599: }
 8600: 
 8601: # ------------------------------------------- Check construction space access
 8602: 
 8603: sub constructaccess {
 8604:     my ($url,$setpriv)=@_;
 8605: 
 8606: # We do not allow editing of previous versions of files
 8607:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8608: 
 8609: # Get username and domain from URL
 8610:     my ($ownername,$ownerdomain,$ownerhome);
 8611: 
 8612:     ($ownerdomain,$ownername) =
 8613:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8614: 
 8615: # The URL does not really point to any authorspace, forget it
 8616:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8617: 
 8618: # Now we need to see if the user has access to the authorspace of
 8619: # $ownername at $ownerdomain
 8620: 
 8621:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8622: # Real author for this?
 8623:        $ownerhome = $env{'user.home'};
 8624:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8625:           return ($ownername,$ownerdomain,$ownerhome);
 8626:        }
 8627:     } else {
 8628: # Co-author for this?
 8629:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8630:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8631:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8632:             return ($ownername,$ownerdomain,$ownerhome);
 8633:         }
 8634:         if ($env{'request.course.id'}) {
 8635:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8636:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8637:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8638:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8639:                     return ($ownername,$ownerdomain,$ownerhome);
 8640:                 }
 8641:             }
 8642:         }
 8643:     }
 8644: 
 8645: # We don't have any access right now. If we are not possibly going to do anything about this,
 8646: # we might as well leave
 8647:    unless ($setpriv) { return ''; }
 8648: 
 8649: # Backdoor access?
 8650:     my $allowed=&allowed('eco',$ownerdomain);
 8651: # Nope
 8652:     unless ($allowed) { return ''; }
 8653: # Looks like we may have access, but could be locked by the owner of the construction space
 8654:     if ($allowed eq 'U') {
 8655:         my %blocked=&get('environment',['domcoord.author'],
 8656:                          $ownerdomain,$ownername);
 8657: # Is blocked by owner
 8658:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8659:     }
 8660:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8661: # Grant temporary access
 8662:         my $then=$env{'user.login.time'};
 8663:         my $update=$env{'user.update.time'};
 8664:         if (!$update) { $update = $then; }
 8665:         my $refresh=$env{'user.refresh.time'};
 8666:         if (!$refresh) { $refresh = $update; }
 8667:         my $now = time;
 8668:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8669:                            $now,'ca','constructaccess');
 8670:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8671:         return($ownername,$ownerdomain,$ownerhome);
 8672:     }
 8673: # No business here
 8674:     return '';
 8675: }
 8676: 
 8677: # ----------------------------------------------------------- Content Blocking
 8678: 
 8679: {
 8680: # Caches for faster Course Contents display where content blocking
 8681: # is in operation (i.e., interval param set) for timed quiz.
 8682: #
 8683: # User for whom data are being temporarily cached.
 8684: my $cacheduser='';
 8685: # Course for which data are being temporarily cached.
 8686: my $cachedcid='';
 8687: # Cached blockers for this user (a hash of blocking items). 
 8688: my %cachedblockers=();
 8689: # When the data were last cached.
 8690: my $cachedlast='';
 8691: 
 8692: sub load_all_blockers {
 8693:     my ($uname,$udom)=@_;
 8694:     if (($uname ne '') && ($udom ne '')) { 
 8695:         if (($cacheduser eq $uname.':'.$udom) &&
 8696:             ($cachedcid eq $env{'request.course.id'}) &&
 8697:             (abs($cachedlast-time)<5)) {
 8698:             return;
 8699:         }
 8700:     }
 8701:     $cachedlast=time;
 8702:     $cacheduser=$uname.':'.$udom;
 8703:     $cachedcid=$env{'request.course.id'};
 8704:     %cachedblockers = &get_commblock_resources();
 8705:     return;
 8706: }
 8707: 
 8708: sub get_comm_blocks {
 8709:     my ($cdom,$cnum) = @_;
 8710:     if ($cdom eq '' || $cnum eq '') {
 8711:         return unless ($env{'request.course.id'});
 8712:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8713:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8714:     }
 8715:     my %commblocks;
 8716:     my $hashid=$cdom.'_'.$cnum;
 8717:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8718:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8719:         %commblocks = %{$blocksref};
 8720:     } else {
 8721:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8722:         my $cachetime = 600;
 8723:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8724:     }
 8725:     return %commblocks;
 8726: }
 8727: 
 8728: sub get_commblock_resources {
 8729:     my ($blocks) = @_;
 8730:     my %blockers = ();
 8731:     return %blockers unless ($env{'request.course.id'});
 8732:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8733:     my %commblocks;
 8734:     if (ref($blocks) eq 'HASH') {
 8735:         %commblocks = %{$blocks};
 8736:     } else {
 8737:         %commblocks = &get_comm_blocks();
 8738:     }
 8739:     return %blockers unless (keys(%commblocks) > 0); 
 8740:     my $navmap = Apache::lonnavmaps::navmap->new();
 8741:     return %blockers unless (ref($navmap));
 8742:     my $now = time;
 8743:     foreach my $block (keys(%commblocks)) {
 8744:         if ($block =~ /^(\d+)____(\d+)$/) {
 8745:             my ($start,$end) = ($1,$2);
 8746:             if ($start <= $now && $end >= $now) {
 8747:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8748:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8749:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8750:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8751:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8752:                             }
 8753:                         }
 8754:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8755:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8756:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8757:                             }
 8758:                         }
 8759:                     }
 8760:                 }
 8761:             }
 8762:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8763:             my $item = $1;
 8764:             my @to_test;
 8765:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8766:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8767:                     my @interval;
 8768:                     my $type = 'map';
 8769:                     if ($item eq 'course') {
 8770:                         $type = 'course';
 8771:                         @interval=&EXT("resource.0.interval");
 8772:                     } else {
 8773:                         if ($item =~ /___\d+___/) {
 8774:                             $type = 'resource';
 8775:                             @interval=&EXT("resource.0.interval",$item);
 8776:                             if (ref($navmap)) {                        
 8777:                                 my $res = $navmap->getBySymb($item); 
 8778:                                 push(@to_test,$res);
 8779:                             }
 8780:                         } else {
 8781:                             my $mapsymb = &symbread($item,1);
 8782:                             if ($mapsymb) {
 8783:                                 if (ref($navmap)) {
 8784:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8785:                                     if (ref($mapres)) {
 8786:                                         my $first = $mapres->map_start();
 8787:                                         my $finish = $mapres->map_finish();
 8788:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
 8789:                                         if (ref($it)) {
 8790:                                             my $res;
 8791:                                             while ($res = $it->next(undef,1)) {
 8792:                                                 next unless (ref($res));
 8793:                                                 my $symb = $res->symb();
 8794:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
 8795:                                                 @interval=&EXT("resource.0.interval",$symb);
 8796:                                                 if ($interval[1] eq 'map') {
 8797:                                                     if ($res->answerable()) {
 8798:                                                         push(@to_test,$res);
 8799:                                                         last;
 8800:                                                     }
 8801:                                                 }
 8802:                                             }
 8803:                                         }
 8804:                                     }
 8805:                                 }
 8806:                             }
 8807:                         }
 8808:                     }
 8809:                     if ($interval[0] =~ /^(\d+)/) {
 8810:                         my $timelimit = $1; 
 8811:                         my $first_access;
 8812:                         if ($type eq 'resource') {
 8813:                             $first_access=&get_first_access($interval[1],$item);
 8814:                         } elsif ($type eq 'map') {
 8815:                             $first_access=&get_first_access($interval[1],undef,$item);
 8816:                         } else {
 8817:                             $first_access=&get_first_access($interval[1]);
 8818:                         }
 8819:                         if ($first_access) {
 8820:                             my $timesup = $first_access+$timelimit;
 8821:                             if ($timesup > $now) {
 8822:                                 my $activeblock;
 8823:                                 foreach my $res (@to_test) {
 8824:                                     if ($res->answerable()) {
 8825:                                         $activeblock = 1;
 8826:                                         last;
 8827:                                     }
 8828:                                 }
 8829:                                 if ($activeblock) {
 8830:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8831:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8832:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8833:                                          }
 8834:                                     }
 8835:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8836:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8837:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8838:                                         }
 8839:                                     }
 8840:                                 }
 8841:                             }
 8842:                         }
 8843:                     }
 8844:                 }
 8845:             }
 8846:         }
 8847:     }
 8848:     return %blockers;
 8849: }
 8850: 
 8851: sub has_comm_blocking {
 8852:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 8853:     my @blockers;
 8854:     return unless ($env{'request.course.id'});
 8855:     return unless ($priv eq 'bre');
 8856:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8857:     return if ($env{'request.state'} eq 'construct');
 8858:     my %blockinfo;
 8859:     if (ref($blocks) eq 'HASH') {
 8860:         %blockinfo = &get_commblock_resources($blocks);
 8861:     } else {
 8862:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 8863:         %blockinfo = %cachedblockers;
 8864:     }
 8865:     return unless (keys(%blockinfo) > 0);
 8866:     my (%possibles,@symbs);
 8867:     if (!$symb) {
 8868:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 8869:     }
 8870:     if ($symb) {
 8871:         @symbs = ($symb);
 8872:     } elsif (keys(%possibles)) { 
 8873:         @symbs = keys(%possibles);
 8874:     }
 8875:     my $noblock;
 8876:     foreach my $symb (@symbs) {
 8877:         last if ($noblock);
 8878:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8879:         foreach my $block (keys(%blockinfo)) {
 8880:             if ($block =~ /^firstaccess____(.+)$/) {
 8881:                 my $item = $1;
 8882:                 unless ($blocked) {
 8883:                     if (($item eq $map) || ($item eq $symb)) {
 8884:                         $noblock = 1;
 8885:                         last;
 8886:                     }
 8887:                 }
 8888:             }
 8889:             if (ref($blockinfo{$block}) eq 'HASH') {
 8890:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 8891:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 8892:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8893:                             push(@blockers,$block);
 8894:                         }
 8895:                     }
 8896:                 }
 8897:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 8898:                     if ($blockinfo{$block}{'maps'}{$map}) {
 8899:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8900:                             push(@blockers,$block);
 8901:                         }
 8902:                     }
 8903:                 }
 8904:             }
 8905:         }
 8906:     }
 8907:     unless ($noblock) { 
 8908:         return @blockers;
 8909:     }
 8910:     return;
 8911: }
 8912: }
 8913: 
 8914: sub deeplink_check {
 8915:     my ($priv,$symb,$uri) = @_;
 8916:     return unless ($env{'request.course.id'});
 8917:     return unless ($priv eq 'bre');
 8918:     return if ($env{'request.state'} eq 'construct');
 8919:     return if ($env{'request.role.adv'});
 8920:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8921:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8922:     my (%possibles,@symbs);
 8923:     if (!$symb) {
 8924:         $symb = &symbread($uri,1,1,1,\%possibles);
 8925:     }
 8926:     if ($symb) {
 8927:         @symbs = ($symb);
 8928:     } elsif (keys(%possibles)) {
 8929:         @symbs = keys(%possibles);
 8930:     }
 8931: 
 8932:     my ($login,$switchrole,$allow);
 8933:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8934:         my $key = $1;
 8935:         my $tinyurl;
 8936:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8937:         if (defined($cached)) {
 8938:              $tinyurl = $result;
 8939:         } else {
 8940:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8941:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8942:              if ($currtiny{$key} ne '') {
 8943:                  $tinyurl = $currtiny{$key};
 8944:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8945:              }
 8946:         }
 8947:         if ($tinyurl ne '') {
 8948:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 8949:             if ($cnumreq eq $cnum) {
 8950:                 $login = $posslogin;
 8951:             } else {
 8952:                 $switchrole = 1;
 8953:             }
 8954:         }
 8955:     }
 8956:     foreach my $symb (@symbs) {
 8957:         last if ($allow);
 8958:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8959:         if ($deeplink eq '') {
 8960:             $allow = 1;
 8961:         } else {
 8962:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 8963:             if ($access eq 'any') {
 8964:                 $allow = 1;
 8965:             } elsif ($login) {
 8966:                 if ($access eq 'only') {
 8967:                     if ($scope eq 'res') {
 8968:                         if ($symb eq $login) {
 8969:                             $allow = 1;
 8970:                         }
 8971:                     } elsif ($scope eq 'map') {
 8972: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 8973:                     } elsif ($scope eq 'rec') {
 8974: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 8975:                     }
 8976:                 } else {
 8977:                     my ($acctype,$item) = split(/:/,$access);
 8978:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 8979:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 8980:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8981:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 8982:                                 $allow = 1;
 8983:                             }
 8984:                         }
 8985:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 8986:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 8987:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8988:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 8989:                                 $allow = 1;
 8990:                             }
 8991:                         }
 8992:                     }
 8993:                 }
 8994:             }
 8995:         }
 8996:     }
 8997:     return if ($allow);
 8998:     return 1;
 8999: }
 9000: 
 9001: # -------------------------------- Deversion and split uri into path an filename   
 9002: 
 9003: #
 9004: #   Removes the version from a URI and
 9005: #   splits it in to its filename and path to the filename.
 9006: #   Seems like File::Basename could have done this more clearly.
 9007: #   Parameters:
 9008: #      $uri   - input URI
 9009: #   Returns:
 9010: #     Two element list consisting of 
 9011: #     $pathname  - the URI up to and excluding the trailing /
 9012: #     $filename  - The part of the URI following the last /
 9013: #  NOTE:
 9014: #    Another realization of this is simply:
 9015: #    use File::Basename;
 9016: #    ...
 9017: #    $uri = shift;
 9018: #    $filename = basename($uri);
 9019: #    $path     = dirname($uri);
 9020: #    return ($filename, $path);
 9021: #
 9022: #     The implementation below is probably faster however.
 9023: #
 9024: sub split_uri_for_cond {
 9025:     my $uri=&deversion(&declutter(shift));
 9026:     my @uriparts=split(/\//,$uri);
 9027:     my $filename=pop(@uriparts);
 9028:     my $pathname=join('/',@uriparts);
 9029:     return ($pathname,$filename);
 9030: }
 9031: # --------------------------------------------------- Is a resource on the map?
 9032: 
 9033: sub is_on_map {
 9034:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9035:     #Trying to find the conditional for the file
 9036:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9037: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9038:     if ($match) {
 9039: 	return (1,$1);
 9040:     } else {
 9041: 	return (0,0);
 9042:     }
 9043: }
 9044: 
 9045: # --------------------------------------------------------- Get symb from alias
 9046: 
 9047: sub get_symb_from_alias {
 9048:     my $symb=shift;
 9049:     my ($map,$resid,$url)=&decode_symb($symb);
 9050: # Already is a symb
 9051:     if ($url) { return $symb; }
 9052: # Must be an alias
 9053:     my $aliassymb='';
 9054:     my %bighash;
 9055:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9056:                             &GDBM_READER(),0640)) {
 9057:         my $rid=$bighash{'mapalias_'.$symb};
 9058: 	if ($rid) {
 9059: 	    my ($mapid,$resid)=split(/\./,$rid);
 9060: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9061: 				    $resid,$bighash{'src_'.$rid});
 9062: 	}
 9063:         untie %bighash;
 9064:     }
 9065:     return $aliassymb;
 9066: }
 9067: 
 9068: # ----------------------------------------------------------------- Define Role
 9069: 
 9070: sub definerole {
 9071:   if (allowed('mcr','/')) {
 9072:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9073:     foreach my $role (split(':',$sysrole)) {
 9074: 	my ($crole,$cqual)=split(/\&/,$role);
 9075:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9076:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9077: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9078:                return "refused:s:$crole&$cqual"; 
 9079:             }
 9080:         }
 9081:     }
 9082:     foreach my $role (split(':',$domrole)) {
 9083: 	my ($crole,$cqual)=split(/\&/,$role);
 9084:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9085:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9086: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9087:                return "refused:d:$crole&$cqual"; 
 9088:             }
 9089:         }
 9090:     }
 9091:     foreach my $role (split(':',$courole)) {
 9092: 	my ($crole,$cqual)=split(/\&/,$role);
 9093:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9094:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9095: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9096:                return "refused:c:$crole&$cqual"; 
 9097:             }
 9098:         }
 9099:     }
 9100:     my $uhome;
 9101:     if (($uname ne '') && ($udom ne '')) {
 9102:         $uhome = &homeserver($uname,$udom);
 9103:         return $uhome if ($uhome eq 'no_host');
 9104:     } else {
 9105:         $uname = $env{'user.name'};
 9106:         $udom = $env{'user.domain'};
 9107:         $uhome = $env{'user.home'};
 9108:     }
 9109:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9110:                 "$udom:$uname:rolesdef_$rolename=".
 9111:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9112:     return reply($command,$uhome);
 9113:   } else {
 9114:     return 'refused';
 9115:   }
 9116: }
 9117: 
 9118: # ---------------- Make a metadata query against the network of library servers
 9119: 
 9120: sub metadata_query {
 9121:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9122:     my %rhash;
 9123:     my %libserv = &all_library();
 9124:     my @server_list = (defined($server_array) ? @$server_array
 9125:                                               : keys(%libserv) );
 9126:     for my $server (@server_list) {
 9127:         my $domains = ''; 
 9128:         if (ref($domains_hash) eq 'HASH') {
 9129:             $domains = $domains_hash->{$server}; 
 9130:         }
 9131: 	unless ($custom or $customshow) {
 9132: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9133: 	    $rhash{$server}=$reply;
 9134: 	}
 9135: 	else {
 9136: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9137: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9138: 			     $server);
 9139: 	    $rhash{$server}=$reply;
 9140: 	}
 9141:     }
 9142:     return \%rhash;
 9143: }
 9144: 
 9145: # ----------------------------------------- Send log queries and wait for reply
 9146: 
 9147: sub log_query {
 9148:     my ($uname,$udom,$query,%filters)=@_;
 9149:     my $uhome=&homeserver($uname,$udom);
 9150:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9151:     my $uhost=&hostname($uhome);
 9152:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9153:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9154:                        $uhome);
 9155:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9156:     return get_query_reply($queryid);
 9157: }
 9158: 
 9159: # -------------------------- Update MySQL table for portfolio file
 9160: 
 9161: sub update_portfolio_table {
 9162:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9163:     if ($group ne '') {
 9164:         $file_name =~s /^\Q$group\E//;
 9165:     }
 9166:     my $homeserver = &homeserver($uname,$udom);
 9167:     my $queryid=
 9168:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9169:                ':'.&escape($file_name).':'.$action,$homeserver);
 9170:     my $reply = &get_query_reply($queryid);
 9171:     return $reply;
 9172: }
 9173: 
 9174: # -------------------------- Update MySQL allusers table
 9175: 
 9176: sub update_allusers_table {
 9177:     my ($uname,$udom,$names) = @_;
 9178:     my $homeserver = &homeserver($uname,$udom);
 9179:     my $queryid=
 9180:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9181:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9182:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9183:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9184:                'generation='.&escape($names->{'generation'}).'%%'.
 9185:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9186:                'id='.&escape($names->{'id'}),$homeserver);
 9187:     return;
 9188: }
 9189: 
 9190: # ------- Request retrieval of institutional classlists for course(s)
 9191: 
 9192: sub fetch_enrollment_query {
 9193:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9194:     my ($homeserver,$sleep,$loopmax);
 9195:     my $maxtries = 1;
 9196:     if ($context eq 'automated') {
 9197:         $homeserver = $perlvar{'lonHostID'};
 9198:         $sleep = 2;
 9199:         $loopmax = 100;
 9200:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9201:     } else {
 9202:         $homeserver = &homeserver($cnum,$dom);
 9203:     }
 9204:     my $host=&hostname($homeserver);
 9205:     my $cmd = '';
 9206:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9207:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9208:     }
 9209:     $cmd =~ s/%%$//;
 9210:     $cmd = &escape($cmd);
 9211:     my $query = 'fetchenrollment';
 9212:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9213:     unless ($queryid=~/^\Q$host\E\_/) { 
 9214:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9215:         return 'error: '.$queryid;
 9216:     }
 9217:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9218:     my $tries = 1;
 9219:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9220:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9221:         $tries ++;
 9222:     }
 9223:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9224:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9225:     } else {
 9226:         my @responses = split(/:/,$reply);
 9227:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9228:             foreach my $line (@responses) {
 9229:                 my ($key,$value) = split(/=/,$line,2);
 9230:                 $$replyref{$key} = $value;
 9231:             }
 9232:         } else {
 9233:             my $pathname = LONCAPA::tempdir();
 9234:             foreach my $line (@responses) {
 9235:                 my ($key,$value) = split(/=/,$line);
 9236:                 $$replyref{$key} = $value;
 9237:                 if ($value > 0) {
 9238:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9239:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9240:                         my $destname = $pathname.'/'.$filename;
 9241:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9242:                         if ($xml_classlist =~ /^error/) {
 9243:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9244:                         } else {
 9245:                             if ( open(FILE,">",$destname) ) {
 9246:                                 print FILE &unescape($xml_classlist);
 9247:                                 close(FILE);
 9248:                             } else {
 9249:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9250:                             }
 9251:                         }
 9252:                     }
 9253:                 }
 9254:             }
 9255:         }
 9256:         return 'ok';
 9257:     }
 9258:     return 'error';
 9259: }
 9260: 
 9261: sub get_query_reply {
 9262:     my ($queryid,$sleep,$loopmax) = @_;;
 9263:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9264:         $sleep = 0.2;
 9265:     }
 9266:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9267:         $loopmax = 100;
 9268:     }
 9269:     my $replyfile=LONCAPA::tempdir().$queryid;
 9270:     my $reply='';
 9271:     for (1..$loopmax) {
 9272: 	sleep($sleep);
 9273:         if (-e $replyfile.'.end') {
 9274: 	    if (open(my $fh,"<",$replyfile)) {
 9275: 		$reply = join('',<$fh>);
 9276: 		close($fh);
 9277: 	   } else { return 'error: reply_file_error'; }
 9278:            return &unescape($reply);
 9279: 	}
 9280:     }
 9281:     return 'timeout:'.$queryid;
 9282: }
 9283: 
 9284: sub courselog_query {
 9285: #
 9286: # possible filters:
 9287: # url: url or symb
 9288: # username
 9289: # domain
 9290: # action: view, submit, grade
 9291: # start: timestamp
 9292: # end: timestamp
 9293: #
 9294:     my (%filters)=@_;
 9295:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9296:     if ($filters{'url'}) {
 9297: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9298:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9299:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9300:     }
 9301:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9302:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9303:     return &log_query($cname,$cdom,'courselog',%filters);
 9304: }
 9305: 
 9306: sub userlog_query {
 9307: #
 9308: # possible filters:
 9309: # action: log check role
 9310: # start: timestamp
 9311: # end: timestamp
 9312: #
 9313:     my ($uname,$udom,%filters)=@_;
 9314:     return &log_query($uname,$udom,'userlog',%filters);
 9315: }
 9316: 
 9317: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9318: 
 9319: sub auto_run {
 9320:     my ($cnum,$cdom) = @_;
 9321:     my $response = 0;
 9322:     my $settings;
 9323:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9324:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9325:         $settings = $domconfig{'autoenroll'};
 9326:         if ($settings->{'run'} eq '1') {
 9327:             $response = 1;
 9328:         }
 9329:     } else {
 9330:         my $homeserver;
 9331:         if (&is_course($cdom,$cnum)) {
 9332:             $homeserver = &homeserver($cnum,$cdom);
 9333:         } else {
 9334:             $homeserver = &domain($cdom,'primary');
 9335:         }
 9336:         if ($homeserver ne 'no_host') {
 9337:             $response = &reply('autorun:'.$cdom,$homeserver);
 9338:         }
 9339:     }
 9340:     return $response;
 9341: }
 9342: 
 9343: sub auto_get_sections {
 9344:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9345:     my $homeserver;
 9346:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9347:         $homeserver = &homeserver($cnum,$cdom);
 9348:     }
 9349:     if (!defined($homeserver)) { 
 9350:         if ($cdom =~ /^$match_domain$/) {
 9351:             $homeserver = &domain($cdom,'primary');
 9352:         }
 9353:     }
 9354:     my @secs;
 9355:     if (defined($homeserver)) {
 9356:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9357:         unless ($response eq 'refused') {
 9358:             @secs = split(/:/,$response);
 9359:         }
 9360:     }
 9361:     return @secs;
 9362: }
 9363: 
 9364: sub auto_new_course {
 9365:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9366:     my $homeserver = &homeserver($cnum,$cdom);
 9367:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9368:     return $response;
 9369: }
 9370: 
 9371: sub auto_validate_courseID {
 9372:     my ($cnum,$cdom,$inst_course_id) = @_;
 9373:     my $homeserver = &homeserver($cnum,$cdom);
 9374:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9375:     return $response;
 9376: }
 9377: 
 9378: sub auto_validate_instcode {
 9379:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9380:     my ($homeserver,$response);
 9381:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9382:         $homeserver = &homeserver($cnum,$cdom);
 9383:     }
 9384:     if (!defined($homeserver)) {
 9385:         if ($cdom =~ /^$match_domain$/) {
 9386:             $homeserver = &domain($cdom,'primary');
 9387:         }
 9388:     }
 9389:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9390:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9391:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9392:     return ($outcome,$description,$defaultcredits);
 9393: }
 9394: 
 9395: sub auto_create_password {
 9396:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9397:     my ($homeserver,$response);
 9398:     my $create_passwd = 0;
 9399:     my $authchk = '';
 9400:     if ($udom =~ /^$match_domain$/) {
 9401:         $homeserver = &domain($udom,'primary');
 9402:     }
 9403:     if ($homeserver eq '') {
 9404:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9405:             $homeserver = &homeserver($cnum,$cdom);
 9406:         }
 9407:     }
 9408:     if ($homeserver eq '') {
 9409:         $authchk = 'nodomain';
 9410:     } else {
 9411:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9412:         if ($response eq 'refused') {
 9413:             $authchk = 'refused';
 9414:         } else {
 9415:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9416:         }
 9417:     }
 9418:     return ($authparam,$create_passwd,$authchk);
 9419: }
 9420: 
 9421: sub auto_photo_permission {
 9422:     my ($cnum,$cdom,$students) = @_;
 9423:     my $homeserver = &homeserver($cnum,$cdom);
 9424:     my ($outcome,$perm_reqd,$conditions) = 
 9425: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9426:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9427: 	return (undef,undef);
 9428:     }
 9429:     return ($outcome,$perm_reqd,$conditions);
 9430: }
 9431: 
 9432: sub auto_checkphotos {
 9433:     my ($uname,$udom,$pid) = @_;
 9434:     my $homeserver = &homeserver($uname,$udom);
 9435:     my ($result,$resulttype);
 9436:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9437: 				   &escape($uname).':'.&escape($pid),
 9438: 				   $homeserver));
 9439:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9440: 	return (undef,undef);
 9441:     }
 9442:     if ($outcome) {
 9443:         ($result,$resulttype) = split(/:/,$outcome);
 9444:     } 
 9445:     return ($result,$resulttype);
 9446: }
 9447: 
 9448: sub auto_photochoice {
 9449:     my ($cnum,$cdom) = @_;
 9450:     my $homeserver = &homeserver($cnum,$cdom);
 9451:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9452: 						       &escape($cdom),
 9453: 						       $homeserver)));
 9454:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9455: 	return (undef,undef);
 9456:     }
 9457:     return ($update,$comment);
 9458: }
 9459: 
 9460: sub auto_photoupdate {
 9461:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9462:     my $homeserver = &homeserver($cnum,$dom);
 9463:     my $host=&hostname($homeserver);
 9464:     my $cmd = '';
 9465:     my $maxtries = 1;
 9466:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9467:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9468:     }
 9469:     $cmd =~ s/%%$//;
 9470:     $cmd = &escape($cmd);
 9471:     my $query = 'institutionalphotos';
 9472:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9473:     unless ($queryid=~/^\Q$host\E\_/) {
 9474:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9475:         return 'error: '.$queryid;
 9476:     }
 9477:     my $reply = &get_query_reply($queryid);
 9478:     my $tries = 1;
 9479:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9480:         $reply = &get_query_reply($queryid);
 9481:         $tries ++;
 9482:     }
 9483:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9484:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9485:     } else {
 9486:         my @responses = split(/:/,$reply);
 9487:         my $outcome = shift(@responses); 
 9488:         foreach my $item (@responses) {
 9489:             my ($key,$value) = split(/=/,$item);
 9490:             $$photo{$key} = $value;
 9491:         }
 9492:         return $outcome;
 9493:     }
 9494:     return 'error';
 9495: }
 9496: 
 9497: sub auto_instcode_format {
 9498:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9499: 	$cat_order) = @_;
 9500:     my $courses = '';
 9501:     my @homeservers;
 9502:     if ($caller eq 'global') {
 9503: 	my %servers = &get_servers($codedom,'library');
 9504: 	foreach my $tryserver (keys(%servers)) {
 9505: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9506: 		push(@homeservers,$tryserver);
 9507: 	    }
 9508:         }
 9509:     } elsif ($caller eq 'requests') {
 9510:         if ($codedom =~ /^$match_domain$/) {
 9511:             my $chome = &domain($codedom,'primary');
 9512:             unless ($chome eq 'no_host') {
 9513:                 push(@homeservers,$chome);
 9514:             }
 9515:         }
 9516:     } else {
 9517:         push(@homeservers,&homeserver($caller,$codedom));
 9518:     }
 9519:     foreach my $code (keys(%{$instcodes})) {
 9520:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9521:     }
 9522:     chop($courses);
 9523:     my $ok_response = 0;
 9524:     my $response;
 9525:     while (@homeservers > 0 && $ok_response == 0) {
 9526:         my $server = shift(@homeservers); 
 9527:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9528:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9529:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9530: 		split(/:/,$response);
 9531:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9532:             push(@{$codetitles},&str2array($codetitles_str));
 9533:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9534:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9535:             $ok_response = 1;
 9536:         }
 9537:     }
 9538:     if ($ok_response) {
 9539:         return 'ok';
 9540:     } else {
 9541:         return $response;
 9542:     }
 9543: }
 9544: 
 9545: sub auto_instcode_defaults {
 9546:     my ($domain,$returnhash,$code_order) = @_;
 9547:     my @homeservers;
 9548: 
 9549:     my %servers = &get_servers($domain,'library');
 9550:     foreach my $tryserver (keys(%servers)) {
 9551: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9552: 	    push(@homeservers,$tryserver);
 9553: 	}
 9554:     }
 9555: 
 9556:     my $response;
 9557:     foreach my $server (@homeservers) {
 9558:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9559:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9560: 	
 9561: 	foreach my $pair (split(/\&/,$response)) {
 9562: 	    my ($name,$value)=split(/\=/,$pair);
 9563: 	    if ($name eq 'code_order') {
 9564: 		@{$code_order} = split(/\&/,&unescape($value));
 9565: 	    } else {
 9566: 		$returnhash->{&unescape($name)}=&unescape($value);
 9567: 	    }
 9568: 	}
 9569: 	return 'ok';
 9570:     }
 9571: 
 9572:     return $response;
 9573: }
 9574: 
 9575: sub auto_possible_instcodes {
 9576:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9577:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9578:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9579:         return;
 9580:     }
 9581:     my (@homeservers,$uhome);
 9582:     if (defined(&domain($domain,'primary'))) {
 9583:         $uhome=&domain($domain,'primary');
 9584:         push(@homeservers,&domain($domain,'primary'));
 9585:     } else {
 9586:         my %servers = &get_servers($domain,'library');
 9587:         foreach my $tryserver (keys(%servers)) {
 9588:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9589:                 push(@homeservers,$tryserver);
 9590:             }
 9591:         }
 9592:     }
 9593:     my $response;
 9594:     foreach my $server (@homeservers) {
 9595:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9596:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9597:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9598:             split(':',$response);
 9599:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9600:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9601:         foreach my $item (split('&',$cat_title)) {   
 9602:             my ($name,$value)=split('=',$item);
 9603:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9604:         }
 9605:         foreach my $item (split('&',$cat_order)) {
 9606:             my ($name,$value)=split('=',$item);
 9607:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9608:         }
 9609:         return 'ok';
 9610:     }
 9611:     return $response;
 9612: }
 9613: 
 9614: sub auto_courserequest_checks {
 9615:     my ($dom) = @_;
 9616:     my ($homeserver,%validations);
 9617:     if ($dom =~ /^$match_domain$/) {
 9618:         $homeserver = &domain($dom,'primary');
 9619:     }
 9620:     unless ($homeserver eq 'no_host') {
 9621:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9622:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9623:             my @items = split(/&/,$response);
 9624:             foreach my $item (@items) {
 9625:                 my ($key,$value) = split('=',$item);
 9626:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9627:             }
 9628:         }
 9629:     }
 9630:     return %validations; 
 9631: }
 9632: 
 9633: sub auto_courserequest_validation {
 9634:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9635:     my ($homeserver,$response);
 9636:     if ($dom =~ /^$match_domain$/) {
 9637:         $homeserver = &domain($dom,'primary');
 9638:     }
 9639:     unless ($homeserver eq 'no_host') {
 9640:         my $customdata;
 9641:         if (ref($custominfo) eq 'HASH') {
 9642:             $customdata = &freeze_escape($custominfo);
 9643:         }
 9644:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9645:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9646:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9647:                                     $customdata,$homeserver));
 9648:     }
 9649:     return $response;
 9650: }
 9651: 
 9652: sub auto_validate_class_sec {
 9653:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9654:     my $homeserver = &homeserver($cnum,$cdom);
 9655:     my $ownerlist;
 9656:     if (ref($owners) eq 'ARRAY') {
 9657:         $ownerlist = join(',',@{$owners});
 9658:     } else {
 9659:         $ownerlist = $owners;
 9660:     }
 9661:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9662:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9663:     return $response;
 9664: }
 9665: 
 9666: sub auto_validate_instclasses {
 9667:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9668:     my ($homeserver,%validations);
 9669:     $homeserver = &homeserver($cnum,$cdom);
 9670:     unless ($homeserver eq 'no_host') {
 9671:         my $ownerlist;
 9672:         if (ref($owners) eq 'ARRAY') {
 9673:             $ownerlist = join(',',@{$owners});
 9674:         } else {
 9675:             $ownerlist = $owners;
 9676:         }
 9677:         if (ref($classesref) eq 'HASH') {
 9678:             my $classes = &freeze_escape($classesref);
 9679:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9680:                                 ':'.$cdom.':'.$classes,$homeserver);
 9681:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9682:                 my @items = split(/&/,$response);
 9683:                 foreach my $item (@items) {
 9684:                     my ($key,$value) = split('=',$item);
 9685:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9686:                 }
 9687:             }
 9688:         }
 9689:     }
 9690:     return %validations;
 9691: }
 9692: 
 9693: sub auto_crsreq_update {
 9694:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9695:         $code,$accessstart,$accessend,$inbound) = @_;
 9696:     my ($homeserver,%crsreqresponse);
 9697:     if ($cdom =~ /^$match_domain$/) {
 9698:         $homeserver = &domain($cdom,'primary');
 9699:     }
 9700:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9701:         my $info;
 9702:         if (ref($inbound) eq 'HASH') {
 9703:             $info = &freeze_escape($inbound);
 9704:         }
 9705:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9706:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9707:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9708:                             &escape($title).':'.&escape($code).':'.
 9709:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9710:                             $homeserver);
 9711:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9712:             my @items = split(/&/,$response);
 9713:             foreach my $item (@items) {
 9714:                 my ($key,$value) = split('=',$item);
 9715:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9716:             }
 9717:         }
 9718:     }
 9719:     return \%crsreqresponse;
 9720: }
 9721: 
 9722: sub auto_export_grades {
 9723:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9724:     my ($homeserver,%exportresponse);
 9725:     if ($cdom =~ /^$match_domain$/) {
 9726:         $homeserver = &domain($cdom,'primary');
 9727:     }
 9728:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9729:         my $info;
 9730:         if (ref($inforef) eq 'HASH') {
 9731:             $info = &freeze_escape($inforef);
 9732:         }
 9733:         if (ref($gradesref) eq 'HASH') {
 9734:             my $grades = &freeze_escape($gradesref);
 9735:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9736:                                 $info.':'.$grades,$homeserver);
 9737:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9738:                 my @items = split(/&/,$response);
 9739:                 foreach my $item (@items) {
 9740:                     my ($key,$value) = split('=',$item);
 9741:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9742:                 }
 9743:             }
 9744:         }
 9745:     }
 9746:     return \%exportresponse;
 9747: }
 9748: 
 9749: sub check_instcode_cloning {
 9750:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9751:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9752:         return;
 9753:     }
 9754:     my $canclone;
 9755:     if (@{$code_order} > 0) {
 9756:         my $instcoderegexp ='^';
 9757:         my @clonecodes = split(/\&/,$cloner);
 9758:         foreach my $item (@{$code_order}) {
 9759:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9760:                 foreach my $pair (@clonecodes) {
 9761:                     my ($key,$val) = split(/\=/,$pair,2);
 9762:                     $val = &unescape($val);
 9763:                     if ($key eq $item) {
 9764:                         $instcoderegexp .= '('.$val.')';
 9765:                         last;
 9766:                     }
 9767:                 }
 9768:             } else {
 9769:                 $instcoderegexp .= $codedefaults->{$item};
 9770:             }
 9771:         }
 9772:         $instcoderegexp .= '$';
 9773:         my (@from,@to);
 9774:         eval {
 9775:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9776:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9777:         };
 9778:         if ((@from > 0) && (@to > 0)) {
 9779:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9780:             if (!@diffs) {
 9781:                 $canclone = 1;
 9782:             }
 9783:         }
 9784:     }
 9785:     return $canclone;
 9786: }
 9787: 
 9788: sub default_instcode_cloning {
 9789:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9790:     my (%codedefaults,@code_order,$canclone);
 9791:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9792:         %codedefaults = %{$codedefaultsref};
 9793:         @code_order = @{$codeorderref};
 9794:     } elsif ($clonedom) {
 9795:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9796:     }
 9797:     if (($domdefclone) && (@code_order)) {
 9798:         my @clonecodes = split(/\+/,$domdefclone);
 9799:         my $instcoderegexp ='^';
 9800:         foreach my $item (@code_order) {
 9801:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9802:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9803:             } else {
 9804:                 $instcoderegexp .= $codedefaults{$item};
 9805:             }
 9806:         }
 9807:         $instcoderegexp .= '$';
 9808:         my (@from,@to);
 9809:         eval {
 9810:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9811:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9812:         };
 9813:         if ((@from > 0) && (@to > 0)) {
 9814:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9815:             if (!@diffs) {
 9816:                 $canclone = 1;
 9817:             }
 9818:         }
 9819:     }
 9820:     return $canclone;
 9821: }
 9822: 
 9823: # ------------------------------------------------------- Course Group routines
 9824: 
 9825: sub get_coursegroups {
 9826:     my ($cdom,$cnum,$group,$namespace) = @_;
 9827:     return(&dump($namespace,$cdom,$cnum,$group));
 9828: }
 9829: 
 9830: sub modify_coursegroup {
 9831:     my ($cdom,$cnum,$groupsettings) = @_;
 9832:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9833: }
 9834: 
 9835: sub toggle_coursegroup_status {
 9836:     my ($cdom,$cnum,$group,$action) = @_;
 9837:     my ($from_namespace,$to_namespace);
 9838:     if ($action eq 'delete') {
 9839:         $from_namespace = 'coursegroups';
 9840:         $to_namespace = 'deleted_groups';
 9841:     } else {
 9842:         $from_namespace = 'deleted_groups';
 9843:         $to_namespace = 'coursegroups';
 9844:     }
 9845:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9846:     if (my $tmp = &error(%curr_group)) {
 9847:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9848:         return ('read error',$tmp);
 9849:     } else {
 9850:         my %savedsettings = %curr_group; 
 9851:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9852:         my $deloutcome;
 9853:         if ($result eq 'ok') {
 9854:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9855:         } else {
 9856:             return ('write error',$result);
 9857:         }
 9858:         if ($deloutcome eq 'ok') {
 9859:             return 'ok';
 9860:         } else {
 9861:             return ('delete error',$deloutcome);
 9862:         }
 9863:     }
 9864: }
 9865: 
 9866: sub modify_group_roles {
 9867:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9868:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9869:     my $role = 'gr/'.&escape($userprivs);
 9870:     my ($uname,$udom) = split(/:/,$user);
 9871:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9872:     if ($result eq 'ok') {
 9873:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9874:     }
 9875:     return $result;
 9876: }
 9877: 
 9878: sub modify_coursegroup_membership {
 9879:     my ($cdom,$cnum,$membership) = @_;
 9880:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9881:     return $result;
 9882: }
 9883: 
 9884: sub get_active_groups {
 9885:     my ($udom,$uname,$cdom,$cnum) = @_;
 9886:     my $now = time;
 9887:     my %groups = ();
 9888:     foreach my $key (keys(%env)) {
 9889:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9890:             my ($start,$end) = split(/\./,$env{$key});
 9891:             if (($end!=0) && ($end<$now)) { next; }
 9892:             if (($start!=0) && ($start>$now)) { next; }
 9893:             if ($1 eq $cdom && $2 eq $cnum) {
 9894:                 $groups{$3} = $env{$key} ;
 9895:             }
 9896:         }
 9897:     }
 9898:     return %groups;
 9899: }
 9900: 
 9901: sub get_group_membership {
 9902:     my ($cdom,$cnum,$group) = @_;
 9903:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9904: }
 9905: 
 9906: sub get_users_groups {
 9907:     my ($udom,$uname,$courseid) = @_;
 9908:     my @usersgroups;
 9909:     my $cachetime=1800;
 9910: 
 9911:     my $hashid="$udom:$uname:$courseid";
 9912:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9913:     if (defined($cached)) {
 9914:         @usersgroups = split(/:/,$grouplist);
 9915:     } else {  
 9916:         $grouplist = '';
 9917:         my $courseurl = &courseid_to_courseurl($courseid);
 9918:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9919:         my $access_end = $env{'course.'.$courseid.
 9920:                               '.default_enrollment_end_date'};
 9921:         my $now = time;
 9922:         foreach my $key (keys(%roleshash)) {
 9923:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9924:                 my $group = $1;
 9925:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9926:                     my $start = $2;
 9927:                     my $end = $1;
 9928:                     if ($start == -1) { next; } # deleted from group
 9929:                     if (($start!=0) && ($start>$now)) { next; }
 9930:                     if (($end!=0) && ($end<$now)) {
 9931:                         if ($access_end && $access_end < $now) {
 9932:                             if ($access_end - $end < 86400) {
 9933:                                 push(@usersgroups,$group);
 9934:                             }
 9935:                         }
 9936:                         next;
 9937:                     }
 9938:                     push(@usersgroups,$group);
 9939:                 }
 9940:             }
 9941:         }
 9942:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9943:         $grouplist = join(':',@usersgroups);
 9944:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9945:     }
 9946:     return @usersgroups;
 9947: }
 9948: 
 9949: sub devalidate_getgroups_cache {
 9950:     my ($udom,$uname,$cdom,$cnum)=@_;
 9951:     my $courseid = $cdom.'_'.$cnum;
 9952: 
 9953:     my $hashid="$udom:$uname:$courseid";
 9954:     &devalidate_cache_new('getgroups',$hashid);
 9955: }
 9956: 
 9957: # ------------------------------------------------------------------ Plain Text
 9958: 
 9959: sub plaintext {
 9960:     my ($short,$type,$cid,$forcedefault) = @_;
 9961:     if ($short =~ m{^cr/}) {
 9962: 	return (split('/',$short))[-1];
 9963:     }
 9964:     if (!defined($cid)) {
 9965:         $cid = $env{'request.course.id'};
 9966:     }
 9967:     my %rolenames = (
 9968:                       Course    => 'std',
 9969:                       Community => 'alt1',
 9970:                       Placement => 'std',
 9971:                     );
 9972:     if ($cid ne '') {
 9973:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9974:             unless ($forcedefault) {
 9975:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9976:                 &Apache::lonlocal::mt_escape(\$roletext);
 9977:                 return &Apache::lonlocal::mt($roletext);
 9978:             }
 9979:         }
 9980:     }
 9981:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9982:         (defined($rolenames{$type})) && 
 9983:         (defined($prp{$short}{$rolenames{$type}}))) {
 9984:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9985:     } elsif ($cid ne '') {
 9986:         my $crstype = $env{'course.'.$cid.'.type'};
 9987:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9988:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9989:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9990:         }
 9991:     }
 9992:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9993: }
 9994: 
 9995: # ----------------------------------------------------------------- Assign Role
 9996: 
 9997: sub assignrole {
 9998:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9999:         $context)=@_;
10000:     my $mrole;
10001:     if ($role =~ /^cr\//) {
10002:         my $cwosec=$url;
10003:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10004: 	unless (&allowed('ccr',$cwosec)) {
10005:            my $refused = 1;
10006:            if ($context eq 'requestcourses') {
10007:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10008:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10009:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10010:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10011:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10012:                            if ($crsenv{'internal.courseowner'} eq
10013:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10014:                                $refused = '';
10015:                            }
10016:                        }
10017:                    }
10018:                }
10019:            }
10020:            if ($refused) {
10021:                &logthis('Refused custom assignrole: '.
10022:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10023:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10024:                return 'refused';
10025:            }
10026:         }
10027:         $mrole='cr';
10028:     } elsif ($role =~ /^gr\//) {
10029:         my $cwogrp=$url;
10030:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10031:         unless (&allowed('mdg',$cwogrp)) {
10032:             &logthis('Refused group assignrole: '.
10033:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10034:                     $env{'user.name'}.' at '.$env{'user.domain'});
10035:             return 'refused';
10036:         }
10037:         $mrole='gr';
10038:     } else {
10039:         my $cwosec=$url;
10040:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10041:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10042:             my $refused;
10043:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10044:                 if (!(&allowed('c'.$role,$url))) {
10045:                     $refused = 1;
10046:                 }
10047:             } else {
10048:                 $refused = 1;
10049:             }
10050:             if ($refused) {
10051:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10052:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10053:                     my %crsenv;
10054:                     if ($role eq 'cc' || $role eq 'co') {
10055:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10056:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10057:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10058:                                 if ($crsenv{'internal.courseowner'} eq 
10059:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10060:                                     $refused = '';
10061:                                 }
10062:                             }
10063:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10064:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10065:                                 if ($crsenv{'internal.courseowner'} eq 
10066:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10067:                                     $refused = '';
10068:                                 }
10069:                             }
10070:                         }
10071:                     }
10072:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10073:                     if ($role eq 'st') {
10074:                         $refused = '';
10075:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10076:                         $refused = '';
10077:                     }
10078:                 } elsif ($context eq 'requestcourses') {
10079:                     my @possroles = ('st','ta','ep','in','cc','co');
10080:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10081:                         my $wrongcc;
10082:                         if ($cnum =~ /^$match_community$/) {
10083:                             $wrongcc = 1 if ($role eq 'cc');
10084:                         } else {
10085:                             $wrongcc = 1 if ($role eq 'co');
10086:                         }
10087:                         unless ($wrongcc) {
10088:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10089:                             if ($crsenv{'internal.courseowner'} eq 
10090:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10091:                                 $refused = '';
10092:                             }
10093:                         }
10094:                     }
10095:                 } elsif ($context eq 'requestauthor') {
10096:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10097:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10098:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10099:                             $refused = '';
10100:                         } else {
10101:                             my %domdefaults = &get_domain_defaults($udom);
10102:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10103:                                 my $checkbystatus;
10104:                                 if ($env{'user.adv'}) { 
10105:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10106:                                     if ($disposition eq 'automatic') {
10107:                                         $refused = '';
10108:                                     } elsif ($disposition eq '') {
10109:                                         $checkbystatus = 1;
10110:                                     } 
10111:                                 } else {
10112:                                     $checkbystatus = 1;
10113:                                 }
10114:                                 if ($checkbystatus) {
10115:                                     if ($env{'environment.inststatus'}) {
10116:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10117:                                         foreach my $type (@inststatuses) {
10118:                                             if (($type ne '') &&
10119:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10120:                                                 $refused = '';
10121:                                             }
10122:                                         }
10123:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10124:                                         $refused = '';
10125:                                     }
10126:                                 }
10127:                             }
10128:                         }
10129:                     }
10130:                 }
10131:                 if ($refused) {
10132:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10133:                              ' '.$role.' '.$end.' '.$start.' by '.
10134: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10135:                     return 'refused';
10136:                 }
10137:             }
10138:         } elsif ($role eq 'au') {
10139:             if ($url ne '/'.$udom.'/') {
10140:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10141:                          ' to assign author role for '.$uname.':'.$udom.
10142:                          ' in domain: '.$url.' refused (wrong domain).');
10143:                 return 'refused';
10144:             }
10145:         }
10146:         $mrole=$role;
10147:     }
10148:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10149:                 "$udom:$uname:$url".'_'."$mrole=$role";
10150:     if ($end) { $command.='_'.$end; }
10151:     if ($start) {
10152: 	if ($end) { 
10153:            $command.='_'.$start; 
10154:         } else {
10155:            $command.='_0_'.$start;
10156:         }
10157:     }
10158:     my $origstart = $start;
10159:     my $origend = $end;
10160:     my $delflag;
10161: # actually delete
10162:     if ($deleteflag) {
10163: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10164: # modify command to delete the role
10165:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10166:                 "$udom:$uname:$url".'_'."$mrole";
10167: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10168: # set start and finish to negative values for userrolelog
10169:            $start=-1;
10170:            $end=-1;
10171:            $delflag = 1;
10172:         }
10173:     }
10174: # send command
10175:     my $answer=&reply($command,&homeserver($uname,$udom));
10176: # log new user role if status is ok
10177:     if ($answer eq 'ok') {
10178: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10179:         if (($role eq 'cc') || ($role eq 'in') ||
10180:             ($role eq 'ep') || ($role eq 'ad') ||
10181:             ($role eq 'ta') || ($role eq 'st') ||
10182:             ($role=~/^cr/) || ($role eq 'gr') ||
10183:             ($role eq 'co')) {
10184: # for course roles, perform group memberships changes triggered by role change.
10185:             unless ($role =~ /^gr/) {
10186:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10187:                                                  $origstart,$selfenroll,$context);
10188:             }
10189:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10190:                            $selfenroll,$context);
10191:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10192:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10193:                  ($role eq 'da')) {
10194:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10195:                            $context);
10196:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10197:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10198:                              $context); 
10199:         }
10200:         if ($role eq 'cc') {
10201:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10202:         }
10203:     }
10204:     return $answer;
10205: }
10206: 
10207: sub autoupdate_coowners {
10208:     my ($url,$end,$start,$uname,$udom) = @_;
10209:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10210:     if (($cdom ne '') && ($cnum ne '')) {
10211:         my $now = time;
10212:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10213:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10214:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10215:             my $instcode = $coursehash{'internal.coursecode'};
10216:             if ($instcode ne '') {
10217:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10218:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10219:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10220:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10221:                         if ($result eq 'valid') {
10222:                             if ($coursehash{'internal.co-owners'}) {
10223:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10224:                                     push(@newcoowners,$coowner);
10225:                                 }
10226:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10227:                                     push(@newcoowners,$uname.':'.$udom);
10228:                                 }
10229:                                 @newcoowners = sort(@newcoowners);
10230:                             } else {
10231:                                 push(@newcoowners,$uname.':'.$udom);
10232:                             }
10233:                         } else {
10234:                             if ($coursehash{'internal.co-owners'}) {
10235:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10236:                                     unless ($coowner eq $uname.':'.$udom) {
10237:                                         push(@newcoowners,$coowner);
10238:                                     }
10239:                                 }
10240:                                 unless (@newcoowners > 0) {
10241:                                     $delcoowners = 1;
10242:                                     $coowners = '';
10243:                                 }
10244:                             }
10245:                         }
10246:                         if (@newcoowners || $delcoowners) {
10247:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10248:                                             $delcoowners,@newcoowners);
10249:                         }
10250:                     }
10251:                 }
10252:             }
10253:         }
10254:     }
10255: }
10256: 
10257: sub store_coowners {
10258:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10259:     my $cid = $cdom.'_'.$cnum;
10260:     my ($coowners,$delresult,$putresult);
10261:     if (@newcoowners) {
10262:         $coowners = join(',',@newcoowners);
10263:         my %coownershash = (
10264:                             'internal.co-owners' => $coowners,
10265:                            );
10266:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10267:         if ($putresult eq 'ok') {
10268:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10269:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10270:             }
10271:         }
10272:     }
10273:     if ($delcoowners) {
10274:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10275:         if ($delresult eq 'ok') {
10276:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10277:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10278:             }
10279:         }
10280:     }
10281:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10282:         my %crsinfo =
10283:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10284:         if (ref($crsinfo{$cid}) eq 'HASH') {
10285:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10286:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10287:         }
10288:     }
10289: }
10290: 
10291: # -------------------------------------------------- Modify user authentication
10292: # Overrides without validation
10293: 
10294: sub modifyuserauth {
10295:     my ($udom,$uname,$umode,$upass)=@_;
10296:     my $uhome=&homeserver($uname,$udom);
10297:     my $allowed;
10298:     if (&allowed('mau',$udom)) {
10299:         $allowed = 1;
10300:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10301:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10302:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10303:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10304:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10305:         if (($cdom ne '') && ($cnum ne '')) {
10306:             my $is_owner = &is_course_owner($cdom,$cnum);
10307:             if ($is_owner) {
10308:                 $allowed = 1;
10309:             }
10310:         }
10311:     }
10312:     unless ($allowed) { return 'refused'; }
10313:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10314:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10315:              ' in domain '.$env{'request.role.domain'});  
10316:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10317: 		     &escape($upass),$uhome);
10318:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10319:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10320:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10321:     &log($udom,,$uname,$uhome,
10322:         'Authentication changed by '.$env{'user.domain'}.', '.
10323:                                      $env{'user.name'}.', '.$umode.
10324:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10325:     unless ($reply eq 'ok') {
10326:         &logthis('Authentication mode error: '.$reply);
10327: 	return 'error: '.$reply;
10328:     }   
10329:     return 'ok';
10330: }
10331: 
10332: # --------------------------------------------------------------- Modify a user
10333: 
10334: sub modifyuser {
10335:     my ($udom,    $uname, $uid,
10336:         $umode,   $upass, $first,
10337:         $middle,  $last,  $gene,
10338:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10339:     $udom= &LONCAPA::clean_domain($udom);
10340:     $uname=&LONCAPA::clean_username($uname);
10341:     my $showcandelete = 'none';
10342:     if (ref($candelete) eq 'ARRAY') {
10343:         if (@{$candelete} > 0) {
10344:             $showcandelete = join(', ',@{$candelete});
10345:         }
10346:     }
10347:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10348:              $umode.', '.$first.', '.$middle.', '.
10349: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10350:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10351:                                      ' desiredhome not specified'). 
10352:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10353:              ' in domain '.$env{'request.role.domain'});
10354:     my $uhome=&homeserver($uname,$udom,'true');
10355:     my $newuser;
10356:     if ($uhome eq 'no_host') {
10357:         $newuser = 1;
10358:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10359:                 ($umode eq 'lti')) {
10360:             return 'error: more information needed to create new user';
10361:         }
10362:     }
10363: # ----------------------------------------------------------------- Create User
10364:     if (($uhome eq 'no_host') && 
10365: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10366:         my $unhome='';
10367:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10368:             $unhome = $desiredhome;
10369: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10370: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10371:         } else { # load balancing routine for determining $unhome
10372:             my $loadm=10000000;
10373: 	    my %servers = &get_servers($udom,'library');
10374: 	    foreach my $tryserver (keys(%servers)) {
10375: 		my $answer=reply('load',$tryserver);
10376: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10377: 		    $loadm=$answer;
10378: 		    $unhome=$tryserver;
10379: 		}
10380: 	    }
10381:         }
10382:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10383: 	    return 'error: unable to find a home server for '.$uname.
10384:                    ' in domain '.$udom;
10385:         }
10386:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10387:                          &escape($upass),$unhome);
10388: 	unless ($reply eq 'ok') {
10389:             return 'error: '.$reply;
10390:         }   
10391:         $uhome=&homeserver($uname,$udom,'true');
10392:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10393: 	    return 'error: unable verify users home machine.';
10394:         }
10395:     }   # End of creation of new user
10396: # ---------------------------------------------------------------------- Add ID
10397:     if ($uid) {
10398:        $uid=~tr/A-Z/a-z/;
10399:        my %uidhash=&idrget($udom,$uname);
10400:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10401:          && (!$forceid)) {
10402: 	  unless ($uid eq $uidhash{$uname}) {
10403: 	      return 'error: user id "'.$uid.'" does not match '.
10404:                   'current user id "'.$uidhash{$uname}.'".';
10405:           }
10406:        } else {
10407: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10408:        }
10409:     }
10410: # -------------------------------------------------------------- Add names, etc
10411:     my @tmp=&get('environment',
10412: 		   ['firstname','middlename','lastname','generation','id',
10413:                     'permanentemail','inststatus'],
10414: 		   $udom,$uname);
10415:     my (%names,%oldnames);
10416:     if ($tmp[0] =~ m/^error:.*/) { 
10417:         %names=(); 
10418:     } else {
10419:         %names = @tmp;
10420:         %oldnames = %names;
10421:     }
10422: #
10423: # If name, email and/or uid are blank (e.g., because an uploaded file
10424: # of users did not contain them), do not overwrite existing values
10425: # unless field is in $candelete array ref.  
10426: #
10427: 
10428:     my @fields = ('firstname','middlename','lastname','generation',
10429:                   'permanentemail','id');
10430:     my %newvalues;
10431:     if (ref($candelete) eq 'ARRAY') {
10432:         foreach my $field (@fields) {
10433:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10434:                 if ($field eq 'firstname') {
10435:                     $names{$field} = $first;
10436:                 } elsif ($field eq 'middlename') {
10437:                     $names{$field} = $middle;
10438:                 } elsif ($field eq 'lastname') {
10439:                     $names{$field} = $last;
10440:                 } elsif ($field eq 'generation') { 
10441:                     $names{$field} = $gene;
10442:                 } elsif ($field eq 'permanentemail') {
10443:                     $names{$field} = $email;
10444:                 } elsif ($field eq 'id') {
10445:                     $names{$field}  = $uid;
10446:                 }
10447:             }
10448:         }
10449:     }
10450:     if ($first)  { $names{'firstname'}  = $first; }
10451:     if (defined($middle)) { $names{'middlename'} = $middle; }
10452:     if ($last)   { $names{'lastname'}   = $last; }
10453:     if (defined($gene))   { $names{'generation'} = $gene; }
10454:     if ($email) {
10455:        $email=~s/[^\w\@\.\-\,]//gs;
10456:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10457:     }
10458:     if ($uid) { $names{'id'}  = $uid; }
10459:     if (defined($inststatus)) {
10460:         $names{'inststatus'} = '';
10461:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10462:         if (ref($usertypes) eq 'HASH') {
10463:             my @okstatuses; 
10464:             foreach my $item (split(/:/,$inststatus)) {
10465:                 if (defined($usertypes->{$item})) {
10466:                     push(@okstatuses,$item);  
10467:                 }
10468:             }
10469:             if (@okstatuses) {
10470:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10471:             }
10472:         }
10473:     }
10474:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10475:                  $umode.', '.$first.', '.$middle.', '.
10476:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10477:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10478:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10479:     } else {
10480:         $logmsg .= ' during self creation';
10481:     }
10482:     my $changed;
10483:     if ($newuser) {
10484:         $changed = 1;
10485:     } else {
10486:         foreach my $field (@fields) {
10487:             if ($names{$field} ne $oldnames{$field}) {
10488:                 $changed = 1;
10489:                 last;
10490:             }
10491:         }
10492:     }
10493:     unless ($changed) {
10494:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10495:         &logthis($logmsg);
10496:         return 'ok';
10497:     }
10498:     my $reply = &put('environment', \%names, $udom,$uname);
10499:     if ($reply ne 'ok') { 
10500:         return 'error: '.$reply;
10501:     }
10502:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10503:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10504:     }
10505:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10506:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10507:     $logmsg = 'Success modifying user '.$logmsg;
10508:     &logthis($logmsg);
10509:     return 'ok';
10510: }
10511: 
10512: # -------------------------------------------------------------- Modify student
10513: 
10514: sub modifystudent {
10515:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10516:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10517:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10518:     if (!$cid) {
10519: 	unless ($cid=$env{'request.course.id'}) {
10520: 	    return 'not_in_class';
10521: 	}
10522:     }
10523: # --------------------------------------------------------------- Make the user
10524:     my $reply=&modifyuser
10525: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10526:          $desiredhome,$email,$inststatus);
10527:     unless ($reply eq 'ok') { return $reply; }
10528:     # This will cause &modify_student_enrollment to get the uid from the
10529:     # student's environment
10530:     $uid = undef if (!$forceid);
10531:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10532:                                         $gene,$usec,$end,$start,$type,$locktype,
10533:                                         $cid,$selfenroll,$context,$credits,$instsec);
10534:     return $reply;
10535: }
10536: 
10537: sub modify_student_enrollment {
10538:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10539:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10540:     my ($cdom,$cnum,$chome);
10541:     if (!$cid) {
10542: 	unless ($cid=$env{'request.course.id'}) {
10543: 	    return 'not_in_class';
10544: 	}
10545: 	$cdom=$env{'course.'.$cid.'.domain'};
10546: 	$cnum=$env{'course.'.$cid.'.num'};
10547:     } else {
10548: 	($cdom,$cnum)=split(/_/,$cid);
10549:     }
10550:     $chome=$env{'course.'.$cid.'.home'};
10551:     if (!$chome) {
10552: 	$chome=&homeserver($cnum,$cdom);
10553:     }
10554:     if (!$chome) { return 'unknown_course'; }
10555:     # Make sure the user exists
10556:     my $uhome=&homeserver($uname,$udom);
10557:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10558: 	return 'error: no such user';
10559:     }
10560:     # Get student data if we were not given enough information
10561:     if (!defined($first)  || $first  eq '' || 
10562:         !defined($last)   || $last   eq '' || 
10563:         !defined($uid)    || $uid    eq '' || 
10564:         !defined($middle) || $middle eq '' || 
10565:         !defined($gene)   || $gene   eq '') {
10566:         # They did not supply us with enough data to enroll the student, so
10567:         # we need to pick up more information.
10568:         my %tmp = &get('environment',
10569:                        ['firstname','middlename','lastname', 'generation','id']
10570:                        ,$udom,$uname);
10571: 
10572:         #foreach my $key (keys(%tmp)) {
10573:         #    &logthis("key $key = ".$tmp{$key});
10574:         #}
10575:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10576:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10577:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10578:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10579:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10580:     }
10581:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10582:     my $user = "$uname:$udom";
10583:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10584:     my $reply=cput('classlist',
10585: 		   {$user => 
10586: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10587: 		   $cdom,$cnum);
10588:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10589:         &devalidate_getsection_cache($udom,$uname,$cid);
10590:     } else { 
10591: 	return 'error: '.$reply;
10592:     }
10593:     # Add student role to user
10594:     my $uurl='/'.$cid;
10595:     $uurl=~s/\_/\//g;
10596:     if ($usec) {
10597: 	$uurl.='/'.$usec;
10598:     }
10599:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10600:                              $selfenroll,$context);
10601:     if ($result ne 'ok') {
10602:         if ($old_entry{$user} ne '') {
10603:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10604:         } else {
10605:             $reply = &del('classlist',[$user],$cdom,$cnum);
10606:         }
10607:     }
10608:     return $result; 
10609: }
10610: 
10611: sub format_name {
10612:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10613:     my $name;
10614:     if ($first ne 'lastname') {
10615: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10616:     } else {
10617: 	if ($lastname=~/\S/) {
10618: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10619: 	    $name=~s/\s+,/,/;
10620: 	} else {
10621: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10622: 	}
10623:     }
10624:     $name=~s/^\s+//;
10625:     $name=~s/\s+$//;
10626:     $name=~s/\s+/ /g;
10627:     return $name;
10628: }
10629: 
10630: # ------------------------------------------------- Write to course preferences
10631: 
10632: sub writecoursepref {
10633:     my ($courseid,%prefs)=@_;
10634:     $courseid=~s/^\///;
10635:     $courseid=~s/\_/\//g;
10636:     my ($cdomain,$cnum)=split(/\//,$courseid);
10637:     my $chome=homeserver($cnum,$cdomain);
10638:     if (($chome eq '') || ($chome eq 'no_host')) { 
10639: 	return 'error: no such course';
10640:     }
10641:     my $cstring='';
10642:     foreach my $pref (keys(%prefs)) {
10643: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10644:     }
10645:     $cstring=~s/\&$//;
10646:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10647: }
10648: 
10649: # ---------------------------------------------------------- Make/modify course
10650: 
10651: sub createcourse {
10652:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10653:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10654:     $url=&declutter($url);
10655:     my $cid='';
10656:     if ($context eq 'requestcourses') {
10657:         my $can_create = 0;
10658:         my ($ownername,$ownerdom) = split(':',$course_owner);
10659:         if ($udom eq $ownerdom) {
10660:             my $reload;
10661:             if (($callercontext eq 'auto') &&
10662:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10663:                 $reload = 'reload';
10664:             }
10665:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10666:                                   $context)) {
10667:                 $can_create = 1;
10668:             }
10669:         } else {
10670:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10671:                                            $category);
10672:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10673:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10674:                 if (@curr > 0) {
10675:                     my @options = qw(approval validate autolimit);
10676:                     my $optregex = join('|',@options);
10677:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10678:                         $can_create = 1;
10679:                     }
10680:                 }
10681:             }
10682:         }
10683:         if ($can_create) {
10684:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10685:                 unless (&allowed('ccc',$udom)) {
10686:                     return 'refused'; 
10687:                 }
10688:             }
10689:         } else {
10690:             return 'refused';
10691:         }
10692:     } elsif (!&allowed('ccc',$udom)) {
10693:         return 'refused';
10694:     }
10695: # --------------------------------------------------------------- Get Unique ID
10696:     my $uname;
10697:     if ($cnum =~ /^$match_courseid$/) {
10698:         my $chome=&homeserver($cnum,$udom,'true');
10699:         if (($chome eq '') || ($chome eq 'no_host')) {
10700:             $uname = $cnum;
10701:         } else {
10702:             $uname = &generate_coursenum($udom,$crstype);
10703:         }
10704:     } else {
10705:         $uname = &generate_coursenum($udom,$crstype);
10706:     }
10707:     return $uname if ($uname =~ /^error/);
10708: # -------------------------------------------------- Check supplied server name
10709:     if (!defined($course_server)) {
10710:         if (defined(&domain($udom,'primary'))) {
10711:             $course_server = &domain($udom,'primary');
10712:         } else {
10713:             $course_server = $env{'user.home'}; 
10714:         }
10715:     }
10716:     my %host_servers =
10717:         &Apache::lonnet::get_servers($udom,'library');
10718:     unless ($host_servers{$course_server}) {
10719:         return 'error: invalid home server for course: '.$course_server;
10720:     }
10721: # ------------------------------------------------------------- Make the course
10722:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10723:                       $course_server);
10724:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10725:     my $uhome=&homeserver($uname,$udom,'true');
10726:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10727: 	return 'error: no such course';
10728:     }
10729: # ----------------------------------------------------------------- Course made
10730: # log existence
10731:     my $now = time;
10732:     my $newcourse = {
10733:                     $udom.'_'.$uname => {
10734:                                      description => $description,
10735:                                      inst_code   => $inst_code,
10736:                                      owner       => $course_owner,
10737:                                      type        => $crstype,
10738:                                      creator     => $env{'user.name'}.':'.
10739:                                                     $env{'user.domain'},
10740:                                      created     => $now,
10741:                                      context     => $context,
10742:                                                 },
10743:                     };
10744:     &courseidput($udom,$newcourse,$uhome,'notime');
10745: # set toplevel url
10746:     my $topurl=$url;
10747:     unless ($nonstandard) {
10748: # ------------------------------------------ For standard courses, make top url
10749:         my $mapurl=&clutter($url);
10750:         if ($mapurl eq '/res/') { $mapurl=''; }
10751:         $env{'form.initmap'}=(<<ENDINITMAP);
10752: <map>
10753: <resource id="1" type="start"></resource>
10754: <resource id="2" src="$mapurl"></resource>
10755: <resource id="3" type="finish"></resource>
10756: <link index="1" from="1" to="2"></link>
10757: <link index="2" from="2" to="3"></link>
10758: </map>
10759: ENDINITMAP
10760:         $topurl=&declutter(
10761:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10762:                           );
10763:     }
10764: # ----------------------------------------------------------- Write preferences
10765:     &writecoursepref($udom.'_'.$uname,
10766:                      ('description'              => $description,
10767:                       'url'                      => $topurl,
10768:                       'internal.creator'         => $env{'user.name'}.':'.
10769:                                                     $env{'user.domain'},
10770:                       'internal.created'         => $now,
10771:                       'internal.creationcontext' => $context)
10772:                     );
10773:     return '/'.$udom.'/'.$uname;
10774: }
10775: 
10776: # ------------------------------------------------------------------- Create ID
10777: sub generate_coursenum {
10778:     my ($udom,$crstype) = @_;
10779:     my $domdesc = &domain($udom);
10780:     return 'error: invalid domain' if ($domdesc eq '');
10781:     my $first;
10782:     if ($crstype eq 'Community') {
10783:         $first = '0';
10784:     } else {
10785:         $first = int(1+rand(9)); 
10786:     } 
10787:     my $uname=$first.
10788:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10789:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10790:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10791: # ----------------------------------------------- Make sure that does not exist
10792:     my $uhome=&homeserver($uname,$udom,'true');
10793:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10794:         if ($crstype eq 'Community') {
10795:             $first = '0';
10796:         } else {
10797:             $first = int(1+rand(9));
10798:         }
10799:         $uname=$first.
10800:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10801:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10802:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10803:         $uhome=&homeserver($uname,$udom,'true');
10804:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10805:             return 'error: unable to generate unique course-ID';
10806:         }
10807:     }
10808:     return $uname;
10809: }
10810: 
10811: sub is_course {
10812:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10813:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10814: 
10815:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10816:     my $uhome=&homeserver($cnum,$cdom);
10817:     my $iscourse;
10818:     if (grep { $_ eq $uhome } current_machine_ids()) {
10819:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10820:     } else {
10821:         my $hashid = $cdom.':'.$cnum;
10822:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10823:         unless (defined($cached)) {
10824:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10825:                                         $cnum,undef,undef,'.');
10826:             $iscourse = 0;
10827:             if (exists($courses{$cdom.'_'.$cnum})) {
10828:                 $iscourse = 1;
10829:             }
10830:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10831:         }
10832:     }
10833:     return unless ($iscourse);
10834:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10835: }
10836: 
10837: sub store_userdata {
10838:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10839:     my $result;
10840:     if ($datakey ne '') {
10841:         if (ref($storehash) eq 'HASH') {
10842:             if ($udom eq '' || $uname eq '') {
10843:                 $udom = $env{'user.domain'};
10844:                 $uname = $env{'user.name'};
10845:             }
10846:             my $uhome=&homeserver($uname,$udom);
10847:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10848:                 $result = 'error: no_host';
10849:             } else {
10850:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10851:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10852: 
10853:                 my $namevalue='';
10854:                 foreach my $key (keys(%{$storehash})) {
10855:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10856:                 }
10857:                 $namevalue=~s/\&$//;
10858:                 unless ($namespace eq 'courserequests') {
10859:                     $datakey = &escape($datakey);
10860:                 }
10861:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10862:                                   $namevalue,$uhome);
10863:             }
10864:         } else {
10865:             $result = 'error: data to store was not a hash reference'; 
10866:         }
10867:     } else {
10868:         $result= 'error: invalid requestkey'; 
10869:     }
10870:     return $result;
10871: }
10872: 
10873: # ---------------------------------------------------------- Assign Custom Role
10874: 
10875: sub assigncustomrole {
10876:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10877:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10878:                        $end,$start,$deleteflag,$selfenroll,$context);
10879: }
10880: 
10881: # ----------------------------------------------------------------- Revoke Role
10882: 
10883: sub revokerole {
10884:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10885:     my $now=time;
10886:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10887: }
10888: 
10889: # ---------------------------------------------------------- Revoke Custom Role
10890: 
10891: sub revokecustomrole {
10892:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10893:     my $now=time;
10894:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10895:            $deleteflag,$selfenroll,$context);
10896: }
10897: 
10898: # ------------------------------------------------------------ Disk usage
10899: sub diskusage {
10900:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10901:     $directorypath =~ s/\/$//;
10902:     my $listing=&reply('du2:'.&escape($directorypath).':'
10903:                        .&escape($getpropath).':'.&escape($uname).':'
10904:                        .&escape($udom),homeserver($uname,$udom));
10905:     if ($listing eq 'unknown_cmd') {
10906:         if ($getpropath) {
10907:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10908:         }
10909:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10910:     }
10911:     return $listing;
10912: }
10913: 
10914: sub is_locked {
10915:     my ($file_name, $domain, $user, $which) = @_;
10916:     my @check;
10917:     my $is_locked;
10918:     push (@check,$file_name);
10919:     my %locked = &get('file_permissions',\@check,
10920: 		      $env{'user.domain'},$env{'user.name'});
10921:     my ($tmp)=keys(%locked);
10922:     if ($tmp=~/^error:/) { undef(%locked); }
10923:     
10924:     if (ref($locked{$file_name}) eq 'ARRAY') {
10925:         $is_locked = 'false';
10926:         foreach my $entry (@{$locked{$file_name}}) {
10927:            if (ref($entry) eq 'ARRAY') {
10928:                $is_locked = 'true';
10929:                if (ref($which) eq 'ARRAY') {
10930:                    push(@{$which},$entry);
10931:                } else {
10932:                    last;
10933:                }
10934:            }
10935:        }
10936:     } else {
10937:         $is_locked = 'false';
10938:     }
10939:     return $is_locked;
10940: }
10941: 
10942: sub declutter_portfile {
10943:     my ($file) = @_;
10944:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10945:     return $file;
10946: }
10947: 
10948: # ------------------------------------------------------------- Mark as Read Only
10949: 
10950: sub mark_as_readonly {
10951:     my ($domain,$user,$files,$what) = @_;
10952:     my %current_permissions = &dump('file_permissions',$domain,$user);
10953:     my ($tmp)=keys(%current_permissions);
10954:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10955:     foreach my $file (@{$files}) {
10956: 	$file = &declutter_portfile($file);
10957:         push(@{$current_permissions{$file}},$what);
10958:     }
10959:     &put('file_permissions',\%current_permissions,$domain,$user);
10960:     return;
10961: }
10962: 
10963: # ------------------------------------------------------------Save Selected Files
10964: 
10965: sub save_selected_files {
10966:     my ($user, $path, @files) = @_;
10967:     my $filename = $user."savedfiles";
10968:     my @other_files = &files_not_in_path($user, $path);
10969:     open (OUT,'>',LONCAPA::tempdir().$filename);
10970:     foreach my $file (@files) {
10971:         print (OUT $env{'form.currentpath'}.$file."\n");
10972:     }
10973:     foreach my $file (@other_files) {
10974:         print (OUT $file."\n");
10975:     }
10976:     close (OUT);
10977:     return 'ok';
10978: }
10979: 
10980: sub clear_selected_files {
10981:     my ($user) = @_;
10982:     my $filename = $user."savedfiles";
10983:     open (OUT,'>',LONCAPA::tempdir().$filename);
10984:     print (OUT undef);
10985:     close (OUT);
10986:     return ("ok");    
10987: }
10988: 
10989: sub files_in_path {
10990:     my ($user, $path) = @_;
10991:     my $filename = $user."savedfiles";
10992:     my %return_files;
10993:     open (IN,'<',LONCAPA::tempdir().$filename);
10994:     while (my $line_in = <IN>) {
10995:         chomp ($line_in);
10996:         my @paths_and_file = split (m!/!, $line_in);
10997:         my $file_part = pop (@paths_and_file);
10998:         my $path_part = join ('/', @paths_and_file);
10999:         $path_part.='/';
11000:         my $path_and_file = $path_part.$file_part;
11001:         if ($path_part eq $path) {
11002:             $return_files{$file_part}= 'selected';
11003:         }
11004:     }
11005:     close (IN);
11006:     return (\%return_files);
11007: }
11008: 
11009: # called in portfolio select mode, to show files selected NOT in current directory
11010: sub files_not_in_path {
11011:     my ($user, $path) = @_;
11012:     my $filename = $user."savedfiles";
11013:     my @return_files;
11014:     my $path_part;
11015:     open(IN, '<',LONCAPA::tempdir().$filename);
11016:     while (my $line = <IN>) {
11017:         #ok, I know it's clunky, but I want it to work
11018:         my @paths_and_file = split(m|/|, $line);
11019:         my $file_part = pop(@paths_and_file);
11020:         chomp($file_part);
11021:         my $path_part = join('/', @paths_and_file);
11022:         $path_part .= '/';
11023:         my $path_and_file = $path_part.$file_part;
11024:         if ($path_part ne $path) {
11025:             push(@return_files, ($path_and_file));
11026:         }
11027:     }
11028:     close(OUT);
11029:     return (@return_files);
11030: }
11031: 
11032: #------------------------------Submitted/Handedback Portfolio Files Versioning
11033:  
11034: sub portfiles_versioning {
11035:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11036:     my $portfolio_root = '/userfiles/portfolio';
11037:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11038:     foreach my $file (@{$portfiles}) {
11039:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11040:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11041:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11042:         my $getpropath = 1;
11043:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11044:                                              $stu_name,$getpropath);
11045:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11046:         my $new_answer = 
11047:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11048:         if ($new_answer ne 'problem getting file') {
11049:             push(@{$versioned_portfiles}, $directory.$new_answer);
11050:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11051:                               [$symb,$env{'request.course.id'},'graded']);
11052:         }
11053:     }
11054: }
11055: 
11056: sub get_next_version {
11057:     my ($answer_name, $answer_ext, $dir_list) = @_;
11058:     my $version;
11059:     if (ref($dir_list) eq 'ARRAY') {
11060:         foreach my $row (@{$dir_list}) {
11061:             my ($file) = split(/\&/,$row,2);
11062:             my ($file_name,$file_version,$file_ext) =
11063:                 &file_name_version_ext($file);
11064:             if (($file_name eq $answer_name) &&
11065:                 ($file_ext eq $answer_ext)) {
11066:                      # gets here if filename and extension match,
11067:                      # regardless of version
11068:                 if ($file_version ne '') {
11069:                     # a versioned file is found  so save it for later
11070:                     if ($file_version > $version) {
11071:                         $version = $file_version;
11072:                     }
11073:                 }
11074:             }
11075:         }
11076:     }
11077:     $version ++;
11078:     return($version);
11079: }
11080: 
11081: sub version_selected_portfile {
11082:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11083:     my ($answer_name,$answer_ver,$answer_ext) =
11084:         &file_name_version_ext($file_name);
11085:     my $new_answer;
11086:     $env{'form.copy'} =
11087:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11088:     if($env{'form.copy'} eq '-1') {
11089:         $new_answer = 'problem getting file';
11090:     } else {
11091:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11092:         my $copy_result = 
11093:             &finishuserfileupload($stu_name,$domain,'copy',
11094:                                   '/portfolio'.$directory.$new_answer);
11095:     }
11096:     undef($env{'form.copy'});
11097:     return ($new_answer);
11098: }
11099: 
11100: sub file_name_version_ext {
11101:     my ($file)=@_;
11102:     my @file_parts = split(/\./, $file);
11103:     my ($name,$version,$ext);
11104:     if (@file_parts > 1) {
11105:         $ext=pop(@file_parts);
11106:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11107:             $version=pop(@file_parts);
11108:         }
11109:         $name=join('.',@file_parts);
11110:     } else {
11111:         $name=join('.',@file_parts);
11112:     }
11113:     return($name,$version,$ext);
11114: }
11115: 
11116: #----------------------------------------------Get portfolio file permissions
11117: 
11118: sub get_portfile_permissions {
11119:     my ($domain,$user) = @_;
11120:     my %current_permissions = &dump('file_permissions',$domain,$user);
11121:     my ($tmp)=keys(%current_permissions);
11122:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11123:     return \%current_permissions;
11124: }
11125: 
11126: #---------------------------------------------Get portfolio file access controls
11127: 
11128: sub get_access_controls {
11129:     my ($current_permissions,$group,$file) = @_;
11130:     my %access;
11131:     my $real_file = $file;
11132:     $file =~ s/\.meta$//;
11133:     if (defined($file)) {
11134:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11135:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11136:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11137:             }
11138:         }
11139:     } else {
11140:         foreach my $key (keys(%{$current_permissions})) {
11141:             if ($key =~ /\0accesscontrol$/) {
11142:                 if (defined($group)) {
11143:                     if ($key !~ m-^\Q$group\E/-) {
11144:                         next;
11145:                     }
11146:                 }
11147:                 my ($fullpath) = split(/\0/,$key);
11148:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11149:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11150:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11151:                     }
11152:                 }
11153:             }
11154:         }
11155:     }
11156:     return %access;
11157: }
11158: 
11159: sub modify_access_controls {
11160:     my ($file_name,$changes,$domain,$user)=@_;
11161:     my ($outcome,$deloutcome);
11162:     my %store_permissions;
11163:     my %new_values;
11164:     my %new_control;
11165:     my %translation;
11166:     my @deletions = ();
11167:     my $now = time;
11168:     if (exists($$changes{'activate'})) {
11169:         if (ref($$changes{'activate'}) eq 'HASH') {
11170:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11171:             my $numnew = scalar(@newitems);
11172:             for (my $i=0; $i<$numnew; $i++) {
11173:                 my $newkey = $newitems[$i];
11174:                 my $newid = &Apache::loncommon::get_cgi_id();
11175:                 if ($newkey =~ /^\d+:/) { 
11176:                     $newkey =~ s/^(\d+)/$newid/;
11177:                     $translation{$1} = $newid;
11178:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11179:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11180:                     $translation{$1} = $newid;
11181:                 }
11182:                 $new_values{$file_name."\0".$newkey} = 
11183:                                           $$changes{'activate'}{$newitems[$i]};
11184:                 $new_control{$newkey} = $now;
11185:             }
11186:         }
11187:     }
11188:     my %todelete;
11189:     my %changed_items;
11190:     foreach my $action ('delete','update') {
11191:         if (exists($$changes{$action})) {
11192:             if (ref($$changes{$action}) eq 'HASH') {
11193:                 foreach my $key (keys(%{$$changes{$action}})) {
11194:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11195:                     if ($action eq 'delete') { 
11196:                         $todelete{$itemnum} = 1;
11197:                     } else {
11198:                         $changed_items{$itemnum} = $key;
11199:                     }
11200:                 }
11201:             }
11202:         }
11203:     }
11204:     # get lock on access controls for file.
11205:     my $lockhash = {
11206:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11207:                                                        ':'.$env{'user.domain'},
11208:                    }; 
11209:     my $tries = 0;
11210:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11211:    
11212:     while (($gotlock ne 'ok') && $tries < 10) {
11213:         $tries ++;
11214:         sleep(0.1);
11215:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11216:     }
11217:     if ($gotlock eq 'ok') {
11218:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11219:         my ($tmp)=keys(%curr_permissions);
11220:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11221:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11222:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11223:             if (ref($curr_controls) eq 'HASH') {
11224:                 foreach my $control_item (keys(%{$curr_controls})) {
11225:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11226:                     if (defined($todelete{$itemnum})) {
11227:                         push(@deletions,$file_name."\0".$control_item);
11228:                     } else {
11229:                         if (defined($changed_items{$itemnum})) {
11230:                             $new_control{$changed_items{$itemnum}} = $now;
11231:                             push(@deletions,$file_name."\0".$control_item);
11232:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11233:                         } else {
11234:                             $new_control{$control_item} = $$curr_controls{$control_item};
11235:                         }
11236:                     }
11237:                 }
11238:             }
11239:         }
11240:         my ($group);
11241:         if (&is_course($domain,$user)) {
11242:             ($group,my $file) = split(/\//,$file_name,2);
11243:         }
11244:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11245:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11246:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11247:         #  remove lock
11248:         my @del_lock = ($file_name."\0".'locked_access_records');
11249:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11250:         my $sqlresult =
11251:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11252:                                     $group);
11253:     } else {
11254:         $outcome = "error: could not obtain lockfile\n";  
11255:     }
11256:     return ($outcome,$deloutcome,\%new_values,\%translation);
11257: }
11258: 
11259: sub make_public_indefinitely {
11260:     my (@requrl) = @_;
11261:     return &automated_portfile_access('public',\@requrl);
11262: }
11263: 
11264: sub automated_portfile_access {
11265:     my ($accesstype,$addsref,$delsref,$info) = @_;
11266:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11267:         return 'invalid';
11268:     }
11269:     my %urls;
11270:     if (ref($addsref) eq 'ARRAY') {
11271:         foreach my $requrl (@{$addsref}) {
11272:             if (&is_portfolio_url($requrl)) {
11273:                 unless (exists($urls{$requrl})) {
11274:                     $urls{$requrl} = 'add';
11275:                 }
11276:             }
11277:         }
11278:     }
11279:     if (ref($delsref) eq 'ARRAY') {
11280:         foreach my $requrl (@{$delsref}) { 
11281:             if (&is_portfolio_url($requrl)) {
11282:                 unless (exists($urls{$requrl})) {
11283:                     $urls{$requrl} = 'delete'; 
11284:                 }
11285:             }
11286:         }
11287:     }
11288:     unless (keys(%urls)) {
11289:         return 'invalid';
11290:     }
11291:     my $ip;
11292:     if ($accesstype eq 'ip') {
11293:         if (ref($info) eq 'HASH') {
11294:             if ($info->{'ip'} ne '') {
11295:                 $ip = $info->{'ip'};
11296:             }
11297:         }
11298:         if ($ip eq '') {
11299:             return 'invalid';
11300:         }
11301:     }
11302:     my $errors;
11303:     my $now = time;
11304:     my %current_perms;
11305:     foreach my $requrl (sort(keys(%urls))) {
11306:         my $action;
11307:         if ($urls{$requrl} eq 'add') {
11308:             $action = 'activate';
11309:         } else {
11310:             $action = 'none';
11311:         }
11312:         my $aclnum = 0;
11313:         my (undef,$udom,$unum,$file_name,$group) =
11314:             &parse_portfolio_url($requrl);
11315:         unless (exists($current_perms{$unum.':'.$udom})) {
11316:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11317:         }
11318:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11319:                                                    $group,$file_name);
11320:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11321:             my ($num,$scope,$end,$start) = 
11322:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11323:             if ($scope eq $accesstype) {
11324:                 if (($start <= $now) && ($end == 0)) {
11325:                     if ($accesstype eq 'ip') {
11326:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11327:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11328:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11329:                                     if ($urls{$requrl} eq 'add') {
11330:                                         $action = 'none';
11331:                                         last;
11332:                                     } else {
11333:                                         $action = 'delete';
11334:                                         $aclnum = $num;
11335:                                         last;
11336:                                     }
11337:                                 }
11338:                             }
11339:                         }
11340:                     } elsif ($accesstype eq 'public') {
11341:                         if ($urls{$requrl} eq 'add') {
11342:                             $action = 'none';
11343:                             last;
11344:                         } else {
11345:                             $action = 'delete';
11346:                             $aclnum = $num;
11347:                             last;
11348:                         }
11349:                     }
11350:                 } elsif ($accesstype eq 'public') {
11351:                     $action = 'update';
11352:                     $aclnum = $num;
11353:                     last;
11354:                 }
11355:             }
11356:         }
11357:         if ($action eq 'none') {
11358:             next;
11359:         } else {
11360:             my %changes;
11361:             my $newend = 0;
11362:             my $newstart = $now;
11363:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11364:             $changes{$action}{$newkey} = {
11365:                 type => $accesstype,
11366:                 time => {
11367:                     start => $newstart,
11368:                     end   => $newend,
11369:                 },
11370:             };
11371:             if ($accesstype eq 'ip') {
11372:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11373:             }
11374:             my ($outcome,$deloutcome,$new_values,$translation) =
11375:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11376:             unless ($outcome eq 'ok') {
11377:                 $errors .= $outcome.' ';
11378:             }
11379:         }
11380:     }
11381:     if ($errors) {
11382:         $errors =~ s/\s$//;
11383:         return $errors;
11384:     } else {
11385:         return 'ok';
11386:     }
11387: }
11388: 
11389: #------------------------------------------------------Get Marked as Read Only
11390: 
11391: sub get_marked_as_readonly {
11392:     my ($domain,$user,$what,$group) = @_;
11393:     my $current_permissions = &get_portfile_permissions($domain,$user);
11394:     my @readonly_files;
11395:     my $cmp1=$what;
11396:     if (ref($what)) { $cmp1=join('',@{$what}) };
11397:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11398:         if (defined($group)) {
11399:             if ($file_name !~ m-^\Q$group\E/-) {
11400:                 next;
11401:             }
11402:         }
11403:         if (ref($value) eq "ARRAY"){
11404:             foreach my $stored_what (@{$value}) {
11405:                 my $cmp2=$stored_what;
11406:                 if (ref($stored_what) eq 'ARRAY') {
11407:                     $cmp2=join('',@{$stored_what});
11408:                 }
11409:                 if ($cmp1 eq $cmp2) {
11410:                     push(@readonly_files, $file_name);
11411:                     last;
11412:                 } elsif (!defined($what)) {
11413:                     push(@readonly_files, $file_name);
11414:                     last;
11415:                 }
11416:             }
11417:         }
11418:     }
11419:     return @readonly_files;
11420: }
11421: #-----------------------------------------------------------Get Marked as Read Only Hash
11422: 
11423: sub get_marked_as_readonly_hash {
11424:     my ($current_permissions,$group,$what) = @_;
11425:     my %readonly_files;
11426:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11427:         if (defined($group)) {
11428:             if ($file_name !~ m-^\Q$group\E/-) {
11429:                 next;
11430:             }
11431:         }
11432:         if (ref($value) eq "ARRAY"){
11433:             foreach my $stored_what (@{$value}) {
11434:                 if (ref($stored_what) eq 'ARRAY') {
11435:                     foreach my $lock_descriptor(@{$stored_what}) {
11436:                         if ($lock_descriptor eq 'graded') {
11437:                             $readonly_files{$file_name} = 'graded';
11438:                         } elsif ($lock_descriptor eq 'handback') {
11439:                             $readonly_files{$file_name} = 'handback';
11440:                         } else {
11441:                             if (!exists($readonly_files{$file_name})) {
11442:                                 $readonly_files{$file_name} = 'locked';
11443:                             }
11444:                         }
11445:                     }
11446:                 } 
11447:             }
11448:         } 
11449:     }
11450:     return %readonly_files;
11451: }
11452: # ------------------------------------------------------------ Unmark as Read Only
11453: 
11454: sub unmark_as_readonly {
11455:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11456:     # for portfolio submissions, $what contains [$symb,$crsid] 
11457:     my ($domain,$user,$what,$file_name,$group) = @_;
11458:     $file_name = &declutter_portfile($file_name);
11459:     my $symb_crs = $what;
11460:     if (ref($what)) { $symb_crs=join('',@$what); }
11461:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11462:     my ($tmp)=keys(%current_permissions);
11463:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11464:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11465:     foreach my $file (@readonly_files) {
11466: 	my $clean_file = &declutter_portfile($file);
11467: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11468: 	my $current_locks = $current_permissions{$file};
11469:         my @new_locks;
11470:         my @del_keys;
11471:         if (ref($current_locks) eq "ARRAY"){
11472:             foreach my $locker (@{$current_locks}) {
11473:                 my $compare=$locker;
11474:                 if (ref($locker) eq 'ARRAY') {
11475:                     $compare=join('',@{$locker});
11476:                     if ($compare ne $symb_crs) {
11477:                         push(@new_locks, $locker);
11478:                     }
11479:                 }
11480:             }
11481:             if (scalar(@new_locks) > 0) {
11482:                 $current_permissions{$file} = \@new_locks;
11483:             } else {
11484:                 push(@del_keys, $file);
11485:                 &del('file_permissions',\@del_keys, $domain, $user);
11486:                 delete($current_permissions{$file});
11487:             }
11488:         }
11489:     }
11490:     &put('file_permissions',\%current_permissions,$domain,$user);
11491:     return;
11492: }
11493: 
11494: # ------------------------------------------------------------ Directory lister
11495: 
11496: sub dirlist {
11497:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11498:     $uri=~s/^\///;
11499:     $uri=~s/\/$//;
11500:     my ($udom, $uname);
11501:     if ($getuserdir) {
11502:         $udom = $userdomain;
11503:         $uname = $username;
11504:     } else {
11505:         (undef,$udom,$uname)=split(/\//,$uri);
11506:         if(defined($userdomain)) {
11507:             $udom = $userdomain;
11508:         }
11509:         if(defined($username)) {
11510:             $uname = $username;
11511:         }
11512:     }
11513:     my ($dirRoot,$listing,@listing_results);
11514: 
11515:     $dirRoot = $perlvar{'lonDocRoot'};
11516:     if (defined($getpropath)) {
11517:         $dirRoot = &propath($udom,$uname);
11518:         $dirRoot =~ s/\/$//;
11519:     } elsif (defined($getuserdir)) {
11520:         my $subdir=$uname.'__';
11521:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11522:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11523:                    ."/$udom/$subdir/$uname";
11524:     } elsif (defined($alternateRoot)) {
11525:         $dirRoot = $alternateRoot;
11526:     }
11527: 
11528:     if($udom) {
11529:         if($uname) {
11530:             my $uhome = &homeserver($uname,$udom);
11531:             if ($uhome eq 'no_host') {
11532:                 return ([],'no_host');
11533:             }
11534:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11535:                               .$getuserdir.':'.&escape($dirRoot)
11536:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11537:             if ($listing eq 'unknown_cmd') {
11538:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11539:             } else {
11540:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11541:             }
11542:             if ($listing eq 'unknown_cmd') {
11543:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11544:                 @listing_results = split(/:/,$listing);
11545:             } else {
11546:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11547:             }
11548:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11549:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11550:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11551:                 return ([],$listing);
11552:             } else {
11553:                 return (\@listing_results);
11554:             }
11555:         } elsif(!$alternateRoot) {
11556:             my (%allusers,%listerror);
11557: 	    my %servers = &get_servers($udom,'library');
11558:  	    foreach my $tryserver (keys(%servers)) {
11559:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11560:                                   &escape($udom),$tryserver);
11561:                 if ($listing eq 'unknown_cmd') {
11562: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11563: 				      $udom, $tryserver);
11564:                 } else {
11565:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11566:                 }
11567: 		if ($listing eq 'unknown_cmd') {
11568: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11569: 				      $udom, $tryserver);
11570: 		    @listing_results = split(/:/,$listing);
11571: 		} else {
11572: 		    @listing_results =
11573: 			map { &unescape($_); } split(/:/,$listing);
11574: 		}
11575:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11576:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11577:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11578:                     $listerror{$tryserver} = $listing;
11579:                 } else {
11580: 		    foreach my $line (@listing_results) {
11581: 			my ($entry) = split(/&/,$line,2);
11582: 			$allusers{$entry} = 1;
11583: 		    }
11584: 		}
11585:             }
11586:             my @alluserslist=();
11587:             foreach my $user (sort(keys(%allusers))) {
11588:                 push(@alluserslist,$user.'&user');
11589:             }
11590: 
11591:             if (!%listerror) {
11592:                 # no errors
11593:                 return (\@alluserslist);
11594:             } elsif (scalar(keys(%servers)) == 1) {
11595:                 # one library server, one error 
11596:                 my ($key) = keys(%listerror);
11597:                 return (\@alluserslist, $listerror{$key});
11598:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11599:                 # con_lost indicates that we might miss data from at least one
11600:                 # library server
11601:                 return (\@alluserslist, 'con_lost');
11602:             } else {
11603:                 # multiple library servers and no con_lost -> data should be
11604:                 # complete. 
11605:                 return (\@alluserslist);
11606:             }
11607: 
11608:         } else {
11609:             return ([],'missing username');
11610:         }
11611:     } elsif(!defined($getpropath)) {
11612:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11613:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11614:         return (\@all_domains);
11615:     } else {
11616:         return ([],'missing domain');
11617:     }
11618: }
11619: 
11620: # --------------------------------------------- GetFileTimestamp
11621: # This function utilizes dirlist and returns the date stamp for
11622: # when it was last modified.  It will also return an error of -1
11623: # if an error occurs
11624: 
11625: sub GetFileTimestamp {
11626:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11627:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11628:     $studentName   = &LONCAPA::clean_username($studentName);
11629:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11630:                                     undef,$getuserdir);
11631:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11632:         return -1;
11633:     }
11634:     if (ref($fileref) eq 'ARRAY') {
11635:         my @stats = split('&',$fileref->[0]);
11636:         # @stats contains first the filename, then the stat output
11637:         return $stats[10]; # so this is 10 instead of 9.
11638:     } else {
11639:         return -1;
11640:     }
11641: }
11642: 
11643: sub stat_file {
11644:     my ($uri) = @_;
11645:     $uri = &clutter_with_no_wrapper($uri);
11646: 
11647:     my ($udom,$uname,$file);
11648:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11649: 	($udom,$uname,$file) =
11650: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11651: 	$file = 'userfiles/'.$file;
11652:     }
11653:     if ($uri =~ m-^/res/-) {
11654: 	($udom,$uname) = 
11655: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11656: 	$file = $uri;
11657:     }
11658: 
11659:     if (!$udom || !$uname || !$file) {
11660: 	# unable to handle the uri
11661: 	return ();
11662:     }
11663:     my $getpropath;
11664:     if ($file =~ /^userfiles\//) {
11665:         $getpropath = 1;
11666:     }
11667:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11668:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11669:         return ();
11670:     } else {
11671:         if (ref($listref) eq 'ARRAY') {
11672:             my @stats = split('&',$listref->[0]);
11673: 	    shift(@stats); #filename is first
11674: 	    return @stats;
11675:         }
11676:     }
11677:     return ();
11678: }
11679: 
11680: # --------------------------------------------------------- recursedirs
11681: # Recursive function to traverse either a specific user's Authoring Space
11682: # or corresponding Published Resource Space, and populate the hash ref:
11683: # $dirhashref with URLs of all directories, and if $filehashref hash
11684: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11685: # or .rights files in resource space, and .meta, .save, .log, and .bak
11686: # files in Authoring Space.
11687: #
11688: # Inputs:
11689: #
11690: # $is_home - true if current server is home server for user's space
11691: # $context - either: priv, or res respectively for Authoring or Resource Space.
11692: # $docroot - Document root (i.e., /home/httpd/html
11693: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11694: # $relpath - Current path (relative to top level).
11695: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11696: # $filehashref - reference to hash to populate with URLs of files (Optional)
11697: #
11698: # Returns: nothing
11699: #
11700: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11701: #
11702: # Currently used by interface/londocs.pm to create linked select boxes for
11703: # directory and filename to import a Course "Author" resource into a course, and
11704: # also to create linked select boxes for Authoring Space and Directory to choose
11705: # save location for creation of a new "standard" problem from the Course Editor.
11706: #
11707: 
11708: sub recursedirs {
11709:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11710:     return unless (ref($dirhashref) eq 'HASH');
11711:     my $currpath = $docroot.$toppath;
11712:     if ($relpath) {
11713:         $currpath .= "/$relpath";
11714:     }
11715:     my $savefile;
11716:     if (ref($filehashref)) {
11717:         $savefile = 1;
11718:     }
11719:     if ($is_home) {
11720:         if (opendir(my $dirh,$currpath)) {
11721:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11722:                 next if ($item eq '');
11723:                 if (-d "$currpath/$item") {
11724:                     my $newpath;
11725:                     if ($relpath) {
11726:                         $newpath = "$relpath/$item";
11727:                     } else {
11728:                         $newpath = $item;
11729:                     }
11730:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11731:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11732:                 } elsif ($savefile) {
11733:                     if ($context eq 'priv') {
11734:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11735:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11736:                         }
11737:                     } else {
11738:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11739:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11740:                         }
11741:                     }
11742:                 }
11743:             }
11744:             closedir($dirh);
11745:         }
11746:     } else {
11747:         my ($dirlistref,$listerror) =
11748:             &dirlist($toppath.$relpath);
11749:         my @dir_lines;
11750:         my $dirptr=16384;
11751:         if (ref($dirlistref) eq 'ARRAY') {
11752:             foreach my $dir_line (sort
11753:                               {
11754:                                   my ($afile)=split('&',$a,2);
11755:                                   my ($bfile)=split('&',$b,2);
11756:                                   return (lc($afile) cmp lc($bfile));
11757:                               } (@{$dirlistref})) {
11758:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11759:                     split(/\&/,$dir_line,16);
11760:                 $item =~ s/\s+$//;
11761:                 next if (($item =~ /^\.\.?$/) || ($obs));
11762:                 if ($dirptr&$testdir) {
11763:                     my $newpath;
11764:                     if ($relpath) {
11765:                         $newpath = "$relpath/$item";
11766:                     } else {
11767:                         $relpath = '/';
11768:                         $newpath = $item;
11769:                     }
11770:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11771:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11772:                 } elsif ($savefile) {
11773:                     if ($context eq 'priv') {
11774:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11775:                             $filehashref->{$relpath}{$item} = 1;
11776:                         }
11777:                     } else {
11778:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11779:                             $filehashref->{$relpath}{$item} = 1;
11780:                         }
11781:                     }
11782:                 }
11783:             }
11784:         }
11785:     }
11786:     return;
11787: }
11788: 
11789: # -------------------------------------------------------- Value of a Condition
11790: 
11791: # gets the value of a specific preevaluated condition
11792: #    stored in the string  $env{user.state.<cid>}
11793: # or looks up a condition reference in the bighash and if if hasn't
11794: # already been evaluated recurses into docondval to get the value of
11795: # the condition, then memoizing it to 
11796: #   $env{user.state.<cid>.<condition>}
11797: sub directcondval {
11798:     my $number=shift;
11799:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11800: 	&Apache::lonuserstate::evalstate();
11801:     }
11802:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11803: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11804:     } elsif ($number =~ /^_/) {
11805: 	my $sub_condition;
11806: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11807: 		&GDBM_READER(),0640)) {
11808: 	    $sub_condition=$bighash{'conditions'.$number};
11809: 	    untie(%bighash);
11810: 	}
11811: 	my $value = &docondval($sub_condition);
11812: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11813: 	return $value;
11814:     }
11815:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11816:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11817:     } else {
11818:        return 2;
11819:     }
11820: }
11821: 
11822: # get the collection of conditions for this resource
11823: sub condval {
11824:     my $condidx=shift;
11825:     my $allpathcond='';
11826:     foreach my $cond (split(/\|/,$condidx)) {
11827: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11828: 	    $allpathcond.=
11829: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11830: 	}
11831:     }
11832:     $allpathcond=~s/\|$//;
11833:     return &docondval($allpathcond);
11834: }
11835: 
11836: #evaluates an expression of conditions
11837: sub docondval {
11838:     my ($allpathcond) = @_;
11839:     my $result=0;
11840:     if ($env{'request.course.id'}
11841: 	&& defined($allpathcond)) {
11842: 	my $operand='|';
11843: 	my @stack;
11844: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11845: 	    if ($chunk eq '(') {
11846: 		push @stack,($operand,$result);
11847: 	    } elsif ($chunk eq ')') {
11848: 		my $before=pop @stack;
11849: 		if (pop @stack eq '&') {
11850: 		    $result=$result>$before?$before:$result;
11851: 		} else {
11852: 		    $result=$result>$before?$result:$before;
11853: 		}
11854: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11855: 		$operand=$chunk;
11856: 	    } else {
11857: 		my $new=directcondval($chunk);
11858: 		if ($operand eq '&') {
11859: 		    $result=$result>$new?$new:$result;
11860: 		} else {
11861: 		    $result=$result>$new?$result:$new;
11862: 		}
11863: 	    }
11864: 	}
11865:     }
11866:     return $result;
11867: }
11868: 
11869: # ---------------------------------------------------- Devalidate courseresdata
11870: 
11871: sub devalidatecourseresdata {
11872:     my ($coursenum,$coursedomain)=@_;
11873:     my $hashid=$coursenum.':'.$coursedomain;
11874:     &devalidate_cache_new('courseres',$hashid);
11875: }
11876: 
11877: 
11878: # --------------------------------------------------- Course Resourcedata Query
11879: #
11880: #  Parameters:
11881: #      $coursenum    - Number of the course.
11882: #      $coursedomain - Domain at which the course was created.
11883: #  Returns:
11884: #     A hash of the course parameters along (I think) with timestamps
11885: #     and version info.
11886: 
11887: sub get_courseresdata {
11888:     my ($coursenum,$coursedomain)=@_;
11889:     my $coursehom=&homeserver($coursenum,$coursedomain);
11890:     my $hashid=$coursenum.':'.$coursedomain;
11891:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11892:     my %dumpreply;
11893:     unless (defined($cached)) {
11894: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11895: 	$result=\%dumpreply;
11896: 	my ($tmp) = keys(%dumpreply);
11897: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11898: 	    &do_cache_new('courseres',$hashid,$result,600);
11899: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11900: 	    return $tmp;
11901: 	} elsif ($tmp =~ /^(error)/) {
11902: 	    $result=undef;
11903: 	    &do_cache_new('courseres',$hashid,$result,600);
11904: 	}
11905:     }
11906:     return $result;
11907: }
11908: 
11909: sub devalidateuserresdata {
11910:     my ($uname,$udom)=@_;
11911:     my $hashid="$udom:$uname";
11912:     &devalidate_cache_new('userres',$hashid);
11913: }
11914: 
11915: sub get_userresdata {
11916:     my ($uname,$udom)=@_;
11917:     #most student don\'t have any data set, check if there is some data
11918:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11919: 
11920:     my $hashid="$udom:$uname";
11921:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11922:     if (!defined($cached)) {
11923: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11924: 	$result=\%resourcedata;
11925: 	&do_cache_new('userres',$hashid,$result,600);
11926:     }
11927:     my ($tmp)=keys(%$result);
11928:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11929: 	return $result;
11930:     }
11931:     #error 2 occurs when the .db doesn't exist
11932:     if ($tmp!~/error: 2 /) {
11933:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11934: 	    &logthis("<font color=\"blue\">WARNING:".
11935: 		     " Trying to get resource data for ".
11936: 		     $uname." at ".$udom.": ".
11937: 		     $tmp."</font>");
11938:         }
11939:     } elsif ($tmp=~/error: 2 /) {
11940: 	#&EXT_cache_set($udom,$uname);
11941: 	&do_cache_new('userres',$hashid,undef,600);
11942: 	undef($tmp); # not really an error so don't send it back
11943:     }
11944:     return $tmp;
11945: }
11946: #----------------------------------------------- resdata - return resource data
11947: #  Purpose:
11948: #    Return resource data for either users or for a course.
11949: #  Parameters:
11950: #     $name      - Course/user name.
11951: #     $domain    - Name of the domain the user/course is registered on.
11952: #     $type      - Type of thing $name is (must be 'course' or 'user')
11953: #     $mapp      - decluttered URL of enclosing map  
11954: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11955: #     $recurseup - Ref to array of map URLs, starting with map containing
11956: #                  $mapp up through hierarchy of nested maps to top level map.  
11957: #     $courseid  - CourseID (first part of param identifier).
11958: #     $modifier  - Middle part of param identifier.
11959: #     $what      - Last part of param identifier.
11960: #     @which     - Array of names of resources desired.
11961: #  Returns:
11962: #     The value of the first reasource in @which that is found in the
11963: #     resource hash.
11964: #  Exceptional Conditions:
11965: #     If the $type passed in is not valid (not the string 'course' or 
11966: #     'user', an undefined  reference is returned.
11967: #     If none of the resources are found, an undef is returned
11968: sub resdata {
11969:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11970:         $modifier,$what,@which)=@_;
11971:     my $result;
11972:     if ($type eq 'course') {
11973: 	$result=&get_courseresdata($name,$domain);
11974:     } elsif ($type eq 'user') {
11975: 	$result=&get_userresdata($name,$domain);
11976:     }
11977:     if (!ref($result)) { return $result; }    
11978:     foreach my $item (@which) {
11979:         if ($item->[1] eq 'course') {
11980:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11981:                 unless ($$recursed) {
11982:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11983:                     $$recursed = 1;
11984:                 }
11985:                 foreach my $item (@${recurseup}) {
11986:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11987:                     last if (defined($result->{$norecursechk}));
11988:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11989:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11990:                 }
11991:             }
11992:         }
11993:         if (defined($result->{$item->[0]})) {
11994: 	    return [$result->{$item->[0]},$item->[1]];
11995: 	}
11996:     }
11997:     return undef;
11998: }
11999: 
12000: sub get_domain_lti {
12001:     my ($cdom,$context) = @_;
12002:     my ($name,%lti);
12003:     if ($context eq 'consumer') {
12004:         $name = 'ltitools';
12005:     } elsif ($context eq 'provider') {
12006:         $name = 'lti';
12007:     } else {
12008:         return %lti;
12009:     }
12010:     my ($result,$cached)=&is_cached_new($name,$cdom);
12011:     if (defined($cached)) {
12012:         if (ref($result) eq 'HASH') {
12013:             %lti = %{$result};
12014:         }
12015:     } else {
12016:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12017:         if (ref($domconfig{$name}) eq 'HASH') {
12018:             %lti = %{$domconfig{$name}};
12019:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
12020:             if (ref($encdomconfig{$name}) eq 'HASH') {
12021:                 foreach my $id (keys(%lti)) {
12022:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12023:                         foreach my $item ('key','secret') {
12024:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12025:                         }
12026:                     }
12027:                 }
12028:             }
12029:         }
12030:         my $cachetime = 24*60*60;
12031:         &do_cache_new($name,$cdom,\%lti,$cachetime);
12032:     }
12033:     return %lti;
12034: }
12035: 
12036: sub get_numsuppfiles {
12037:     my ($cnum,$cdom,$ignorecache)=@_;
12038:     my $hashid=$cnum.':'.$cdom;
12039:     my ($suppcount,$cached);
12040:     unless ($ignorecache) {
12041:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12042:     }
12043:     unless (defined($cached)) {
12044:         my $chome=&homeserver($cnum,$cdom);
12045:         unless ($chome eq 'no_host') {
12046:             ($suppcount,my $supptools,my $errors) = (0,0,0);
12047:             my $suppmap = 'supplemental.sequence';
12048:             ($suppcount,$supptools,$errors) =
12049:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12050:                                                          $supptools,$errors);
12051:         }
12052:         &do_cache_new('suppcount',$hashid,$suppcount,600);
12053:     }
12054:     return $suppcount;
12055: }
12056: 
12057: #
12058: # EXT resource caching routines
12059: #
12060: 
12061: {
12062: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12063: #
12064: # The course for which we cache
12065: my $cachedmapkey='';
12066: # The cached recursive maps for this course
12067: my %cachedmaps=();
12068: # When this was last done
12069: my $cachedmaptime='';
12070: 
12071: sub clear_EXT_cache_status {
12072:     &delenv('cache.EXT.');
12073: }
12074: 
12075: sub EXT_cache_status {
12076:     my ($target_domain,$target_user) = @_;
12077:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12078:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12079:         # We know already the user has no data
12080:         return 1;
12081:     } else {
12082:         return 0;
12083:     }
12084: }
12085: 
12086: sub EXT_cache_set {
12087:     my ($target_domain,$target_user) = @_;
12088:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12089:     #&appenv({$cachename => time});
12090: }
12091: 
12092: # --------------------------------------------------------- Value of a Variable
12093: sub EXT {
12094: 
12095:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
12096:     unless ($varname) { return ''; }
12097:     #get real user name/domain, courseid and symb
12098:     my $courseid;
12099:     my $publicuser;
12100:     if ($symbparm) {
12101: 	$symbparm=&get_symb_from_alias($symbparm);
12102:     }
12103:     if (!($uname && $udom)) {
12104:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12105:       if (!$symbparm) {	$symbparm=$cursymb; }
12106:     } else {
12107: 	$courseid=$env{'request.course.id'};
12108:     }
12109:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12110:     my $rest;
12111:     if (defined($therest[0])) {
12112:        $rest=join('.',@therest);
12113:     } else {
12114:        $rest='';
12115:     }
12116: 
12117:     my $qualifierrest=$qualifier;
12118:     if ($rest) { $qualifierrest.='.'.$rest; }
12119:     my $spacequalifierrest=$space;
12120:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12121:     if ($realm eq 'user') {
12122: # --------------------------------------------------------------- user.resource
12123: 	if ($space eq 'resource') {
12124: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12125: 		  || defined($Apache::lonhomework::parsing_a_task))
12126: 		 &&
12127: 		 ($symbparm eq &symbread()) ) {	
12128: 		# if we are in the middle of processing the resource the
12129: 		# get the value we are planning on committing
12130:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12131:                     return $Apache::lonhomework::results{$qualifierrest};
12132:                 } else {
12133:                     return $Apache::lonhomework::history{$qualifierrest};
12134:                 }
12135: 	    } else {
12136: 		my %restored;
12137: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12138: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12139: 		} else {
12140: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12141: 		}
12142: 		return $restored{$qualifierrest};
12143: 	    }
12144: # ----------------------------------------------------------------- user.access
12145:         } elsif ($space eq 'access') {
12146: 	    # FIXME - not supporting calls for a specific user
12147:             return &allowed($qualifier,$rest);
12148: # ------------------------------------------ user.preferences, user.environment
12149:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12150: 	    if (($uname eq $env{'user.name'}) &&
12151: 		($udom eq $env{'user.domain'})) {
12152: 		return $env{join('.',('environment',$qualifierrest))};
12153: 	    } else {
12154: 		my %returnhash;
12155: 		if (!$publicuser) {
12156: 		    %returnhash=&userenvironment($udom,$uname,
12157: 						 $qualifierrest);
12158: 		}
12159: 		return $returnhash{$qualifierrest};
12160: 	    }
12161: # ----------------------------------------------------------------- user.course
12162:         } elsif ($space eq 'course') {
12163: 	    # FIXME - not supporting calls for a specific user
12164:             return $env{join('.',('request.course',$qualifier))};
12165: # ------------------------------------------------------------------- user.role
12166:         } elsif ($space eq 'role') {
12167: 	    # FIXME - not supporting calls for a specific user
12168:             my ($role,$where)=split(/\./,$env{'request.role'});
12169:             if ($qualifier eq 'value') {
12170: 		return $role;
12171:             } elsif ($qualifier eq 'extent') {
12172:                 return $where;
12173:             }
12174: # ----------------------------------------------------------------- user.domain
12175:         } elsif ($space eq 'domain') {
12176:             return $udom;
12177: # ------------------------------------------------------------------- user.name
12178:         } elsif ($space eq 'name') {
12179:             return $uname;
12180: # ---------------------------------------------------- Any other user namespace
12181:         } else {
12182: 	    my %reply;
12183: 	    if (!$publicuser) {
12184: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12185: 	    }
12186: 	    return $reply{$qualifierrest};
12187:         }
12188:     } elsif ($realm eq 'query') {
12189: # ---------------------------------------------- pull stuff out of query string
12190:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12191: 						[$spacequalifierrest]);
12192: 	return $env{'form.'.$spacequalifierrest}; 
12193:    } elsif ($realm eq 'request') {
12194: # ------------------------------------------------------------- request.browser
12195:         if ($space eq 'browser') {
12196:             return $env{'browser.'.$qualifier};
12197: # ------------------------------------------------------------ request.filename
12198:         } else {
12199:             return $env{'request.'.$spacequalifierrest};
12200:         }
12201:     } elsif ($realm eq 'course') {
12202: # ---------------------------------------------------------- course.description
12203:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12204:     } elsif ($realm eq 'resource') {
12205: 
12206: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12207: 	    if (!$symbparm) { $symbparm=&symbread(); }
12208: 	}
12209: 
12210:         if ($qualifier eq '') {
12211: 	    if ($space eq 'title') {
12212: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12213: 	        return &gettitle($symbparm);
12214: 	    }
12215: 	
12216: 	    if ($space eq 'map') {
12217: 	        my ($map) = &decode_symb($symbparm);
12218: 	        return &symbread($map);
12219: 	    }
12220:             if ($space eq 'maptitle') {
12221:                 my ($map) = &decode_symb($symbparm);
12222:                 return &gettitle($map);
12223:             }
12224: 	    if ($space eq 'filename') {
12225: 	        if ($symbparm) {
12226: 		    return &clutter((&decode_symb($symbparm))[2]);
12227: 	        }
12228: 	        return &hreflocation('',$env{'request.filename'});
12229: 	    }
12230: 
12231:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12232:                 if ($space eq 'visibleparts') {
12233:                     my $navmap = Apache::lonnavmaps::navmap->new();
12234:                     my $item;
12235:                     if (ref($navmap)) {
12236:                         my $res = $navmap->getBySymb($symbparm);
12237:                         my $parts = $res->parts();
12238:                         if (ref($parts) eq 'ARRAY') {
12239:                             $item = join(',',@{$parts});
12240:                         }
12241:                         undef($navmap);
12242:                     }
12243:                     return $item;
12244:                 }
12245:             }
12246:         }
12247: 
12248: 	my ($section, $group, @groups, @recurseup, $recursed);
12249: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12250:         if (($courseid eq '') && ($cid)) {
12251:             $courseid = $cid;
12252:         }
12253: 	if (($symbparm && $courseid) && 
12254: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12255: 
12256: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12257: 
12258: # ----------------------------------------------------- Cascading lookup scheme
12259: 	    my $symbp=$symbparm;
12260: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12261: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12262:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12263: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12264: 	    if (($env{'user.name'} eq $uname) &&
12265: 		($env{'user.domain'} eq $udom)) {
12266: 		$section=$env{'request.course.sec'};
12267:                 @groups = split(/:/,$env{'request.course.groups'});  
12268:                 @groups=&sort_course_groups($courseid,@groups); 
12269: 	    } else {
12270: 		if (! defined($usection)) {
12271: 		    $section=&getsection($udom,$uname,$courseid);
12272: 		} else {
12273: 		    $section = $usection;
12274: 		}
12275:                 @groups = &get_users_groups($udom,$uname,$courseid);
12276: 	    }
12277: 
12278: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12279: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12280:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12281: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12282: 
12283: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12284: 	    my $courselevelr=$courseid.'.'.$symbparm;
12285:             $courseleveli=$courseid.'.'.$recurseparm;
12286: 	    $courselevelm=$courseid.'.'.$mapparm;
12287: 
12288: # ----------------------------------------------------------- first, check user
12289: 
12290: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12291:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12292: 				       ([$courselevelr,'resource'],
12293: 					[$courselevelm,'map'     ],
12294:                                         [$courseleveli,'map'     ],
12295: 					[$courselevel, 'course'  ]));
12296: 	    if (defined($userreply)) { return &get_reply($userreply); }
12297: 
12298: # ------------------------------------------------ second, check some of course
12299:             my $coursereply;
12300:             if (@groups > 0) {
12301:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12302:                                        $recurseparm,$mapparm,$spacequalifierrest,
12303:                                        $mapp,\$recursed,\@recurseup);
12304:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12305:             }
12306: 
12307: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12308: 				  $env{'course.'.$courseid.'.domain'},
12309: 				  'course',$mapp,\$recursed,\@recurseup,
12310:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12311: 				  ([$seclevelr,   'resource'],
12312: 				   [$seclevelm,   'map'     ],
12313:                                    [$secleveli,   'map'     ],
12314: 				   [$seclevel,    'course'  ],
12315: 				   [$courselevelr,'resource']));
12316: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12317: 
12318: # ------------------------------------------------------ third, check map parms
12319: 	    my %parmhash=();
12320: 	    my $thisparm='';
12321: 	    if (tie(%parmhash,'GDBM_File',
12322: 		    $env{'request.course.fn'}.'_parms.db',
12323: 		    &GDBM_READER(),0640)) {
12324: 		$thisparm=$parmhash{$symbparm};
12325: 		untie(%parmhash);
12326: 	    }
12327: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12328: 	}
12329: # ------------------------------------------ fourth, look in resource metadata
12330:  
12331:         my $what = $spacequalifierrest;
12332: 	$what=~s/\./\_/;
12333: 	my $filename;
12334: 	if (!$symbparm) { $symbparm=&symbread(); }
12335: 	if ($symbparm) {
12336: 	    $filename=(&decode_symb($symbparm))[2];
12337: 	} else {
12338: 	    $filename=$env{'request.filename'};
12339: 	}
12340:         my $toolsymb;
12341:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12342:             $toolsymb = $symbparm;
12343:         }
12344: 	my $metadata=&metadata($filename,$what,$toolsymb);
12345: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12346: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12347: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12348: 
12349: # ----------------------------------------------- fifth, look in rest of course
12350: 	if ($symbparm && defined($courseid) && 
12351: 	    $courseid eq $env{'request.course.id'}) {
12352: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12353: 				     $env{'course.'.$courseid.'.domain'},
12354: 				     'course',$mapp,\$recursed,\@recurseup,
12355:                                      $courseid,'.',$spacequalifierrest,
12356: 				     ([$courselevelm,'map'   ],
12357:                                       [$courseleveli,'map'   ],
12358: 				      [$courselevel, 'course']));
12359: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12360: 	}
12361: # ------------------------------------------------------------------ Cascade up
12362: 	unless ($space eq '0') {
12363: 	    my @parts=split(/_/,$space);
12364: 	    my $id=pop(@parts);
12365: 	    my $part=join('_',@parts);
12366: 	    if ($part eq '') { $part='0'; }
12367: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12368: 				 $symbparm,$udom,$uname,$section,1);
12369: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12370: 	}
12371: 	if ($recurse) { return undef; }
12372: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12373: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12374: # ---------------------------------------------------- Any other user namespace
12375:     } elsif ($realm eq 'environment') {
12376: # ----------------------------------------------------------------- environment
12377: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12378: 	    return $env{'environment.'.$spacequalifierrest};
12379: 	} else {
12380: 	    if ($uname eq 'anonymous' && $udom eq '') {
12381: 		return '';
12382: 	    }
12383: 	    my %returnhash=&userenvironment($udom,$uname,
12384: 					    $spacequalifierrest);
12385: 	    return $returnhash{$spacequalifierrest};
12386: 	}
12387:     } elsif ($realm eq 'system') {
12388: # ----------------------------------------------------------------- system.time
12389: 	if ($space eq 'time') {
12390: 	    return time;
12391:         }
12392:     } elsif ($realm eq 'server') {
12393: # ----------------------------------------------------------------- system.time
12394: 	if ($space eq 'name') {
12395: 	    return $ENV{'SERVER_NAME'};
12396:         }
12397:     } elsif ($realm eq 'client') {
12398:         if ($space eq 'remote_addr') {
12399:             return $ENV{'REMOTE_ADDR'};
12400:         }
12401:     }
12402:     return '';
12403: }
12404: 
12405: sub get_reply {
12406:     my ($reply_value) = @_;
12407:     if (ref($reply_value) eq 'ARRAY') {
12408:         if (wantarray) {
12409: 	    return @$reply_value;
12410:         }
12411:         return $reply_value->[0];
12412:     } else {
12413:         return $reply_value;
12414:     }
12415: }
12416: 
12417: sub check_group_parms {
12418:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12419:         $recursed,$recurseupref) = @_;
12420:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12421:                   [$what,'course']);
12422:     my $coursereply;
12423:     foreach my $group (@{$groups}) {
12424:         my @groupitems = ();
12425:         foreach my $level (@levels) {
12426:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12427:              push(@groupitems,[$item,$level->[1]]);
12428:         }
12429:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12430:                                    $env{'course.'.$courseid.'.domain'},
12431:                                    'course',$mapp,$recursed,$recurseupref,
12432:                                    $courseid,'.['.$group.'].',$what,
12433:                                    @groupitems);
12434:         last if (defined($coursereply));
12435:     }
12436:     return $coursereply;
12437: }
12438: 
12439: sub get_map_hierarchy {
12440:     my ($mapname,$courseid) = @_;
12441:     my @recurseup = ();
12442:     if ($mapname) {
12443:         if (($cachedmapkey eq $courseid) &&
12444:             (abs($cachedmaptime-time)<5)) {
12445:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12446:                 return @{$cachedmaps{$mapname}};
12447:             }
12448:         }
12449:         my $navmap = Apache::lonnavmaps::navmap->new();
12450:         if (ref($navmap)) {
12451:             @recurseup = $navmap->recurseup_maps($mapname);
12452:             undef($navmap);
12453:             $cachedmaps{$mapname} = \@recurseup;
12454:             $cachedmaptime=time;
12455:             $cachedmapkey=$courseid;
12456:         }
12457:     }
12458:     return @recurseup;
12459: }
12460: 
12461: }
12462: 
12463: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12464:     my ($courseid,@groups) = @_;
12465:     @groups = sort(@groups);
12466:     return @groups;
12467: }
12468: 
12469: sub packages_tab_default {
12470:     my ($uri,$varname,$toolsymb)=@_;
12471:     my (undef,$part,$name)=split(/\./,$varname);
12472: 
12473:     my (@extension,@specifics,$do_default);
12474:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12475: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12476: 	if ($pack_type eq 'default') {
12477: 	    $do_default=1;
12478: 	} elsif ($pack_type eq 'extension') {
12479: 	    push(@extension,[$package,$pack_type,$pack_part]);
12480: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12481: 	    # only look at packages defaults for packages that this id is
12482: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12483: 	}
12484:     }
12485:     # first look for a package that matches the requested part id
12486:     foreach my $package (@specifics) {
12487: 	my (undef,$pack_type,$pack_part)=@{$package};
12488: 	next if ($pack_part ne $part);
12489: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12490: 	    return $packagetab{"$pack_type&$name&default"};
12491: 	}
12492:     }
12493:     # look for any possible matching non extension_ package
12494:     foreach my $package (@specifics) {
12495: 	my (undef,$pack_type,$pack_part)=@{$package};
12496: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12497: 	    return $packagetab{"$pack_type&$name&default"};
12498: 	}
12499: 	if ($pack_type eq 'part') { $pack_part='0'; }
12500: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12501: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12502: 	}
12503:     }
12504:     # look for any posible extension_ match
12505:     foreach my $package (@extension) {
12506: 	my ($package,$pack_type)=@{$package};
12507: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12508: 	    return $packagetab{"$pack_type&$name&default"};
12509: 	}
12510: 	if (defined($packagetab{$package."&$name&default"})) {
12511: 	    return $packagetab{$package."&$name&default"};
12512: 	}
12513:     }
12514:     # look for a global default setting
12515:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12516: 	return $packagetab{"default&$name&default"};
12517:     }
12518:     return undef;
12519: }
12520: 
12521: sub add_prefix_and_part {
12522:     my ($prefix,$part)=@_;
12523:     my $keyroot;
12524:     if (defined($prefix) && $prefix !~ /^__/) {
12525: 	# prefix that has a part already
12526: 	$keyroot=$prefix;
12527:     } elsif (defined($prefix)) {
12528: 	# prefix that is missing a part
12529: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12530:     } else {
12531: 	# no prefix at all
12532: 	if (defined($part)) { $keyroot='_'.$part; }
12533:     }
12534:     return $keyroot;
12535: }
12536: 
12537: # ---------------------------------------------------------------- Get metadata
12538: 
12539: my %metaentry;
12540: my %importedpartids;
12541: my %importedrespids;
12542: sub metadata {
12543:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12544:     $uri=&declutter($uri);
12545:     # if it is a non metadata possible uri return quickly
12546:     if (($uri eq '') || 
12547: 	(($uri =~ m|^/*adm/|) && 
12548: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12549:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12550: 	return undef;
12551:     }
12552:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12553: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12554: 	return undef;
12555:     }
12556:     my $filename=$uri;
12557:     $uri=~s/\.meta$//;
12558: #
12559: # Is the metadata already cached?
12560: # Look at timestamp of caching
12561: # Everything is cached by the main uri, libraries are never directly cached
12562: #
12563:     if (!defined($liburi)) {
12564: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12565: 	if (defined($cached)) { return $result->{':'.$what}; }
12566:     }
12567: 
12568: #
12569: # If the uri is for an external tool the file from
12570: # which metadata should be retrieved depends on whether
12571: # the tool had been configured to be gradable (set in the Course
12572: # Editor or Resource Editor).
12573: #
12574: # If a valid symb has been included as the third arg in the call
12575: # to &metadata() that can be used to retrieve the value of
12576: # parameter_0_gradable set for the resource, and included in the
12577: # uploaded map containing the tool. The value is retrieved via
12578: # &EXT(), if a valid symb is available.  Otherwise the value of
12579: # gradable in the exttool_$marker.db file for the tool instance
12580: # is retrieved via &get().
12581: #
12582: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12583: # hiddenresource and encrypturl (during course initialization)
12584: # the map-level parameter for resource.0.gradable included in the 
12585: # uploaded map containing the tool will not yet have been stored
12586: # in the user_course_parms.db file for the user's session, so in 
12587: # this case fall back to retrieving gradable status from the
12588: # exttool_$marker.db file.
12589: #
12590: # In order to avoid an infinite loop, &metadata() will return
12591: # before a call to &EXT(), if the uri is for an external tool
12592: # and the $what for which metadata is being requested is
12593: # parameter_0_gradable or 0_gradable.
12594: #
12595: 
12596:     if ($uri =~ /ext\.tool$/) {
12597:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12598:             return;
12599:         } else {
12600:             my ($checked,$use_passback);
12601:             if ($toolsymb ne '') {
12602:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12603:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12604:                     $checked = 1;
12605:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12606:                         $use_passback = 1;
12607:                     }
12608:                 }
12609:             }
12610:             unless ($checked) {
12611:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12612:                 $marker=~s/\D//g;
12613:                 if ($marker) {
12614:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12615:                     $use_passback = $toolsettings{'gradable'};
12616:                 }
12617:             }
12618:             if ($use_passback) {
12619:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12620:             } else {
12621:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12622:             }
12623:         }
12624:     }
12625: 
12626:     {
12627: # Imported parts would go here
12628:         my @origfiletagids=();
12629:         my $importedparts=0;
12630: 
12631: # Imported responseids would go here
12632:         my $importedresponses=0;
12633: #
12634: # Is this a recursive call for a library?
12635: #
12636: #	if (! exists($metacache{$uri})) {
12637: #	    $metacache{$uri}={};
12638: #	}
12639: 	my $cachetime = 60*60;
12640:         if ($liburi) {
12641: 	    $liburi=&declutter($liburi);
12642:             $filename=$liburi;
12643:         } else {
12644: 	    &devalidate_cache_new('meta',$uri);
12645: 	    undef(%metaentry);
12646: 	}
12647:         my %metathesekeys=();
12648:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12649: 	my $metastring;
12650: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12651: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12652: 	    $metastring = 
12653: 		&Apache::lonnet::ssi_body($which,
12654: 					  ('grade_target' => 'meta'));
12655: 	    $cachetime = 1; # only want this cached in the child not long term
12656: 	} elsif (($uri !~ m -^(editupload)/-) && 
12657:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12658: 	    my $file=&filelocation('',&clutter($filename));
12659: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12660: 	    $metastring=&getfile($file);
12661: 	}
12662:         my $parser=HTML::LCParser->new(\$metastring);
12663:         my $token;
12664:         undef %metathesekeys;
12665:         while ($token=$parser->get_token) {
12666: 	    if ($token->[0] eq 'S') {
12667: 		if (defined($token->[2]->{'package'})) {
12668: #
12669: # This is a package - get package info
12670: #
12671: 		    my $package=$token->[2]->{'package'};
12672: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12673: 		    if (defined($token->[2]->{'id'})) { 
12674: 			$keyroot.='_'.$token->[2]->{'id'}; 
12675: 		    }
12676: 		    if ($metaentry{':packages'}) {
12677: 			$metaentry{':packages'}.=','.$package.$keyroot;
12678: 		    } else {
12679: 			$metaentry{':packages'}=$package.$keyroot;
12680: 		    }
12681: 		    foreach my $pack_entry (keys(%packagetab)) {
12682: 			my $part=$keyroot;
12683: 			$part=~s/^\_//;
12684: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12685: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12686: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12687: 			    # ignore package.tab specified default values
12688:                             # here &package_tab_default() will fetch those
12689: 			    if ($subp eq 'default') { next; }
12690: 			    my $value=$packagetab{$pack_entry};
12691: 			    my $unikey;
12692: 			    if ($pack =~ /_0$/) {
12693: 				$unikey='parameter_0_'.$name;
12694: 				$part=0;
12695: 			    } else {
12696: 				$unikey='parameter'.$keyroot.'_'.$name;
12697: 			    }
12698: 			    if ($subp eq 'display') {
12699: 				$value.=' [Part: '.$part.']';
12700: 			    }
12701: 			    $metaentry{':'.$unikey.'.part'}=$part;
12702: 			    $metathesekeys{$unikey}=1;
12703: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12704: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12705: 			    }
12706: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12707: 				$metaentry{':'.$unikey}=
12708: 				    $metaentry{':'.$unikey.'.default'};
12709: 			    }
12710: 			}
12711: 		    }
12712: 		} else {
12713: #
12714: # This is not a package - some other kind of start tag
12715: #
12716: 		    my $entry=$token->[1];
12717: 		    my $unikey='';
12718: 
12719: 		    if ($entry eq 'import') {
12720: #
12721: # Importing a library here
12722: #
12723:                         my $location=$parser->get_text('/import');
12724:                         my $dir=$filename;
12725:                         $dir=~s|[^/]*$||;
12726:                         $location=&filelocation($dir,$location);
12727: 
12728:                         my $importid=$token->[2]->{'id'};
12729:                         my $importmode=$token->[2]->{'importmode'};
12730: #
12731: # Check metadata for imported file to
12732: # see if it contained response items
12733: #
12734:                         my ($origfile,@libfilekeys);
12735:                         my %currmetaentry = %metaentry;
12736:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12737:                                                            $depthcount+1));
12738:                         if (grep(/^responseorder$/,@libfilekeys)) {
12739:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12740:                                                              undef,$depthcount+1);
12741:                             if ($libresponseorder ne '') {
12742:                                 if ($#origfiletagids<0) {
12743:                                     undef(%importedrespids);
12744:                                     undef(%importedpartids);
12745:                                 }
12746:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12747:                                 if (@respids) {
12748:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12749:                                 }
12750:                                 if ($importedrespids{$importid} ne '') {
12751:                                     $importedresponses = 1;
12752: # We need to get the original file and the imported file to get the response order correct
12753: # Load and inspect original file
12754:                                     if ($#origfiletagids<0) {
12755:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12756:                                         $origfile=&getfile($origfilelocation);
12757:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12758:                                     }
12759:                                 }
12760:                             }
12761:                         }
12762: # Do not overwrite contents of %metaentry hash for resource itself with 
12763: # hash populated for imported library file
12764:                         %metaentry = %currmetaentry;
12765:                         undef(%currmetaentry);
12766:                         if ($importmode eq 'part') {
12767: # Import as part(s)
12768:                            $importedparts=1;
12769: # We need to get the original file and the imported file to get the part order correct
12770: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12771: # Load and inspect original file if we didn't do that already
12772:                            if ($#origfiletagids<0) {
12773:                                undef(%importedrespids);
12774:                                undef(%importedpartids);
12775:                                if ($origfile eq '') {
12776:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12777:                                    $origfile=&getfile($origfilelocation);
12778:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12779:                                }
12780:                            }
12781:                            my @impfilepartids;
12782: # If <partorder> tag is included in metadata for the imported file
12783: # get the parts in the imported file from that.
12784:                            if (grep(/^partorder$/,@libfilekeys)) {
12785:                                %currmetaentry = %metaentry;
12786:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12787:                                                             $depthcount+1);
12788:                                %metaentry = %currmetaentry;
12789:                                undef(%currmetaentry);
12790:                                if ($libpartorder ne '') {
12791:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12792:                                }
12793:                            } else {
12794: # If no <partorder> tag available, load and inspect imported file
12795:                                my $impfile=&getfile($location);
12796:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12797:                            }
12798:                            if ($#impfilepartids>=0) {
12799: # This problem had parts
12800:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12801:                            } else {
12802: # Importing by turning a single problem into a problem part
12803: # It gets the import-tags ID as part-ID
12804:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12805:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12806:                            }
12807:                         } else {
12808: # Import as problem or as normal import
12809:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12810:                             unless ($importmode eq 'problem') {
12811: # Normal import
12812:                                 if (defined($token->[2]->{'id'})) {
12813:                                     $unikey.='_'.$token->[2]->{'id'};
12814:                                 }
12815:                             }
12816: # Check metadata for imported file to
12817: # see if it contained parts
12818:                             if (grep(/^partorder$/,@libfilekeys)) {
12819:                                 %currmetaentry = %metaentry;
12820:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12821:                                                              $depthcount+1);
12822:                                 %metaentry = %currmetaentry;
12823:                                 undef(%currmetaentry);
12824:                                 if ($libpartorder ne '') {
12825:                                     $importedparts = 1;
12826:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12827:                                 }
12828:                             }
12829:                         }
12830: 			if ($depthcount<20) {
12831: 			    my $metadata = 
12832: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12833: 					  $depthcount+1);
12834: 			    foreach my $meta (split(',',$metadata)) {
12835: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12836: 				$metathesekeys{$meta}=1;
12837: 			    }
12838:                         }
12839: 		    } else {
12840: #
12841: # Not importing, some other kind of non-package, non-library start tag
12842: # 
12843:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12844:                         if (defined($token->[2]->{'id'})) {
12845:                             $unikey.='_'.$token->[2]->{'id'};
12846:                         }
12847: 			if (defined($token->[2]->{'name'})) { 
12848: 			    $unikey.='_'.$token->[2]->{'name'}; 
12849: 			}
12850: 			$metathesekeys{$unikey}=1;
12851: 			foreach my $param (@{$token->[3]}) {
12852: 			    $metaentry{':'.$unikey.'.'.$param} =
12853: 				$token->[2]->{$param};
12854: 			}
12855: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12856: 			my $default=$metaentry{':'.$unikey.'.default'};
12857: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12858: 		 # only ws inside the tag, and not in default, so use default
12859: 		 # as value
12860: 			    $metaentry{':'.$unikey}=$default;
12861: 			} elsif ( $internaltext =~ /\S/ ) {
12862: 		  # something interesting inside the tag
12863: 			    $metaentry{':'.$unikey}=$internaltext;
12864: 			} else {
12865: 		  # no interesting values, don't set a default
12866: 			}
12867: # end of not-a-package not-a-library import
12868: 		    }
12869: # end of not-a-package start tag
12870: 		}
12871: # the next is the end of "start tag"
12872: 	    }
12873: 	}
12874: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12875: 	$extension = lc($extension);
12876: 	if ($extension eq 'htm') { $extension='html'; }
12877: 
12878: 	foreach my $key (keys(%packagetab)) {
12879: 	    #no specific packages #how's our extension
12880: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12881: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12882: 					 \%metathesekeys);
12883: 	}
12884: 
12885: 	if (!exists($metaentry{':packages'})
12886: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12887: 	    foreach my $key (keys(%packagetab)) {
12888: 		#no specific packages well let's get default then
12889: 		if ($key!~/^default&/) { next; }
12890: 		&metadata_create_package_def($uri,$key,'default',
12891: 					     \%metathesekeys);
12892: 	    }
12893: 	}
12894: # are there custom rights to evaluate
12895: 	if ($metaentry{':copyright'} eq 'custom') {
12896: 
12897:     #
12898:     # Importing a rights file here
12899:     #
12900: 	    unless ($depthcount) {
12901: 		my $location=$metaentry{':customdistributionfile'};
12902: 		my $dir=$filename;
12903: 		$dir=~s|[^/]*$||;
12904: 		$location=&filelocation($dir,$location);
12905: 		my $rights_metadata =
12906: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12907: 			      $depthcount+1);
12908: 		foreach my $rights (split(',',$rights_metadata)) {
12909: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12910: 		    $metathesekeys{$rights}=1;
12911: 		}
12912: 	    }
12913: 	}
12914: 	# uniqifiy package listing
12915: 	my %seen;
12916: 	my @uniq_packages =
12917: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12918: 	$metaentry{':packages'} = join(',',@uniq_packages);
12919: 
12920:         if (($importedresponses) || ($importedparts)) {
12921:             if ($importedparts) {
12922: # We had imported parts and need to rebuild partorder
12923:                 $metaentry{':partorder'}='';
12924:                 $metathesekeys{'partorder'}=1;
12925:             }
12926:             if ($importedresponses) {
12927: # We had imported responses and need to rebuil responseorder
12928:                 $metaentry{':responseorder'}='';
12929:                 $metathesekeys{'responseorder'}=1;
12930:             }
12931:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12932:                 my $origid = $origfiletagids[$index+1];
12933:                 if ($origfiletagids[$index] eq 'part') {
12934: # Original part, part of the problem
12935:                     if ($importedparts) {
12936:                         $metaentry{':partorder'}.=','.$origid;
12937:                     }
12938:                 } elsif ($origfiletagids[$index] eq 'import') {
12939:                     if ($importedparts) {
12940: # We have imported parts at this position
12941:                         if ($importedpartids{$origid} ne '') {
12942:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12943:                         }
12944:                     }
12945:                     if ($importedresponses) {
12946: # We have imported responses at this position
12947:                         if ($importedrespids{$origid} ne '') {
12948:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12949:                         }
12950:                     }
12951:                 } else {
12952: # Original response item, part of the problem
12953:                     if ($importedresponses) {
12954:                         $metaentry{':responseorder'}.=','.$origid;
12955:                     }
12956:                 }
12957:             }
12958:             if ($importedparts) {
12959:                 $metaentry{':partorder'}=~s/^\,//;
12960:             }
12961:             if ($importedresponses) {
12962:                 $metaentry{':responseorder'}=~s/^\,//;
12963:             }
12964:         }
12965: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12966: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12967: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12968:         unless ($liburi) {
12969: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12970:         }
12971: # this is the end of "was not already recently cached
12972:     }
12973:     return $metaentry{':'.$what};
12974: }
12975: 
12976: sub metadata_create_package_def {
12977:     my ($uri,$key,$package,$metathesekeys)=@_;
12978:     my ($pack,$name,$subp)=split(/\&/,$key);
12979:     if ($subp eq 'default') { next; }
12980:     
12981:     if (defined($metaentry{':packages'})) {
12982: 	$metaentry{':packages'}.=','.$package;
12983:     } else {
12984: 	$metaentry{':packages'}=$package;
12985:     }
12986:     my $value=$packagetab{$key};
12987:     my $unikey;
12988:     $unikey='parameter_0_'.$name;
12989:     $metaentry{':'.$unikey.'.part'}=0;
12990:     $$metathesekeys{$unikey}=1;
12991:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12992: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12993:     }
12994:     if (defined($metaentry{':'.$unikey.'.default'})) {
12995: 	$metaentry{':'.$unikey}=
12996: 	    $metaentry{':'.$unikey.'.default'};
12997:     }
12998: }
12999: 
13000: sub metadata_generate_part0 {
13001:     my ($metadata,$metacache,$uri) = @_;
13002:     my %allnames;
13003:     foreach my $metakey (keys(%$metadata)) {
13004: 	if ($metakey=~/^parameter\_(.*)/) {
13005: 	  my $part=$$metacache{':'.$metakey.'.part'};
13006: 	  my $name=$$metacache{':'.$metakey.'.name'};
13007: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13008: 	    $allnames{$name}=$part;
13009: 	  }
13010: 	}
13011:     }
13012:     foreach my $name (keys(%allnames)) {
13013:       $$metadata{"parameter_0_$name"}=1;
13014:       my $key=":parameter_0_$name";
13015:       $$metacache{"$key.part"}='0';
13016:       $$metacache{"$key.name"}=$name;
13017:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13018: 					   $allnames{$name}.'_'.$name.
13019: 					   '.type'};
13020:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13021: 			     '.display'};
13022:       my $expr='[Part: '.$allnames{$name}.']';
13023:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13024:       $$metacache{"$key.display"}=$olddis;
13025:     }
13026: }
13027: 
13028: # ------------------------------------------------------ Devalidate title cache
13029: 
13030: sub devalidate_title_cache {
13031:     my ($url)=@_;
13032:     if (!$env{'request.course.id'}) { return; }
13033:     my $symb=&symbread($url);
13034:     if (!$symb) { return; }
13035:     my $key=$env{'request.course.id'}."\0".$symb;
13036:     &devalidate_cache_new('title',$key);
13037: }
13038: 
13039: # ------------------------------------------------- Get the title of a course
13040: 
13041: sub current_course_title {
13042:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13043: }
13044: # ------------------------------------------------- Get the title of a resource
13045: 
13046: sub gettitle {
13047:     my $urlsymb=shift;
13048:     my $symb=&symbread($urlsymb);
13049:     if ($symb) {
13050: 	my $key=$env{'request.course.id'}."\0".$symb;
13051: 	my ($result,$cached)=&is_cached_new('title',$key);
13052: 	if (defined($cached)) { 
13053: 	    return $result;
13054: 	}
13055: 	my ($map,$resid,$url)=&decode_symb($symb);
13056: 	my $title='';
13057: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13058: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13059: 	} else {
13060: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13061: 		    &GDBM_READER(),0640)) {
13062: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13063: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13064: 		untie(%bighash);
13065: 	    }
13066: 	}
13067: 	$title=~s/\&colon\;/\:/gs;
13068: 	if ($title) {
13069: # Remember both $symb and $title for dynamic metadata
13070:             $accesshash{$symb.'___crstitle'}=$title;
13071:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13072: # Cache this title and then return it
13073: 	    return &do_cache_new('title',$key,$title,600);
13074: 	}
13075: 	$urlsymb=$url;
13076:     }
13077:     my $title=&metadata($urlsymb,'title');
13078:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13079:     return $title;
13080: }
13081: 
13082: sub get_slot {
13083:     my ($which,$cnum,$cdom)=@_;
13084:     if (!$cnum || !$cdom) {
13085: 	(undef,my $courseid)=&whichuser();
13086: 	$cdom=$env{'course.'.$courseid.'.domain'};
13087: 	$cnum=$env{'course.'.$courseid.'.num'};
13088:     }
13089:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13090:     my %slotinfo;
13091:     if (exists($remembered{$key})) {
13092: 	$slotinfo{$which} = $remembered{$key};
13093:     } else {
13094: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13095: 	&Apache::lonhomework::showhash(%slotinfo);
13096: 	my ($tmp)=keys(%slotinfo);
13097: 	if ($tmp=~/^error:/) { return (); }
13098: 	$remembered{$key} = $slotinfo{$which};
13099:     }
13100:     if (ref($slotinfo{$which}) eq 'HASH') {
13101: 	return %{$slotinfo{$which}};
13102:     }
13103:     return $slotinfo{$which};
13104: }
13105: 
13106: sub get_reservable_slots {
13107:     my ($cnum,$cdom,$uname,$udom) = @_;
13108:     my $now = time;
13109:     my $reservable_info;
13110:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13111:     if (exists($remembered{$key})) {
13112:         $reservable_info = $remembered{$key};
13113:     } else {
13114:         my %resv;
13115:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13116:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13117:         $reservable_info = \%resv;
13118:         $remembered{$key} = $reservable_info;
13119:     }
13120:     return $reservable_info;
13121: }
13122: 
13123: sub get_course_slots {
13124:     my ($cnum,$cdom) = @_;
13125:     my $hashid=$cnum.':'.$cdom;
13126:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13127:     if (defined($cached)) {
13128:         if (ref($result) eq 'HASH') {
13129:             return %{$result};
13130:         }
13131:     } else {
13132:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13133:         my ($tmp) = keys(%slots);
13134:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13135:             &do_cache_new('allslots',$hashid,\%slots,600);
13136:             return %slots;
13137:         }
13138:     }
13139:     return;
13140: }
13141: 
13142: sub devalidate_slots_cache {
13143:     my ($cnum,$cdom)=@_;
13144:     my $hashid=$cnum.':'.$cdom;
13145:     &devalidate_cache_new('allslots',$hashid);
13146: }
13147: 
13148: sub get_coursechange {
13149:     my ($cdom,$cnum) = @_;
13150:     if ($cdom eq '' || $cnum eq '') {
13151:         return unless ($env{'request.course.id'});
13152:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13153:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13154:     }
13155:     my $hashid=$cdom.'_'.$cnum;
13156:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13157:     if ((defined($cached)) && ($change ne '')) {
13158:         return $change;
13159:     } else {
13160:         my %crshash;
13161:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13162:         if ($crshash{'internal.contentchange'} eq '') {
13163:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13164:             if ($change eq '') {
13165:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13166:                 $change = $crshash{'internal.created'};
13167:             }
13168:         } else {
13169:             $change = $crshash{'internal.contentchange'};
13170:         }
13171:         my $cachetime = 600;
13172:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13173:     }
13174:     return $change;
13175: }
13176: 
13177: sub devalidate_coursechange_cache {
13178:     my ($cnum,$cdom)=@_;
13179:     my $hashid=$cnum.':'.$cdom;
13180:     &devalidate_cache_new('crschange',$hashid);
13181: }
13182: 
13183: # ------------------------------------------------- Update symbolic store links
13184: 
13185: sub symblist {
13186:     my ($mapname,%newhash)=@_;
13187:     $mapname=&deversion(&declutter($mapname));
13188:     my %hash;
13189:     if (($env{'request.course.fn'}) && (%newhash)) {
13190:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13191:                       &GDBM_WRCREAT(),0640)) {
13192: 	    foreach my $url (keys(%newhash)) {
13193: 		next if ($url eq 'last_known'
13194: 			 && $env{'form.no_update_last_known'});
13195: 		$hash{declutter($url)}=&encode_symb($mapname,
13196: 						    $newhash{$url}->[1],
13197: 						    $newhash{$url}->[0]);
13198:             }
13199:             if (untie(%hash)) {
13200: 		return 'ok';
13201:             }
13202:         }
13203:     }
13204:     return 'error';
13205: }
13206: 
13207: # --------------------------------------------------------------- Verify a symb
13208: 
13209: sub symbverify {
13210:     my ($symb,$thisurl,$encstate)=@_;
13211:     my $thisfn=$thisurl;
13212:     $thisfn=&declutter($thisfn);
13213: # direct jump to resource in page or to a sequence - will construct own symbs
13214:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13215: # check URL part
13216:     my ($map,$resid,$url)=&decode_symb($symb);
13217: 
13218:     unless ($url eq $thisfn) { return 0; }
13219: 
13220:     $symb=&symbclean($symb);
13221:     $thisurl=&deversion($thisurl);
13222:     $thisfn=&deversion($thisfn);
13223: 
13224:     my %bighash;
13225:     my $okay=0;
13226: 
13227:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13228:                             &GDBM_READER(),0640)) {
13229:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13230:             $thisurl =~ s/\?.+$//;
13231:             if ($map =~ m{^uploaded/.+\.page$}) {
13232:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13233:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13234:             }
13235:         }
13236:         my $ids;
13237:         if ($map =~ m{^uploaded/.+\.page$}) {
13238:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13239:         } else {
13240:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13241:         }
13242:         unless ($ids) {
13243:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13244:             $ids=$bighash{$idkey};
13245:         }
13246:         if ($ids) {
13247: # ------------------------------------------------------------------- Has ID(s)
13248:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13249:                 $symb =~ s/\?.+$//;
13250:             }
13251: 	    foreach my $id (split(/\,/,$ids)) {
13252: 	       my ($mapid,$resid)=split(/\./,$id);
13253:                if (
13254:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13255:    eq $symb) {
13256:                    if (ref($encstate)) {
13257:                        $$encstate = $bighash{'encrypted_'.$id};
13258:                    }
13259: 		   if (($env{'request.role.adv'}) ||
13260: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13261:                        ($thisurl eq '/adm/navmaps')) {
13262: 		       $okay=1;
13263:                        last;
13264: 		   }
13265: 	       }
13266: 	   }
13267:         }
13268: 	untie(%bighash);
13269:     }
13270:     return $okay;
13271: }
13272: 
13273: # --------------------------------------------------------------- Clean-up symb
13274: 
13275: sub symbclean {
13276:     my $symb=shift;
13277:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13278: # remove version from map
13279:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13280: 
13281: # remove version from URL
13282:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13283: 
13284: # remove wrapper
13285: 
13286:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13287:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13288:     return $symb;
13289: }
13290: 
13291: # ---------------------------------------------- Split symb to find map and url
13292: 
13293: sub encode_symb {
13294:     my ($map,$resid,$url)=@_;
13295:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13296: }
13297: 
13298: sub decode_symb {
13299:     my $symb=shift;
13300:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13301:     my ($map,$resid,$url)=split(/___/,$symb);
13302:     return (&fixversion($map),$resid,&fixversion($url));
13303: }
13304: 
13305: sub fixversion {
13306:     my $fn=shift;
13307:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13308:     my %bighash;
13309:     my $uri=&clutter($fn);
13310:     my $key=$env{'request.course.id'}.'_'.$uri;
13311: # is this cached?
13312:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13313:     if (defined($cached)) { return $result; }
13314: # unfortunately not cached, or expired
13315:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13316: 	    &GDBM_READER(),0640)) {
13317:  	if ($bighash{'version_'.$uri}) {
13318:  	    my $version=$bighash{'version_'.$uri};
13319:  	    unless (($version eq 'mostrecent') || 
13320: 		    ($version==&getversion($uri))) {
13321:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13322:  	    }
13323:  	}
13324:  	untie %bighash;
13325:     }
13326:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13327: }
13328: 
13329: sub deversion {
13330:     my $url=shift;
13331:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13332:     return $url;
13333: }
13334: 
13335: # ------------------------------------------------------ Return symb list entry
13336: 
13337: sub symbread {
13338:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13339:         $ignoresymbdb,$noenccheck)=@_;
13340:     my $cache_str='request.symbread.cached.'.$thisfn;
13341:     if (defined($env{$cache_str})) {
13342:         unless (ref($possibles) eq 'HASH') {
13343:             if ($ignorecachednull) {
13344:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
13345:             } else {
13346:                 return $env{$cache_str};
13347:             }
13348:         }
13349:     }
13350: # no filename provided? try from environment
13351:     unless ($thisfn) {
13352:         if ($env{'request.symb'}) {
13353:             return $env{$cache_str}=&symbclean($env{'request.symb'});
13354: 	}
13355: 	$thisfn=$env{'request.filename'};
13356:     }
13357:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13358: # is that filename actually a symb? Verify, clean, and return
13359:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13360: 	if (&symbverify($thisfn,$1)) {
13361: 	    return $env{$cache_str}=&symbclean($thisfn);
13362: 	}
13363:     }
13364:     $thisfn=declutter($thisfn);
13365:     my %hash;
13366:     my %bighash;
13367:     my $syval='';
13368:     if (($env{'request.course.fn'}) && ($thisfn)) {
13369:         my $targetfn = $thisfn;
13370:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13371:             $targetfn = 'adm/wrapper/'.$thisfn;
13372:         }
13373: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13374: 	    $targetfn=$1;
13375: 	}
13376:         unless ($ignoresymbdb) {
13377:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13378:                           &GDBM_READER(),0640)) {
13379: 	        $syval=$hash{$targetfn};
13380:                 untie(%hash);
13381:             }
13382:             if ($syval && $checkforblock) {
13383:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13384:                 if (@blockers) {
13385:                     $syval='';
13386:                 }
13387:             }
13388:         }
13389: # ---------------------------------------------------------- There was an entry
13390:         if ($syval) {
13391: 	    #unless ($syval=~/\_\d+$/) {
13392: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13393: 		    #&appenv({'request.ambiguous' => $thisfn});
13394: 		    #return $env{$cache_str}='';
13395: 		#}    
13396: 		#$syval.=$1;
13397: 	    #}
13398:         } else {
13399: # ------------------------------------------------------- Was not in symb table
13400:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13401:                             &GDBM_READER(),0640)) {
13402: # ---------------------------------------------- Get ID(s) for current resource
13403:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13404:               unless ($ids) { 
13405:                  $ids=$bighash{'ids_/'.$thisfn};
13406:               }
13407:               unless ($ids) {
13408: # alias?
13409: 		  $ids=$bighash{'mapalias_'.$thisfn};
13410:               }
13411:               if ($ids) {
13412: # ------------------------------------------------------------------- Has ID(s)
13413:                  my @possibilities=split(/\,/,$ids);
13414:                  if ($#possibilities==0) {
13415: # ----------------------------------------------- There is only one possibility
13416: 		     my ($mapid,$resid)=split(/\./,$ids);
13417: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13418: 						    $resid,$thisfn);
13419:                      if (ref($possibles) eq 'HASH') {
13420:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13421:                              $possibles->{$syval} = 1;
13422:                          }
13423:                      }
13424:                      if ($checkforblock) {
13425:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13426:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13427:                              if (@blockers) {
13428:                                  $syval = '';
13429:                                  untie(%bighash);
13430:                                  return $env{$cache_str}='';
13431:                              }
13432:                          }
13433:                      }
13434:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13435: # ------------------------------------------ There is more than one possibility
13436:                      my $realpossible=0;
13437:                      foreach my $id (@possibilities) {
13438: 			 my $file=$bighash{'src_'.$id};
13439:                          my $canaccess;
13440:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13441:                              $canaccess = 1;
13442:                          } else { 
13443:                              $canaccess = &allowed('bre',$file);
13444:                          }
13445:                          if ($canaccess) {
13446:          		     my ($mapid,$resid)=split(/\./,$id);
13447:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13448:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13449: 						             $resid,$thisfn);
13450:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13451:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13452:                                  if ($checkforblock) {
13453:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13454:                                      if (@blockers > 0) {
13455:                                          $syval = '';
13456:                                      } else {
13457:                                          $syval = $poss_syval;
13458:                                          $realpossible++;
13459:                                      }
13460:                                  } else {
13461:                                      $syval = $poss_syval;
13462:                                      $realpossible++;
13463:                                  }
13464:                                  if ($syval) {
13465:                                      if (ref($possibles) eq 'HASH') {
13466:                                          $possibles->{$syval} = 1;
13467:                                      }
13468:                                  }
13469:                              }
13470: 			 }
13471:                      }
13472: 		     if ($realpossible!=1) { $syval=''; }
13473:                  } else {
13474:                      $syval='';
13475:                  }
13476: 	      }
13477:               untie(%bighash);
13478:            }
13479:         }
13480:         if ($syval) {
13481: 	    return $env{$cache_str}=$syval;
13482:         }
13483:     }
13484:     &appenv({'request.ambiguous' => $thisfn});
13485:     return $env{$cache_str}='';
13486: }
13487: 
13488: # ---------------------------------------------------------- Return random seed
13489: 
13490: sub numval {
13491:     my $txt=shift;
13492:     $txt=~tr/A-J/0-9/;
13493:     $txt=~tr/a-j/0-9/;
13494:     $txt=~tr/K-T/0-9/;
13495:     $txt=~tr/k-t/0-9/;
13496:     $txt=~tr/U-Z/0-5/;
13497:     $txt=~tr/u-z/0-5/;
13498:     $txt=~s/\D//g;
13499:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13500:     return int($txt);
13501: }
13502: 
13503: sub numval2 {
13504:     my $txt=shift;
13505:     $txt=~tr/A-J/0-9/;
13506:     $txt=~tr/a-j/0-9/;
13507:     $txt=~tr/K-T/0-9/;
13508:     $txt=~tr/k-t/0-9/;
13509:     $txt=~tr/U-Z/0-5/;
13510:     $txt=~tr/u-z/0-5/;
13511:     $txt=~s/\D//g;
13512:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13513:     my $total;
13514:     foreach my $val (@txts) { $total+=$val; }
13515:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13516:     return int($total);
13517: }
13518: 
13519: sub numval3 {
13520:     use integer;
13521:     my $txt=shift;
13522:     $txt=~tr/A-J/0-9/;
13523:     $txt=~tr/a-j/0-9/;
13524:     $txt=~tr/K-T/0-9/;
13525:     $txt=~tr/k-t/0-9/;
13526:     $txt=~tr/U-Z/0-5/;
13527:     $txt=~tr/u-z/0-5/;
13528:     $txt=~s/\D//g;
13529:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13530:     my $total;
13531:     foreach my $val (@txts) { $total+=$val; }
13532:     if ($_64bit) { $total=(($total<<32)>>32); }
13533:     return $total;
13534: }
13535: 
13536: sub digest {
13537:     my ($data)=@_;
13538:     my $digest=&Digest::MD5::md5($data);
13539:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13540:     my ($e,$f);
13541:     {
13542:         use integer;
13543:         $e=($a+$b);
13544:         $f=($c+$d);
13545:         if ($_64bit) {
13546:             $e=(($e<<32)>>32);
13547:             $f=(($f<<32)>>32);
13548:         }
13549:     }
13550:     if (wantarray) {
13551: 	return ($e,$f);
13552:     } else {
13553: 	my $g;
13554: 	{
13555: 	    use integer;
13556: 	    $g=($e+$f);
13557: 	    if ($_64bit) {
13558: 		$g=(($g<<32)>>32);
13559: 	    }
13560: 	}
13561: 	return $g;
13562:     }
13563: }
13564: 
13565: sub latest_rnd_algorithm_id {
13566:     return '64bit5';
13567: }
13568: 
13569: sub get_rand_alg {
13570:     my ($courseid)=@_;
13571:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13572:     if ($courseid) {
13573: 	return $env{"course.$courseid.rndseed"};
13574:     }
13575:     return &latest_rnd_algorithm_id();
13576: }
13577: 
13578: sub validCODE {
13579:     my ($CODE)=@_;
13580:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13581:     return 0;
13582: }
13583: 
13584: sub getCODE {
13585:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13586:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13587: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13588: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13589: 	return $Apache::lonhomework::history{'resource.CODE'};
13590:     }
13591:     return undef;
13592: }
13593: #
13594: #  Determines the random seed for a specific context:
13595: #
13596: # parameters:
13597: #   symb      - in course context the symb for the seed.
13598: #   course_id - The course id of the form domain_coursenum.
13599: #   domain    - Domain for the user.
13600: #   course    - Course for the user.
13601: #   cenv      - environment of the course.
13602: #
13603: # NOTE:
13604: #   All parameters are picked out of the environment if missing
13605: #   or not defined.
13606: #   If a symb cannot be determined the current time is used instead.
13607: #
13608: #  For a given well defined symb, courside, domain, username,
13609: #  and course environment, the seed is reproducible.
13610: #
13611: sub rndseed {
13612:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13613:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13614:     if (!defined($symb)) {
13615: 	unless ($symb=$wsymb) { return time; }
13616:     }
13617:     if (!defined $courseid) { 
13618: 	$courseid=$wcourseid; 
13619:     }
13620:     if (!defined $domain) { $domain=$wdomain; }
13621:     if (!defined $username) { $username=$wusername }
13622: 
13623:     my $which;
13624:     if (defined($cenv->{'rndseed'})) {
13625: 	$which = $cenv->{'rndseed'};
13626:     } else {
13627: 	$which =&get_rand_alg($courseid);
13628:     }
13629:     if (defined(&getCODE())) {
13630: 
13631: 	if ($which eq '64bit5') {
13632: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13633: 	} elsif ($which eq '64bit4') {
13634: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13635: 	} else {
13636: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13637: 	}
13638:     } elsif ($which eq '64bit5') {
13639: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13640:     } elsif ($which eq '64bit4') {
13641: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13642:     } elsif ($which eq '64bit3') {
13643: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13644:     } elsif ($which eq '64bit2') {
13645: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13646:     } elsif ($which eq '64bit') {
13647: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13648:     }
13649:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13650: }
13651: 
13652: sub rndseed_32bit {
13653:     my ($symb,$courseid,$domain,$username)=@_;
13654:     {
13655: 	use integer;
13656: 	my $symbchck=unpack("%32C*",$symb) << 27;
13657: 	my $symbseed=numval($symb) << 22;
13658: 	my $namechck=unpack("%32C*",$username) << 17;
13659: 	my $nameseed=numval($username) << 12;
13660: 	my $domainseed=unpack("%32C*",$domain) << 7;
13661: 	my $courseseed=unpack("%32C*",$courseid);
13662: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13663: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13664: 	#&logthis("rndseed :$num:$symb");
13665: 	if ($_64bit) { $num=(($num<<32)>>32); }
13666: 	return $num;
13667:     }
13668: }
13669: 
13670: sub rndseed_64bit {
13671:     my ($symb,$courseid,$domain,$username)=@_;
13672:     {
13673: 	use integer;
13674: 	my $symbchck=unpack("%32S*",$symb) << 21;
13675: 	my $symbseed=numval($symb) << 10;
13676: 	my $namechck=unpack("%32S*",$username);
13677: 	
13678: 	my $nameseed=numval($username) << 21;
13679: 	my $domainseed=unpack("%32S*",$domain) << 10;
13680: 	my $courseseed=unpack("%32S*",$courseid);
13681: 	
13682: 	my $num1=$symbchck+$symbseed+$namechck;
13683: 	my $num2=$nameseed+$domainseed+$courseseed;
13684: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13685: 	#&logthis("rndseed :$num:$symb");
13686: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13687: 	return "$num1,$num2";
13688:     }
13689: }
13690: 
13691: sub rndseed_64bit2 {
13692:     my ($symb,$courseid,$domain,$username)=@_;
13693:     {
13694: 	use integer;
13695: 	# strings need to be an even # of cahracters long, it it is odd the
13696:         # last characters gets thrown away
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_64bit3 {
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=numval2($symb) << 10;
13722: 	my $namechck=unpack("%32S*",$username.' ');
13723: 	
13724: 	my $nameseed=numval2($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 :$num1:$num2:$_64bit");
13732: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13733: 	
13734: 	return "$num1:$num2";
13735:     }
13736: }
13737: 
13738: sub rndseed_64bit4 {
13739:     my ($symb,$courseid,$domain,$username)=@_;
13740:     {
13741: 	use integer;
13742: 	# strings need to be an even # of cahracters long, it it is odd the
13743:         # last characters gets thrown away
13744: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13745: 	my $symbseed=numval3($symb) << 10;
13746: 	my $namechck=unpack("%32S*",$username.' ');
13747: 	
13748: 	my $nameseed=numval3($username) << 21;
13749: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13750: 	my $courseseed=unpack("%32S*",$courseid.' ');
13751: 	
13752: 	my $num1=$symbchck+$symbseed+$namechck;
13753: 	my $num2=$nameseed+$domainseed+$courseseed;
13754: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13755: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13756: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13757: 	
13758: 	return "$num1:$num2";
13759:     }
13760: }
13761: 
13762: sub rndseed_64bit5 {
13763:     my ($symb,$courseid,$domain,$username)=@_;
13764:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13765:     return "$num1:$num2";
13766: }
13767: 
13768: sub rndseed_CODE_64bit {
13769:     my ($symb,$courseid,$domain,$username)=@_;
13770:     {
13771: 	use integer;
13772: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13773: 	my $symbseed=numval2($symb);
13774: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13775: 	my $CODEseed=numval(&getCODE());
13776: 	my $courseseed=unpack("%32S*",$courseid.' ');
13777: 	my $num1=$symbseed+$CODEchck;
13778: 	my $num2=$CODEseed+$courseseed+$symbchck;
13779: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13780: 	#&logthis("rndseed :$num1:$num2:$symb");
13781: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13782: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13783: 	return "$num1:$num2";
13784:     }
13785: }
13786: 
13787: sub rndseed_CODE_64bit4 {
13788:     my ($symb,$courseid,$domain,$username)=@_;
13789:     {
13790: 	use integer;
13791: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13792: 	my $symbseed=numval3($symb);
13793: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13794: 	my $CODEseed=numval3(&getCODE());
13795: 	my $courseseed=unpack("%32S*",$courseid.' ');
13796: 	my $num1=$symbseed+$CODEchck;
13797: 	my $num2=$CODEseed+$courseseed+$symbchck;
13798: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13799: 	#&logthis("rndseed :$num1:$num2:$symb");
13800: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13801: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13802: 	return "$num1:$num2";
13803:     }
13804: }
13805: 
13806: sub rndseed_CODE_64bit5 {
13807:     my ($symb,$courseid,$domain,$username)=@_;
13808:     my $code = &getCODE();
13809:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13810:     return "$num1:$num2";
13811: }
13812: 
13813: sub setup_random_from_rndseed {
13814:     my ($rndseed)=@_;
13815:     if ($rndseed =~/([,:])/) {
13816:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13817:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13818:             &Math::Random::random_set_seed_from_phrase($rndseed);
13819:         } else {
13820:             &Math::Random::random_set_seed($num1,$num2);
13821:         }
13822:     } else {
13823: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13824:     }
13825: }
13826: 
13827: sub latest_receipt_algorithm_id {
13828:     return 'receipt3';
13829: }
13830: 
13831: sub recunique {
13832:     my $fucourseid=shift;
13833:     my $unique;
13834:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13835: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13836: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13837:     } else {
13838: 	$unique=$perlvar{'lonReceipt'};
13839:     }
13840:     return unpack("%32C*",$unique);
13841: }
13842: 
13843: sub recprefix {
13844:     my $fucourseid=shift;
13845:     my $prefix;
13846:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13847: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13848: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13849:     } else {
13850: 	$prefix=$perlvar{'lonHostID'};
13851:     }
13852:     return unpack("%32C*",$prefix);
13853: }
13854: 
13855: sub ireceipt {
13856:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13857: 
13858:     my $return =&recprefix($fucourseid).'-';
13859: 
13860:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13861: 	$env{'request.state'} eq 'construct') {
13862: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13863: 	return $return;
13864:     }
13865: 
13866:     my $cuname=unpack("%32C*",$funame);
13867:     my $cudom=unpack("%32C*",$fudom);
13868:     my $cucourseid=unpack("%32C*",$fucourseid);
13869:     my $cusymb=unpack("%32C*",$fusymb);
13870:     my $cunique=&recunique($fucourseid);
13871:     my $cpart=unpack("%32S*",$part);
13872:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13873: 
13874: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13875: 			       
13876: 	$return.= ($cunique%$cuname+
13877: 		   $cunique%$cudom+
13878: 		   $cusymb%$cuname+
13879: 		   $cusymb%$cudom+
13880: 		   $cucourseid%$cuname+
13881: 		   $cucourseid%$cudom+
13882: 		   $cpart%$cuname+
13883: 		   $cpart%$cudom);
13884:     } else {
13885: 	$return.= ($cunique%$cuname+
13886: 		   $cunique%$cudom+
13887: 		   $cusymb%$cuname+
13888: 		   $cusymb%$cudom+
13889: 		   $cucourseid%$cuname+
13890: 		   $cucourseid%$cudom);
13891:     }
13892:     return $return;
13893: }
13894: 
13895: sub receipt {
13896:     my ($part)=@_;
13897:     my ($symb,$courseid,$domain,$name) = &whichuser();
13898:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13899: }
13900: 
13901: sub whichuser {
13902:     my ($passedsymb)=@_;
13903:     my ($symb,$courseid,$domain,$name,$publicuser);
13904:     if (defined($env{'form.grade_symb'})) {
13905: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13906: 	my $allowed=&allowed('vgr',$tmp_courseid);
13907: 	if (!$allowed &&
13908: 	    exists($env{'request.course.sec'}) &&
13909: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13910: 	    $allowed=&allowed('vgr',$tmp_courseid.
13911: 			      '/'.$env{'request.course.sec'});
13912: 	}
13913: 	if ($allowed) {
13914: 	    ($symb)=&get_env_multiple('form.grade_symb');
13915: 	    $courseid=$tmp_courseid;
13916: 	    ($domain)=&get_env_multiple('form.grade_domain');
13917: 	    ($name)=&get_env_multiple('form.grade_username');
13918: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13919: 	}
13920:     }
13921:     if (!$passedsymb) {
13922: 	$symb=&symbread();
13923:     } else {
13924: 	$symb=$passedsymb;
13925:     }
13926:     $courseid=$env{'request.course.id'};
13927:     $domain=$env{'user.domain'};
13928:     $name=$env{'user.name'};
13929:     if ($name eq 'public' && $domain eq 'public') {
13930: 	if (!defined($env{'form.username'})) {
13931: 	    $env{'form.username'}.=time.rand(10000000);
13932: 	}
13933: 	$name.=$env{'form.username'};
13934:     }
13935:     return ($symb,$courseid,$domain,$name,$publicuser);
13936: 
13937: }
13938: 
13939: # ------------------------------------------------------------ Serves up a file
13940: # returns either the contents of the file or 
13941: # -1 if the file doesn't exist
13942: #
13943: # if the target is a file that was uploaded via DOCS, 
13944: # a check will be made to see if a current copy exists on the local server,
13945: # if it does this will be served, otherwise a copy will be retrieved from
13946: # the home server for the course and stored in /home/httpd/html/userfiles on
13947: # the local server.   
13948: 
13949: sub getfile {
13950:     my ($file) = @_;
13951:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13952:     &repcopy($file);
13953:     return &readfile($file);
13954: }
13955: 
13956: sub repcopy_userfile {
13957:     my ($file)=@_;
13958:     my $londocroot = $perlvar{'lonDocRoot'};
13959:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13960:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13961:     my ($cdom,$cnum,$filename) = 
13962: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13963:     my $uri="/uploaded/$cdom/$cnum/$filename";
13964:     if (-e "$file") {
13965: # we already have a local copy, check it out
13966: 	my @fileinfo = stat($file);
13967: 	my $rtncode;
13968: 	my $info;
13969: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13970: 	if ($lwpresp ne 'ok') {
13971: # there is no such file anymore, even though we had a local copy
13972: 	    if ($rtncode eq '404') {
13973: 		unlink($file);
13974: 	    }
13975: 	    return -1;
13976: 	}
13977: 	if ($info < $fileinfo[9]) {
13978: # nice, the file we have is up-to-date, just say okay
13979: 	    return 'ok';
13980: 	} else {
13981: # the file is outdated, get rid of it
13982: 	    unlink($file);
13983: 	}
13984:     }
13985: # one way or the other, at this point, we don't have the file
13986: # construct the correct path for the file
13987:     my @parts = ($cdom,$cnum); 
13988:     if ($filename =~ m|^(.+)/[^/]+$|) {
13989: 	push @parts, split(/\//,$1);
13990:     }
13991:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13992:     foreach my $part (@parts) {
13993: 	$path .= '/'.$part;
13994: 	if (!-e $path) {
13995: 	    mkdir($path,0770);
13996: 	}
13997:     }
13998: # now the path exists for sure
13999: # get a user agent
14000:     my $transferfile=$file.'.in.transfer';
14001: # FIXME: this should flock
14002:     if (-e $transferfile) { return 'ok'; }
14003:     my $request;
14004:     $uri=~s/^\///;
14005:     my $homeserver = &homeserver($cnum,$cdom);
14006:     my $hostname = &hostname($homeserver);
14007:     my $protocol = $protocol{$homeserver};
14008:     $protocol = 'http' if ($protocol ne 'https');
14009:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14010:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14011: # did it work?
14012:     if ($response->is_error()) {
14013: 	unlink($transferfile);
14014: 	&logthis("Userfile repcopy failed for $uri");
14015: 	return -1;
14016:     }
14017: # worked, rename the transfer file
14018:     rename($transferfile,$file);
14019:     return 'ok';
14020: }
14021: 
14022: sub tokenwrapper {
14023:     my $uri=shift;
14024:     $uri=~s|^https?\://([^/]+)||;
14025:     $uri=~s|^/||;
14026:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14027:     my $token=$1;
14028:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14029:     if ($udom && $uname && $file) {
14030: 	$file=~s|(\?\.*)*$||;
14031:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14032:         my $homeserver = &homeserver($uname,$udom);
14033:         my $hostname = &hostname($homeserver);
14034:         my $protocol = $protocol{$homeserver};
14035:         $protocol = 'http' if ($protocol ne 'https');
14036:         return $protocol.'://'.$hostname.'/'.$uri.
14037:                (($uri=~/\?/)?'&':'?').'token='.$token.
14038:                                '&tokenissued='.$perlvar{'lonHostID'};
14039:     } else {
14040:         return '/adm/notfound.html';
14041:     }
14042: }
14043: 
14044: # call with reqtype HEAD: get last modification time
14045: # call with reqtype GET: get the file contents
14046: # Do not call this with reqtype GET for large files! It loads everything into memory
14047: #
14048: sub getuploaded {
14049:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14050:     $uri=~s/^\///;
14051:     my $homeserver = &homeserver($cnum,$cdom);
14052:     my $hostname = &hostname($homeserver);
14053:     my $protocol = $protocol{$homeserver};
14054:     $protocol = 'http' if ($protocol ne 'https');
14055:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14056:     my $request=new HTTP::Request($reqtype,$uri);
14057:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14058:     $$rtncode = $response->code;
14059:     if (! $response->is_success()) {
14060: 	return 'failed';
14061:     }      
14062:     if ($reqtype eq 'HEAD') {
14063: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14064:     } elsif ($reqtype eq 'GET') {
14065: 	$$info = $response->content;
14066:     }
14067:     return 'ok';
14068: }
14069: 
14070: sub readfile {
14071:     my $file = shift;
14072:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14073:     my $fh;
14074:     open($fh,"<",$file);
14075:     my $a='';
14076:     while (my $line = <$fh>) { $a .= $line; }
14077:     return $a;
14078: }
14079: 
14080: sub filelocation {
14081:     my ($dir,$file) = @_;
14082:     my $location;
14083:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14084: 
14085:     if ($file =~ m-^/adm/-) {
14086: 	$file=~s-^/adm/wrapper/-/-;
14087: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14088:     }
14089: 
14090:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14091:         $location = $file;
14092:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14093:         my ($udom,$uname,$filename)=
14094:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14095:         my $home=&homeserver($uname,$udom);
14096:         my $is_me=0;
14097:         my @ids=&current_machine_ids();
14098:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14099:         if ($is_me) {
14100:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14101:         } else {
14102:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14103:   	      $udom.'/'.$uname.'/'.$filename;
14104:         }
14105:     } elsif ($file =~ m-^/adm/-) {
14106: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14107:     } else {
14108:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14109:         $file=~s:^/(res|priv)/:/:;
14110:         my $space=$1;
14111:         if ( !( $file =~ m:^/:) ) {
14112:             $location = $dir. '/'.$file;
14113:         } else {
14114:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14115:         }
14116:     }
14117:     $location=~s://+:/:g; # remove duplicate /
14118:     while ($location=~m{/\.\./}) {
14119: 	if ($location =~ m{/[^/]+/\.\./}) {
14120: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14121: 	} else {
14122: 	    $location=~ s{/\.\./}{/}g;
14123: 	}
14124:     } #remove dir/..
14125:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14126:     return $location;
14127: }
14128: 
14129: sub hreflocation {
14130:     my ($dir,$file)=@_;
14131:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14132: 	$file=filelocation($dir,$file);
14133:     } elsif ($file=~m-^/adm/-) {
14134: 	$file=~s-^/adm/wrapper/-/-;
14135: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14136:     }
14137:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14138: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14139:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14140: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14141: 	        {/uploaded/$1/$2/}x;
14142:     }
14143:     if ($file=~ m{^/userfiles/}) {
14144: 	$file =~ s{^/userfiles/}{/uploaded/};
14145:     }
14146:     return $file;
14147: }
14148: 
14149: 
14150: 
14151: 
14152: 
14153: sub current_machine_domains {
14154:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14155: }
14156: 
14157: sub machine_domains {
14158:     my ($hostname) = @_;
14159:     my @domains;
14160:     my %hostname = &all_hostnames();
14161:     while( my($id, $name) = each(%hostname)) {
14162: #	&logthis("-$id-$name-$hostname-");
14163: 	if ($hostname eq $name) {
14164: 	    push(@domains,&host_domain($id));
14165: 	}
14166:     }
14167:     return @domains;
14168: }
14169: 
14170: sub current_machine_ids {
14171:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14172: }
14173: 
14174: sub machine_ids {
14175:     my ($hostname) = @_;
14176:     $hostname ||= &hostname($perlvar{'lonHostID'});
14177:     my @ids;
14178:     my %name_to_host = &all_names();
14179:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14180: 	return @{ $name_to_host{$hostname} };
14181:     }
14182:     return;
14183: }
14184: 
14185: sub additional_machine_domains {
14186:     my @domains;
14187:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
14188:     while( my $line = <$fh>) {
14189:         $line =~ s/\s//g;
14190:         push(@domains,$line);
14191:     }
14192:     return @domains;
14193: }
14194: 
14195: sub default_login_domain {
14196:     my $domain = $perlvar{'lonDefDomain'};
14197:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14198:     foreach my $posdom (&current_machine_domains(),
14199:                         &additional_machine_domains()) {
14200:         if (lc($posdom) eq lc($testdomain)) {
14201:             $domain=$posdom;
14202:             last;
14203:         }
14204:     }
14205:     return $domain;
14206: }
14207: 
14208: sub shared_institution {
14209:     my ($dom) = @_;
14210:     my $same_intdom;
14211:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
14212:     if ($hostintdom ne '') {
14213:         my %iphost = &get_iphost();
14214:         my $primary_id = &domain($dom,'primary');
14215:         my $primary_ip = &get_host_ip($primary_id);
14216:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14217:             foreach my $id (@{$iphost{$primary_ip}}) {
14218:                 my $intdom = &internet_dom($id);
14219:                 if ($intdom eq $hostintdom) {
14220:                     $same_intdom = 1;
14221:                     last;
14222:                 }
14223:             }
14224:         }
14225:     }
14226:     return $same_intdom;
14227: }
14228: 
14229: sub uses_sts {
14230:     my ($ignore_cache) = @_;
14231:     my $lonhost = $perlvar{'lonHostID'};
14232:     my $hostname = &hostname($lonhost);
14233:     my $sts_on;
14234:     if ($protocol{$lonhost} eq 'https') {
14235:         my $cachetime = 12*3600;
14236:         if (!$ignore_cache) {
14237:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14238:             if (defined($cached)) {
14239:                 return $sts_on;
14240:             }
14241:         }
14242:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14243:         my $request=new HTTP::Request('HEAD',$url);
14244:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14245:         if ($response->is_success) {
14246:             my $has_sts = $response->header('Strict-Transport-Security');
14247:             if ($has_sts eq '') {
14248:                 $sts_on = 0;
14249:             } else {
14250:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14251:                     my $maxage = $1;
14252:                     if ($maxage) {
14253:                         $sts_on = 1;
14254:                     } else {
14255:                         $sts_on = 0;
14256:                     }
14257:                 } else {
14258:                     $sts_on = 0;
14259:                 }
14260:             }
14261:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14262:         }
14263:     }
14264:     return;
14265: }
14266: 
14267: # ------------------------------------------------------------- Declutters URLs
14268: 
14269: sub declutter {
14270:     my $thisfn=shift;
14271:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14272:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14273:         $thisfn=~s{^/home/httpd/html}{};
14274:     }
14275:     $thisfn=~s/^\///;
14276:     $thisfn=~s|^adm/wrapper/||;
14277:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14278:     $thisfn=~s/^res\///;
14279:     $thisfn=~s/^priv\///;
14280:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14281:         $thisfn=~s/\?.+$//;
14282:     }
14283:     return $thisfn;
14284: }
14285: 
14286: # ------------------------------------------------------------- Clutter up URLs
14287: 
14288: sub clutter {
14289:     my $thisfn='/'.&declutter(shift);
14290:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14291: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14292:        $thisfn='/res'.$thisfn; 
14293:     }
14294:     if ($thisfn !~m|^/adm|) {
14295: 	if ($thisfn =~ m|^/ext/|) {
14296: 	    $thisfn='/adm/wrapper'.$thisfn;
14297: 	} else {
14298: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14299: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14300: 	    if ($embstyle eq 'ssi'
14301: 		|| ($embstyle eq 'hdn')
14302: 		|| ($embstyle eq 'rat')
14303: 		|| ($embstyle eq 'prv')
14304: 		|| ($embstyle eq 'ign')) {
14305: 		#do nothing with these
14306: 	    } elsif (($embstyle eq 'img') 
14307: 		|| ($embstyle eq 'emb')
14308: 		|| ($embstyle eq 'wrp')) {
14309: 		$thisfn='/adm/wrapper'.$thisfn;
14310: 	    } elsif ($embstyle eq 'unk'
14311: 		     && $thisfn!~/\.(sequence|page)$/) {
14312: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14313: 	    } else {
14314: #		&logthis("Got a blank emb style");
14315: 	    }
14316: 	}
14317:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14318:         $thisfn='/adm/wrapper'.$thisfn;
14319:     }
14320:     return $thisfn;
14321: }
14322: 
14323: sub clutter_with_no_wrapper {
14324:     my $uri = &clutter(shift);
14325:     if ($uri =~ m-^/adm/-) {
14326: 	$uri =~ s-^/adm/wrapper/-/-;
14327: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14328:     }
14329:     return $uri;
14330: }
14331: 
14332: sub freeze_escape {
14333:     my ($value)=@_;
14334:     if (ref($value)) {
14335: 	$value=&nfreeze($value);
14336: 	return '__FROZEN__'.&escape($value);
14337:     }
14338:     return &escape($value);
14339: }
14340: 
14341: 
14342: sub thaw_unescape {
14343:     my ($value)=@_;
14344:     if ($value =~ /^__FROZEN__/) {
14345: 	substr($value,0,10,undef);
14346: 	$value=&unescape($value);
14347: 	return &thaw($value);
14348:     }
14349:     return &unescape($value);
14350: }
14351: 
14352: sub correct_line_ends {
14353:     my ($result)=@_;
14354:     $$result =~s/\r\n/\n/mg;
14355:     $$result =~s/\r/\n/mg;
14356: }
14357: # ================================================================ Main Program
14358: 
14359: sub goodbye {
14360:    &logthis("Starting Shut down");
14361: #not converted to using infrastruture and probably shouldn't be
14362:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14363: #converted
14364: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14365:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14366: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14367: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14368: #1.1 only
14369: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14370: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14371: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14372: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14373:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14374:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14375:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14376:    &flushcourselogs();
14377:    &logthis("Shutting down");
14378: }
14379: 
14380: sub get_dns {
14381:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14382:     if (!$ignore_cache) {
14383: 	my ($content,$cached)=
14384: 	    &Apache::lonnet::is_cached_new('dns',$url);
14385: 	if ($cached) {
14386: 	    &$func($content,$hashref);
14387: 	    return;
14388: 	}
14389:     }
14390: 
14391:     my %alldns;
14392:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14393:         foreach my $dns (<$config>) {
14394: 	    next if ($dns !~ /^\^(\S*)/x);
14395:             my $line = $1;
14396:             my ($host,$protocol) = split(/:/,$line);
14397:             if ($protocol ne 'https') {
14398:                 $protocol = 'http';
14399:             }
14400: 	    $alldns{$host} = $protocol;
14401:         }
14402:         close($config);
14403:     }
14404:     while (%alldns) {
14405: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14406: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14407:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14408:         delete($alldns{$dns});
14409: 	next if ($response->is_error());
14410:         if ($url eq '/adm/dns/loncapaCRL') {
14411:             return &$func($response);
14412:         } else {
14413: 	    my @content = split("\n",$response->content);
14414: 	    unless ($nocache) {
14415: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14416: 	    }
14417: 	    &$func(\@content,$hashref);
14418:             return;
14419:         }
14420:     }
14421:     my $which = (split('/',$url,4))[3];
14422:     if ($which eq 'loncapaCRL') {
14423:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14424:         if (-e $diskfile) {
14425:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14426:         } else {
14427:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14428:         }
14429:     } else {
14430:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14431:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14432:             my @content = <$config>;
14433:             close($config);
14434:             &$func(\@content,$hashref);
14435:         }
14436:     }
14437:     return;
14438: }
14439: 
14440: # ------------------------------------------------------Get DNS checksums file
14441: sub parse_dns_checksums_tab {
14442:     my ($lines,$hashref) = @_;
14443:     my $lonhost = $perlvar{'lonHostID'};
14444:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14445:     my $loncaparev = &get_server_loncaparev($machine_dom);
14446:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14447:     my $webconfdir = '/etc/httpd/conf';
14448:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14449:         $webconfdir = '/etc/apache2';
14450:     } elsif ($distro =~ /^sles(\d+)$/) {
14451:         if ($1 >= 10) {
14452:             $webconfdir = '/etc/apache2';
14453:         }
14454:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14455:         if ($1 >= 10.0) {
14456:             $webconfdir = '/etc/apache2';
14457:         }
14458:     }
14459:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14460:     my (%chksum,%revnum);
14461:     if (ref($lines) eq 'ARRAY') {
14462:         chomp(@{$lines});
14463:         my $version = shift(@{$lines});
14464:         if ($version eq $release) {  
14465:             foreach my $line (@{$lines}) {
14466:                 my ($file,$version,$shasum) = split(/,/,$line);
14467:                 if ($file =~ m{^/etc/httpd/conf}) {
14468:                     if ($webconfdir eq '/etc/apache2') {
14469:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14470:                     }
14471:                 }
14472:                 $chksum{$file} = $shasum;
14473:                 $revnum{$file} = $version;
14474:             }
14475:             if (ref($hashref) eq 'HASH') {
14476:                 %{$hashref} = (
14477:                                 sums     => \%chksum,
14478:                                 versions => \%revnum,
14479:                               );
14480:             }
14481:         }
14482:     }
14483:     return;
14484: }
14485: 
14486: sub fetch_dns_checksums {
14487:     my %checksums;
14488:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14489:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14490:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14491:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14492:              \%checksums);
14493:     return \%checksums;
14494: }
14495: 
14496: sub fetch_crl_pemfile {
14497:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14498: }
14499: 
14500: sub save_crl_pem {
14501:     my ($response) = @_;
14502:     my ($msg,$hadchanges);
14503:     if (ref($response)) {
14504:         my $now = time;
14505:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14506:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14507:         if (open(my $fh,'>',"$tmpcrl")) {
14508:             print $fh $response->content;
14509:             close($fh);
14510:             if (-e $lonca) {
14511:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14512:                     my $check = <PIPE>;
14513:                     close(PIPE);
14514:                     chomp($check);
14515:                     if ($check eq 'verify OK') {
14516:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14517:                         my $backup;
14518:                         if (-e $dest) {
14519:                             if (&File::Copy::move($dest,"$dest.bak")) {
14520:                                 $backup = 'ok';
14521:                             }
14522:                         }
14523:                         if (&File::Copy::move($tmpcrl,$dest)) {
14524:                             $msg = 'ok';
14525:                             if ($backup) {
14526:                                 my (%oldnums,%newnums);
14527:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14528:                                     while (<PIPE>) {
14529:                                         $oldnums{(split(/:/))[1]} = 1;
14530:                                     }
14531:                                     close(PIPE);
14532:                                 }
14533:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14534:                                     while(<PIPE>) {
14535:                                         $newnums{(split(/:/))[1]} = 1;
14536:                                     }
14537:                                     close(PIPE);
14538:                                 }
14539:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14540:                                     unless (exists($oldnums{$key})) {
14541:                                         $hadchanges = 1;
14542:                                         last;
14543:                                     }
14544:                                 }
14545:                                 unless ($hadchanges) {
14546:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14547:                                         unless (exists($newnums{$key})) {
14548:                                             $hadchanges = 1;
14549:                                             last;
14550:                                         }
14551:                                     }
14552:                                 }
14553:                             }
14554:                         }
14555:                     } else {
14556:                         unlink($tmpcrl);
14557:                     }
14558:                 } else {
14559:                     unlink($tmpcrl);
14560:                 }
14561:             } else {
14562:                 unlink($tmpcrl);
14563:             }
14564:         }
14565:     }
14566:     return ($msg,$hadchanges);
14567: }
14568: 
14569: # ------------------------------------------------------------ Read domain file
14570: {
14571:     my $loaded;
14572:     my %domain;
14573: 
14574:     sub parse_domain_tab {
14575: 	my ($lines) = @_;
14576: 	foreach my $line (@$lines) {
14577: 	    next if ($line =~ /^(\#|\s*$ )/x);
14578: 
14579: 	    chomp($line);
14580: 	    my ($name,@elements) = split(/:/,$line,9);
14581: 	    my %this_domain;
14582: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14583: 			       'lang_def', 'city', 'longi', 'lati',
14584: 			       'primary') {
14585: 		$this_domain{$field} = shift(@elements);
14586: 	    }
14587: 	    $domain{$name} = \%this_domain;
14588: 	}
14589:     }
14590: 
14591:     sub reset_domain_info {
14592: 	undef($loaded);
14593: 	undef(%domain);
14594:     }
14595: 
14596:     sub load_domain_tab {
14597: 	my ($ignore_cache,$nocache) = @_;
14598: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14599: 	my $fh;
14600: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14601: 	    my @lines = <$fh>;
14602: 	    &parse_domain_tab(\@lines);
14603: 	}
14604: 	close($fh);
14605: 	$loaded = 1;
14606:     }
14607: 
14608:     sub domain {
14609: 	&load_domain_tab() if (!$loaded);
14610: 
14611: 	my ($name,$what) = @_;
14612: 	return if ( !exists($domain{$name}) );
14613: 
14614: 	if (!$what) {
14615: 	    return $domain{$name}{'description'};
14616: 	}
14617: 	return $domain{$name}{$what};
14618:     }
14619: 
14620:     sub domain_info {
14621:         &load_domain_tab() if (!$loaded);
14622:         return %domain;
14623:     }
14624: 
14625: }
14626: 
14627: 
14628: # ------------------------------------------------------------- Read hosts file
14629: {
14630:     my %hostname;
14631:     my %hostdom;
14632:     my %libserv;
14633:     my $loaded;
14634:     my %name_to_host;
14635:     my %internetdom;
14636:     my %LC_dns_serv;
14637: 
14638:     sub parse_hosts_tab {
14639: 	my ($file) = @_;
14640: 	foreach my $configline (@$file) {
14641: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14642:             chomp($configline);
14643: 	    if ($configline =~ /^\^/) {
14644:                 if ($configline =~ /^\^([\w.\-]+)/) {
14645:                     $LC_dns_serv{$1} = 1;
14646:                 }
14647:                 next;
14648:             }
14649: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14650: 	    $name=~s/\s//g;
14651: 	    if ($id && $domain && $role && $name) {
14652:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14653:                     my $curr = $hostname{$id};
14654:                     my $skip;
14655:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14656:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14657:                             $skip = 1;
14658:                         } else {
14659:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14660:                         }
14661:                     }
14662:                     unless ($skip) {
14663:                         push(@{$name_to_host{$name}},$id);
14664:                     }
14665:                 } else {
14666:                     push(@{$name_to_host{$name}},$id);
14667:                 }
14668: 		$hostname{$id}=$name;
14669: 		$hostdom{$id}=$domain;
14670: 		if ($role eq 'library') { $libserv{$id}=$name; }
14671:                 if (defined($protocol)) {
14672:                     if ($protocol eq 'https') {
14673:                         $protocol{$id} = $protocol;
14674:                     } else {
14675:                         $protocol{$id} = 'http'; 
14676:                     }
14677:                 } else {
14678:                     $protocol{$id} = 'http';
14679:                 }
14680:                 if (defined($intdom)) {
14681:                     $internetdom{$id} = $intdom;
14682:                 }
14683: 	    }
14684: 	}
14685:     }
14686:     
14687:     sub reset_hosts_info {
14688: 	&purge_remembered();
14689: 	&reset_domain_info();
14690: 	&reset_hosts_ip_info();
14691:         undef(%internetdom);
14692: 	undef(%name_to_host);
14693: 	undef(%hostname);
14694: 	undef(%hostdom);
14695: 	undef(%libserv);
14696: 	undef($loaded);
14697:     }
14698: 
14699:     sub load_hosts_tab {
14700: 	my ($ignore_cache,$nocache) = @_;
14701: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14702: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14703: 	my @config = <$config>;
14704: 	&parse_hosts_tab(\@config);
14705: 	close($config);
14706: 	$loaded=1;
14707:     }
14708: 
14709:     sub hostname {
14710: 	&load_hosts_tab() if (!$loaded);
14711: 
14712: 	my ($lonid) = @_;
14713: 	return $hostname{$lonid};
14714:     }
14715: 
14716:     sub all_hostnames {
14717: 	&load_hosts_tab() if (!$loaded);
14718: 
14719: 	return %hostname;
14720:     }
14721: 
14722:     sub all_names {
14723:         my ($ignore_cache,$nocache) = @_;
14724: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14725: 
14726: 	return %name_to_host;
14727:     }
14728: 
14729:     sub all_host_domain {
14730:         &load_hosts_tab() if (!$loaded);
14731:         return %hostdom;
14732:     }
14733: 
14734:     sub all_host_intdom {
14735:         &load_hosts_tab() if (!$loaded);
14736:         return %internetdom;
14737:     }
14738: 
14739:     sub is_library {
14740: 	&load_hosts_tab() if (!$loaded);
14741: 
14742: 	return exists($libserv{$_[0]});
14743:     }
14744: 
14745:     sub all_library {
14746: 	&load_hosts_tab() if (!$loaded);
14747: 
14748: 	return %libserv;
14749:     }
14750: 
14751:     sub unique_library {
14752: 	#2x reverse removes all hostnames that appear more than once
14753:         my %unique = reverse &all_library();
14754:         return reverse %unique;
14755:     }
14756: 
14757:     sub get_servers {
14758: 	&load_hosts_tab() if (!$loaded);
14759: 
14760: 	my ($domain,$type) = @_;
14761: 	my %possible_hosts = ($type eq 'library') ? %libserv
14762: 	                                          : %hostname;
14763: 	my %result;
14764: 	if (ref($domain) eq 'ARRAY') {
14765: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14766: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14767: 		    $result{$host} = $hostname;
14768: 		}
14769: 	    }
14770: 	} else {
14771: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14772: 		if ($hostdom{$host} eq $domain) {
14773: 		    $result{$host} = $hostname;
14774: 		}
14775: 	    }
14776: 	}
14777: 	return %result;
14778:     }
14779: 
14780:     sub get_unique_servers {
14781:         my %unique = reverse &get_servers(@_);
14782: 	return reverse %unique;
14783:     }
14784: 
14785:     sub host_domain {
14786: 	&load_hosts_tab() if (!$loaded);
14787: 
14788: 	my ($lonid) = @_;
14789: 	return $hostdom{$lonid};
14790:     }
14791: 
14792:     sub all_domains {
14793: 	&load_hosts_tab() if (!$loaded);
14794: 
14795: 	my %seen;
14796: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14797: 	return @uniq;
14798:     }
14799: 
14800:     sub internet_dom {
14801:         &load_hosts_tab() if (!$loaded);
14802: 
14803:         my ($lonid) = @_;
14804:         return $internetdom{$lonid};
14805:     }
14806: 
14807:     sub is_LC_dns {
14808:         &load_hosts_tab() if (!$loaded);
14809: 
14810:         my ($hostname) = @_;
14811:         return exists($LC_dns_serv{$hostname});
14812:     }
14813: 
14814: }
14815: 
14816: { 
14817:     my %iphost;
14818:     my %name_to_ip;
14819:     my %lonid_to_ip;
14820: 
14821:     sub get_hosts_from_ip {
14822: 	my ($ip) = @_;
14823: 	my %iphosts = &get_iphost();
14824: 	if (ref($iphosts{$ip})) {
14825: 	    return @{$iphosts{$ip}};
14826: 	}
14827: 	return;
14828:     }
14829:     
14830:     sub reset_hosts_ip_info {
14831: 	undef(%iphost);
14832: 	undef(%name_to_ip);
14833: 	undef(%lonid_to_ip);
14834:     }
14835: 
14836:     sub get_host_ip {
14837: 	my ($lonid) = @_;
14838: 	if (exists($lonid_to_ip{$lonid})) {
14839: 	    return $lonid_to_ip{$lonid};
14840: 	}
14841: 	my $name=&hostname($lonid);
14842:    	my $ip = gethostbyname($name);
14843: 	return if (!$ip || length($ip) ne 4);
14844: 	$ip=inet_ntoa($ip);
14845: 	$name_to_ip{$name}   = $ip;
14846: 	$lonid_to_ip{$lonid} = $ip;
14847: 	return $ip;
14848:     }
14849:     
14850:     sub get_iphost {
14851: 	my ($ignore_cache,$nocache) = @_;
14852: 
14853: 	if (!$ignore_cache) {
14854: 	    if (%iphost) {
14855: 		return %iphost;
14856: 	    }
14857: 	    my ($ip_info,$cached)=
14858: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14859: 	    if ($cached) {
14860: 		%iphost      = %{$ip_info->[0]};
14861: 		%name_to_ip  = %{$ip_info->[1]};
14862: 		%lonid_to_ip = %{$ip_info->[2]};
14863: 		return %iphost;
14864: 	    }
14865: 	}
14866: 
14867: 	# get yesterday's info for fallback
14868: 	my %old_name_to_ip;
14869: 	my ($ip_info,$cached)=
14870: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14871: 	if ($cached) {
14872: 	    %old_name_to_ip = %{$ip_info->[1]};
14873: 	}
14874: 
14875: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14876: 	foreach my $name (keys(%name_to_host)) {
14877: 	    my $ip;
14878: 	    if (!exists($name_to_ip{$name})) {
14879: 		$ip = gethostbyname($name);
14880: 		if (!$ip || length($ip) ne 4) {
14881: 		    if (defined($old_name_to_ip{$name})) {
14882: 			$ip = $old_name_to_ip{$name};
14883: 			&logthis("Can't find $name defaulting to old $ip");
14884: 		    } else {
14885: 			&logthis("Name $name no IP found");
14886: 			next;
14887: 		    }
14888: 		} else {
14889: 		    $ip=inet_ntoa($ip);
14890: 		}
14891: 		$name_to_ip{$name} = $ip;
14892: 	    } else {
14893: 		$ip = $name_to_ip{$name};
14894: 	    }
14895: 	    foreach my $id (@{ $name_to_host{$name} }) {
14896: 		$lonid_to_ip{$id} = $ip;
14897: 	    }
14898: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14899: 	}
14900:         unless ($nocache) {
14901: 	    &do_cache_new('iphost','iphost',
14902: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14903: 		          48*60*60);
14904:         }
14905: 
14906: 	return %iphost;
14907:     }
14908: 
14909:     #
14910:     #  Given a DNS returns the loncapa host name for that DNS 
14911:     # 
14912:     sub host_from_dns {
14913:         my ($dns) = @_;
14914:         my @hosts;
14915:         my $ip;
14916: 
14917:         if (exists($name_to_ip{$dns})) {
14918:             $ip = $name_to_ip{$dns};
14919:         }
14920:         if (!$ip) {
14921:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14922:             if (length($ip) == 4) { 
14923: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14924:             }
14925:         }
14926:         if ($ip) {
14927: 	    @hosts = get_hosts_from_ip($ip);
14928: 	    return $hosts[0];
14929:         }
14930:         return undef;
14931:     }
14932: 
14933:     sub get_internet_names {
14934:         my ($lonid) = @_;
14935:         return if ($lonid eq '');
14936:         my ($idnref,$cached)=
14937:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14938:         if ($cached) {
14939:             return $idnref;
14940:         }
14941:         my $ip = &get_host_ip($lonid);
14942:         my @hosts = &get_hosts_from_ip($ip);
14943:         my %iphost = &get_iphost();
14944:         my (@idns,%seen);
14945:         foreach my $id (@hosts) {
14946:             my $dom = &host_domain($id);
14947:             my $prim_id = &domain($dom,'primary');
14948:             my $prim_ip = &get_host_ip($prim_id);
14949:             next if ($seen{$prim_ip});
14950:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14951:                 foreach my $id (@{$iphost{$prim_ip}}) {
14952:                     my $intdom = &internet_dom($id);
14953:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14954:                         push(@idns,$intdom);
14955:                     }
14956:                 }
14957:             }
14958:             $seen{$prim_ip} = 1;
14959:         }
14960:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14961:     }
14962: 
14963: }
14964: 
14965: sub all_loncaparevs {
14966:     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);
14967: }
14968: 
14969: # ---------------------------------------------------------- Read loncaparev table
14970: {
14971:     sub load_loncaparevs { 
14972:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14973:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14974:                 while (my $configline=<$config>) {
14975:                     chomp($configline);
14976:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14977:                     $loncaparevs{$hostid}=$loncaparev;
14978:                 }
14979:                 close($config);
14980:             }
14981:         }
14982:     }
14983: }
14984: 
14985: # ---------------------------------------------------------- Read serverhostID table
14986: {
14987:     sub load_serverhomeIDs {
14988:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14989:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14990:                 while (my $configline=<$config>) {
14991:                     chomp($configline);
14992:                     my ($name,$id)=split(/:/,$configline);
14993:                     $serverhomeIDs{$name}=$id;
14994:                 }
14995:                 close($config);
14996:             }
14997:         }
14998:     }
14999: }
15000: 
15001: 
15002: BEGIN {
15003: 
15004: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15005:     unless ($readit) {
15006: {
15007:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15008:     %perlvar = (%perlvar,%{$configvars});
15009: }
15010: 
15011: 
15012: # ------------------------------------------------------ Read spare server file
15013: {
15014:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15015: 
15016:     while (my $configline=<$config>) {
15017:        chomp($configline);
15018:        if ($configline) {
15019: 	   my ($host,$type) = split(':',$configline,2);
15020: 	   if (!defined($type) || $type eq '') { $type = 'default' };
15021: 	   push(@{ $spareid{$type} }, $host);
15022:        }
15023:     }
15024:     close($config);
15025: }
15026: # ------------------------------------------------------------ Read permissions
15027: {
15028:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15029: 
15030:     while (my $configline=<$config>) {
15031: 	chomp($configline);
15032: 	if ($configline) {
15033: 	    my ($role,$perm)=split(/ /,$configline);
15034: 	    if ($perm ne '') { $pr{$role}=$perm; }
15035: 	}
15036:     }
15037:     close($config);
15038: }
15039: 
15040: # -------------------------------------------- Read plain texts for permissions
15041: {
15042:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15043: 
15044:     while (my $configline=<$config>) {
15045: 	chomp($configline);
15046: 	if ($configline) {
15047: 	    my ($short,@plain)=split(/:/,$configline);
15048:             %{$prp{$short}} = ();
15049: 	    if (@plain > 0) {
15050:                 $prp{$short}{'std'} = $plain[0];
15051:                 for (my $i=1; $i<@plain; $i++) {
15052:                     $prp{$short}{'alt'.$i} = $plain[$i];  
15053:                 }
15054:             }
15055: 	}
15056:     }
15057:     close($config);
15058: }
15059: 
15060: # ---------------------------------------------------------- Read package table
15061: {
15062:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15063: 
15064:     while (my $configline=<$config>) {
15065: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15066: 	chomp($configline);
15067: 	my ($short,$plain)=split(/:/,$configline);
15068: 	my ($pack,$name)=split(/\&/,$short);
15069: 	if ($plain ne '') {
15070: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
15071: 	    $packagetab{$short}=$plain; 
15072: 	}
15073:     }
15074:     close($config);
15075: }
15076: 
15077: # ---------------------------------------------------------- Read loncaparev table
15078: 
15079: &load_loncaparevs();
15080: 
15081: # ---------------------------------------------------------- Read serverhostID table
15082: 
15083: &load_serverhomeIDs();
15084: 
15085: # ---------------------------------------------------------- Read releaseslist XML
15086: {
15087:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15088:     if (-e $file) {
15089:         my $parser = HTML::LCParser->new($file);
15090:         while (my $token = $parser->get_token()) {
15091:             if ($token->[0] eq 'S') {
15092:                 my $item = $token->[1];
15093:                 my $name = $token->[2]{'name'};
15094:                 my $value = $token->[2]{'value'};
15095:                 my $valuematch = $token->[2]{'valuematch'};
15096:                 my $namematch = $token->[2]{'namematch'};
15097:                 if ($item eq 'parameter') {
15098:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15099:                         my $release = $parser->get_text();
15100:                         $release =~ s/(^\s*|\s*$ )//gx;
15101:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15102:                     }
15103:                 } elsif ($item ne '' && $name ne '') {
15104:                     my $release = $parser->get_text();
15105:                     $release =~ s/(^\s*|\s*$ )//gx;
15106:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
15107:                 }
15108:             }
15109:         }
15110:     }
15111: }
15112: 
15113: # ---------------------------------------------------------- Read managers table
15114: {
15115:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15116:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15117:             while (my $configline=<$config>) {
15118:                 chomp($configline);
15119:                 next if ($configline =~ /^\#/);
15120:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15121:                     $managerstab{$configline} = 1;
15122:                 }
15123:             }
15124:             close($config);
15125:         }
15126:     }
15127: }
15128: 
15129: # ------------- set up temporary directory
15130: {
15131:     $tmpdir = LONCAPA::tempdir();
15132: 
15133: }
15134: 
15135: # ------------- set default texengine (domain default overrides this)
15136: {
15137:     $deftex = LONCAPA::texengine();
15138: }
15139: 
15140: # ------------- set default minimum length for passwords for internal auth users
15141: {
15142:     $passwdmin = LONCAPA::passwd_min();
15143: }
15144: 
15145: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
15146: 				'compress_threshold'=> 20_000,
15147:  			        });
15148: 
15149: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15150: $dumpcount=0;
15151: $locknum=0;
15152: 
15153: &logtouch();
15154: &logthis('<font color="yellow">INFO: Read configuration</font>');
15155: $readit=1;
15156:     {
15157: 	use integer;
15158: 	my $test=(2**32)+1;
15159: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15160: 	&logthis(" Detected 64bit platform ($_64bit)");
15161:     }
15162: }
15163: }
15164: 
15165: 1;
15166: __END__
15167: 
15168: =pod
15169: 
15170: =head1 NAME
15171: 
15172: Apache::lonnet - Subroutines to ask questions about things in the network.
15173: 
15174: =head1 SYNOPSIS
15175: 
15176: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15177: 
15178:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15179: 
15180: Common parameters:
15181: 
15182: =over 4
15183: 
15184: =item *
15185: 
15186: $uname : an internal username (if $cname expecting a course Id specifically)
15187: 
15188: =item *
15189: 
15190: $udom : a domain (if $cdom expecting a course's domain specifically)
15191: 
15192: =item *
15193: 
15194: $symb : a resource instance identifier
15195: 
15196: =item *
15197: 
15198: $namespace : the name of a .db file that contains the data needed or
15199: being set.
15200: 
15201: =back
15202: 
15203: =head1 OVERVIEW
15204: 
15205: lonnet provides subroutines which interact with the
15206: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15207: about classes, users, and resources.
15208: 
15209: For many of these objects you can also use this to store data about
15210: them or modify them in various ways.
15211: 
15212: =head2 Symbs
15213: 
15214: To identify a specific instance of a resource, LON-CAPA uses symbols
15215: or "symbs"X<symb>. These identifiers are built from the URL of the
15216: map, the resource number of the resource in the map, and the URL of
15217: the resource itself. The latter is somewhat redundant, but might help
15218: if maps change.
15219: 
15220: An example is
15221: 
15222:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15223: 
15224: The respective map entry is
15225: 
15226:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15227:   title="Problem 2">
15228:  </resource>
15229: 
15230: Symbs are used by the random number generator, as well as to store and
15231: restore data specific to a certain instance of for example a problem.
15232: 
15233: =head2 Storing And Retrieving Data
15234: 
15235: X<store()>X<cstore()>X<restore()>Three of the most important functions
15236: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15237: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15238: is is the non-critical message twin of cstore. These functions are for
15239: handlers to store a perl hash to a user's permanent data space in an
15240: easy manner, and to retrieve it again on another call. It is expected
15241: that a handler would use this once at the beginning to retrieve data,
15242: and then again once at the end to send only the new data back.
15243: 
15244: The data is stored in the user's data directory on the user's
15245: homeserver under the ID of the course.
15246: 
15247: The hash that is returned by restore will have all of the previous
15248: value for all of the elements of the hash.
15249: 
15250: Example:
15251: 
15252:  #creating a hash
15253:  my %hash;
15254:  $hash{'foo'}='bar';
15255: 
15256:  #storing it
15257:  &Apache::lonnet::cstore(\%hash);
15258: 
15259:  #changing a value
15260:  $hash{'foo'}='notbar';
15261: 
15262:  #adding a new value
15263:  $hash{'bar'}='foo';
15264:  &Apache::lonnet::cstore(\%hash);
15265: 
15266:  #retrieving the hash
15267:  my %history=&Apache::lonnet::restore();
15268: 
15269:  #print the hash
15270:  foreach my $key (sort(keys(%history))) {
15271:    print("\%history{$key} = $history{$key}");
15272:  }
15273: 
15274: Will print out:
15275: 
15276:  %history{1:foo} = bar
15277:  %history{1:keys} = foo:timestamp
15278:  %history{1:timestamp} = 990455579
15279:  %history{2:bar} = foo
15280:  %history{2:foo} = notbar
15281:  %history{2:keys} = foo:bar:timestamp
15282:  %history{2:timestamp} = 990455580
15283:  %history{bar} = foo
15284:  %history{foo} = notbar
15285:  %history{timestamp} = 990455580
15286:  %history{version} = 2
15287: 
15288: Note that the special hash entries C<keys>, C<version> and
15289: C<timestamp> were added to the hash. C<version> will be equal to the
15290: total number of versions of the data that have been stored. The
15291: C<timestamp> attribute will be the UNIX time the hash was
15292: stored. C<keys> is available in every historical section to list which
15293: keys were added or changed at a specific historical revision of a
15294: hash.
15295: 
15296: B<Warning>: do not store the hash that restore returns directly. This
15297: will cause a mess since it will restore the historical keys as if the
15298: were new keys. I.E. 1:foo will become 1:1:foo etc.
15299: 
15300: Calling convention:
15301: 
15302:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15303:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15304: 
15305: For more detailed information, see lonnet specific documentation.
15306: 
15307: =head1 RETURN MESSAGES
15308: 
15309: =over 4
15310: 
15311: =item * B<con_lost>: unable to contact remote host
15312: 
15313: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15314: when the connection is brought back up
15315: 
15316: =item * B<con_failed>: unable to contact remote host and unable to save message
15317: for later delivery
15318: 
15319: =item * B<error:>: an error a occurred, a description of the error follows the :
15320: 
15321: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15322: that was requested
15323: 
15324: =back
15325: 
15326: =head1 PUBLIC SUBROUTINES
15327: 
15328: =head2 Session Environment Functions
15329: 
15330: =over 4
15331: 
15332: =item * 
15333: X<appenv()>
15334: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15335: the user envirnoment file, and will be restored for each access this
15336: user makes during this session, also modifies the %env for the current
15337: process. Optional rolesarrayref - if defined contains a reference to an array
15338: of roles which are exempt from the restriction on modifying user.role entries 
15339: in the user's environment.db and in %env.    
15340: 
15341: =item *
15342: X<delenv()>
15343: B<delenv($delthis,$regexp)>: removes all items from the session
15344: environment file that begin with $delthis. If the 
15345: optional second arg - $regexp - is true, $delthis is treated as a 
15346: regular expression, otherwise \Q$delthis\E is used. 
15347: The values are also deleted from the current processes %env.
15348: 
15349: =item * get_env_multiple($name) 
15350: 
15351: gets $name from the %env hash, it seemlessly handles the cases where multiple
15352: values may be defined and end up as an array ref.
15353: 
15354: returns an array of values
15355: 
15356: =back
15357: 
15358: =head2 User Information
15359: 
15360: =over 4
15361: 
15362: =item *
15363: X<queryauthenticate()>
15364: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15365: authentication scheme
15366: 
15367: =item *
15368: X<authenticate()>
15369: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15370: authenticate user from domain's lib servers (first use the current
15371: one). C<$upass> should be the users password.
15372: $checkdefauth is optional (value is 1 if a check should be made to
15373:    authenticate user using default authentication method, and allow
15374:    account creation if username does not have account in the domain).
15375: $clientcancheckhost is optional (value is 1 if checking whether the
15376:    server can host will occur on the client side in lonauth.pm).   
15377: 
15378: =item *
15379: X<homeserver()>
15380: B<homeserver($uname,$udom)>: find the server which has
15381: the user's directory and files (there must be only one), this caches
15382: the answer, and also caches if there is a borken connection.
15383: 
15384: =item *
15385: X<idget()>
15386: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15387: a list of student/employee IDs or clicker IDs
15388: (student/employee IDs are a unique resource in a domain, there must be 
15389: only 1 ID per username, and only 1 username per ID in a specific domain).
15390: clickerIDs are not necessarily unique, as students might share clickers.
15391: (returns hash: id=>name,id=>name)
15392: 
15393: =item *
15394: X<idrget()>
15395: B<idrget($udom,@unames)>: find the IDs behind a list of
15396: usernames (returns hash: name=>id,name=>id)
15397: 
15398: =item *
15399: X<idput()>
15400: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15401: names and associated student/employee IDs or clicker IDs.
15402: 
15403: =item *
15404: X<iddel()>
15405: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15406: student/employee ID or clicker ID username look-ups from domain.
15407: The homeserver ($uhome) and namespace ($namespace) are optional.
15408: If no $uhome is provided, it will be determined usig &homeserver()
15409: for each user.  If no $namespace is provided, the default is ids.
15410: 
15411: =item *
15412: X<updateclickers()>
15413: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15414: clicker ID-to-username look-ups in clickers.db on library server.
15415: Permitted actions are add or del (i.e., add or delete). The 
15416: clickers.db contains clickerID as keys (escaped), and each corresponding
15417: value is an escaped comma-separated list of usernames (for whom the
15418: library server is the homeserver), who registered that particular ID.
15419: If $critical is true, the update will be sent via &critical, otherwise
15420: &reply() will be used.
15421: 
15422: =item *
15423: X<rolesinit()>
15424: B<rolesinit($udom,$username)>: get user privileges.
15425: returns user role, first access and timer interval hashes
15426: 
15427: =item *
15428: X<privileged()>
15429: B<privileged($username,$domain)>: returns a true if user has a
15430: privileged and active role (i.e. su or dc), false otherwise.
15431: 
15432: =item *
15433: X<getsection()>
15434: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15435: course $cname, return section name/number or '' for "not in course"
15436: and '-1' for "no section"
15437: 
15438: =item *
15439: X<userenvironment()>
15440: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15441: passed in @what from the requested user's environment, returns a hash
15442: 
15443: =item * 
15444: X<userlog_query()>
15445: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15446: activity.log file. %filters defines filters applied when parsing the
15447: log file. These can be start or end timestamps, or the type of action
15448: - log to look for Login or Logout events, check for Checkin or
15449: Checkout, role for role selection. The response is in the form
15450: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15451: escaped strings of the action recorded in the activity.log file.
15452: 
15453: =back
15454: 
15455: =head2 User Roles
15456: 
15457: =over 4
15458: 
15459: =item *
15460: 
15461: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15462: returns codes for allowed actions.
15463: 
15464: The first argument is required, all others are optional.
15465: 
15466: $priv is the privilege being checked.
15467: $uri contains additional information about what is being checked for access (e.g.,
15468: URL, course ID etc.). 
15469: $symb is the unique resource instance identifier in a course; if needed,
15470: but not provided, it will be retrieved via a call to &symbread(). 
15471: $role is the role for which a priv is being checked (only used if priv is evb). 
15472: $clientip is the user's IP address (only used when checking for access to portfolio 
15473: files).
15474: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15475: prevents recursive calls to &allowed.
15476: 
15477:  F: full access
15478:  U,I,K: authentication modes (cxx only)
15479:  '': forbidden
15480:  1: user needs to choose course
15481:  2: browse allowed
15482:  A: passphrase authentication needed
15483:  B: access temporarily blocked because of a blocking event in a course.
15484:  D: access blocked because access is required via session initiated via deep-link 
15485: 
15486: =item *
15487: 
15488: constructaccess($url,$setpriv) : check for access to construction space URL
15489: 
15490: See if the owner domain and name in the URL match those in the
15491: expected environment.  If so, return three element list
15492: ($ownername,$ownerdomain,$ownerhome).
15493: 
15494: Otherwise return the null string.
15495: 
15496: If second argument 'setpriv' is true, it assigns the privileges,
15497: and returns the same three element list, unless the owner has
15498: blocked "ad hoc" Domain Coordinator access to the Author Space,
15499: in which case the null string is returned.
15500: 
15501: =item *
15502: 
15503: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15504: define a custom role rolename set privileges in format of lonTabs/roles.tab
15505: for system, domain, and course level. $uname and $udom are optional (current
15506: user's username and domain will be used when either of $uname or $udom are absent.
15507: 
15508: =item *
15509: 
15510: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15511: (rolesplain.tab); plain text explanation of a user role term.
15512: $type is Course (default) or Community.
15513: If $forcedefault evaluates to true, text returned will be default 
15514: text for $type. Otherwise, if this is a course, the text returned 
15515: will be a custom name for the role (if defined in the course's 
15516: environment).  If no custom name is defined the default is returned.
15517:    
15518: =item *
15519: 
15520: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15521: All arguments are optional. Returns a hash of a roles, either for
15522: co-author/assistant author roles for a user's Construction Space
15523: (default), or if $context is 'userroles', roles for the user himself,
15524: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15525: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15526: For each key, value is set to colon-separated start and end times for
15527: the role.  If no username and domain are specified, will default to
15528: current user/domain. Types, roles, and roledoms are references to arrays
15529: of role statuses (active, future or previous), roles 
15530: (e.g., cc,in, st etc.) and domains of the roles which can be used
15531: to restrict the list of roles reported. If no array ref is 
15532: provided for types, will default to return only active roles.
15533: 
15534: =item *
15535: 
15536: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15537: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15538: 
15539: Additional optional arguments are: $type (if role checking is to be restricted 
15540: to certain user status types -- previous (expired roles), active (currently
15541: available roles) or future (roles available in the future), and
15542: $hideprivileged -- if true will not report course roles for users who
15543: have active Domain Coordinator role in course's domain or in additional
15544: domains (specified in 'Domains to check for privileged users' in course
15545: environment -- set via:  Course Settings -> Classlists and staff listing).
15546: 
15547: =item *
15548: 
15549: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15550: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15551: $possdomains and $possroles are optional array refs -- to domains to check and
15552: roles to check.  If $possdomains is not specified, a dump will be done of the
15553: users' roles.db to check for a dc or su role in any domain. This can be
15554: time consuming if &privileged is called repeatedly (e.g., when displaying a
15555: classlist), so in such cases, supplying a $possdomains array is preferred, as
15556: this then allows &privileged_by_domain() to be used, which caches the identity
15557: of privileged users, eliminating the need for repeated calls to &dump().
15558: 
15559: =item *
15560: 
15561: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15562: where the outer hash keys are domains specified in the $possdomains array ref,
15563: next inner hash keys are privileged roles specified in the $roles array ref,
15564: and the innermost hash contains key = value pairs for username:domain = end:start
15565: for active or future "privileged" users with that role in that domain. To avoid
15566: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15567: innerhash are cached using priv_$role and $dom as the identifiers.
15568: 
15569: =back
15570: 
15571: =head2 User Modification
15572: 
15573: =over 4
15574: 
15575: =item *
15576: 
15577: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15578: user for the level given by URL.  Optional start and end dates (leave empty
15579: string or zero for "no date")
15580: 
15581: =item *
15582: 
15583: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15584: change a users, password, possible return values are: ok,
15585: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15586: refused
15587: 
15588: =item *
15589: 
15590: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15591: 
15592: =item *
15593: 
15594: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15595:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15596: 
15597: will update user information (firstname,middlename,lastname,generation,
15598: permanentemail), and if forceid is true, student/employee ID also.
15599: A user's institutional affiliation(s) can also be updated.
15600: User information fields will not be overwritten with empty entries 
15601: unless the field is included in the $candelete array reference.
15602: This array is included when a single user is modified via "Manage Users",
15603: or when Autoupdate.pl is run by cron in a domain.
15604: 
15605: =item *
15606: 
15607: modifystudent
15608: 
15609: modify a student's enrollment and identification information.
15610: The course id is resolved based on the current user's environment.  
15611: This means the invoking user must be a course coordinator or otherwise
15612: associated with a course.
15613: 
15614: This call is essentially a wrapper for lonnet::modifyuser and
15615: lonnet::modify_student_enrollment
15616: 
15617: Inputs: 
15618: 
15619: =over 4
15620: 
15621: =item B<$udom> Student's loncapa domain
15622: 
15623: =item B<$uname> Student's loncapa login name
15624: 
15625: =item B<$uid> Student/Employee ID
15626: 
15627: =item B<$umode> Student's authentication mode
15628: 
15629: =item B<$upass> Student's password
15630: 
15631: =item B<$first> Student's first name
15632: 
15633: =item B<$middle> Student's middle name
15634: 
15635: =item B<$last> Student's last name
15636: 
15637: =item B<$gene> Student's generation
15638: 
15639: =item B<$usec> Student's section in course
15640: 
15641: =item B<$end> Unix time of the roles expiration
15642: 
15643: =item B<$start> Unix time of the roles start date
15644: 
15645: =item B<$forceid> If defined, allow $uid to be changed
15646: 
15647: =item B<$desiredhome> server to use as home server for student
15648: 
15649: =item B<$email> Student's permanent e-mail address
15650: 
15651: =item B<$type> Type of enrollment (auto or manual)
15652: 
15653: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15654: 
15655: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15656: 
15657: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15658: 
15659: =item B<$context> role change context (shown in User Management Logs display in a course)
15660: 
15661: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15662: 
15663: =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.
15664: 
15665: =back
15666: 
15667: =item *
15668: 
15669: modify_student_enrollment
15670: 
15671: Change a student's enrollment status in a class.  The environment variable
15672: 'role.request.course' must be defined for this function to proceed.
15673: 
15674: Inputs:
15675: 
15676: =over 4
15677: 
15678: =item $udom, student's domain
15679: 
15680: =item $uname, student's name
15681: 
15682: =item $uid, student's user id
15683: 
15684: =item $first, student's first name
15685: 
15686: =item $middle
15687: 
15688: =item $last
15689: 
15690: =item $gene
15691: 
15692: =item $usec
15693: 
15694: =item $end
15695: 
15696: =item $start
15697: 
15698: =item $type
15699: 
15700: =item $locktype
15701: 
15702: =item $cid
15703: 
15704: =item $selfenroll
15705: 
15706: =item $context
15707: 
15708: =item $credits, number of credits student will earn from this class
15709: 
15710: =item $instsec, institutional course section code for student
15711: 
15712: =back
15713: 
15714: 
15715: =item *
15716: 
15717: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15718: custom role; give a custom role to a user for the level given by URL.  Specify
15719: name and domain of role author, and role name
15720: 
15721: =item *
15722: 
15723: revokerole($udom,$uname,$url,$role) : revoke a role for url
15724: 
15725: =item *
15726: 
15727: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15728: 
15729: =back
15730: 
15731: =head2 Course Infomation
15732: 
15733: =over 4
15734: 
15735: =item *
15736: 
15737: coursedescription($courseid,$options) : returns a hash of information about the
15738: specified course id, including all environment settings for the
15739: course, the description of the course will be in the hash under the
15740: key 'description'
15741: 
15742: $options is an optional parameter that if supplied is a hash reference that controls
15743: what how this function works.  It has the following key/values:
15744: 
15745: =over 4
15746: 
15747: =item freshen_cache
15748: 
15749: If defined, and the environment cache for the course is valid, it is 
15750: returned in the returned hash.
15751: 
15752: =item one_time
15753: 
15754: If defined, the last cache time is set to _now_
15755: 
15756: =item user
15757: 
15758: If defined, the supplied username is used instead of the current user.
15759: 
15760: 
15761: =back
15762: 
15763: =item *
15764: 
15765: resdata($name,$domain,$type,@which) : request for current parameter
15766: setting for a specific $type, where $type is either 'course' or 'user',
15767: @what should be a list of parameters to ask about. This routine caches
15768: answers for 10 minutes.
15769: 
15770: =item *
15771: 
15772: get_courseresdata($courseid, $domain) : dump the entire course resource
15773: data base, returning a hash that is keyed by the resource name and has
15774: values that are the resource value.  I believe that the timestamps and
15775: versions are also returned.
15776: 
15777: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15778: supplemental content area. This routine caches the number of files for 
15779: 10 minutes.
15780: 
15781: =back
15782: 
15783: =head2 Course Modification
15784: 
15785: =over 4
15786: 
15787: =item *
15788: 
15789: writecoursepref($courseid,%prefs) : write preferences (environment
15790: database) for a course
15791: 
15792: =item *
15793: 
15794: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15795: 
15796: =item *
15797: 
15798: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15799: 
15800: =item *
15801: 
15802: is_course($courseid), is_course($cdom, $cnum)
15803: 
15804: Accepts either a combined $courseid (in the form of domain_courseid) or the
15805: two component version $cdom, $cnum. It checks if the specified course exists.
15806: 
15807: Returns:
15808:     undef if the course doesn't exist, otherwise
15809:     in scalar context the combined courseid.
15810:     in list context the two components of the course identifier, domain and 
15811:     courseid.    
15812: 
15813: =back
15814: 
15815: =head2 Bubblesheet Configuration
15816: 
15817: =over 4
15818: 
15819: =item *
15820: 
15821: get_scantron_config($which)
15822: 
15823: $which - the name of the configuration to parse from the file.
15824: 
15825: Parses and returns the bubblesheet configuration line selected as a
15826: hash of configuration file fields.
15827: 
15828: 
15829: Returns:
15830:     If the named configuration is not in the file, an empty
15831:     hash is returned.
15832: 
15833:     a hash with the fields
15834:       name         - internal name for the this configuration setup
15835:       description  - text to display to operator that describes this config
15836:       CODElocation - if 0 or the string 'none'
15837:                           - no CODE exists for this config
15838:                      if -1 || the string 'letter'
15839:                           - a CODE exists for this config and is
15840:                             a string of letters
15841:                      Unsupported value (but planned for future support)
15842:                           if a positive integer
15843:                                - The CODE exists as the first n items from
15844:                                  the question section of the form
15845:                           if the string 'number'
15846:                                - The CODE exists for this config and is
15847:                                  a string of numbers
15848:       CODEstart   - (only matter if a CODE exists) column in the line where
15849:                      the CODE starts
15850:       CODElength  - length of the CODE
15851:       IDstart     - column where the student/employee ID starts
15852:       IDlength    - length of the student/employee ID info
15853:       Qstart      - column where the information from the bubbled
15854:                     'questions' start
15855:       Qlength     - number of columns comprising a single bubble line from
15856:                     the sheet. (usually either 1 or 10)
15857:       Qon         - either a single character representing the character used
15858:                     to signal a bubble was chosen in the positional setup, or
15859:                     the string 'letter' if the letter of the chosen bubble is
15860:                     in the final, or 'number' if a number representing the
15861:                     chosen bubble is in the file (1->A 0->J)
15862:       Qoff        - the character used to represent that a bubble was
15863:                     left blank
15864:       PaperID     - if the scanning process generates a unique number for each
15865:                     sheet scanned the column that this ID number starts in
15866:       PaperIDlength - number of columns that comprise the unique ID number
15867:                       for the sheet of paper
15868:       FirstName   - column that the first name starts in
15869:       FirstNameLength - number of columns that the first name spans
15870:       LastName    - column that the last name starts in
15871:       LastNameLength - number of columns that the last name spans
15872:       BubblesPerRow - number of bubbles available in each row used to
15873:                       bubble an answer. (If not specified, 10 assumed).
15874: 
15875: 
15876: =item *
15877: 
15878: get_scantronformat_file($cdom)
15879: 
15880: $cdom - the course's domain (optional); if not supplied, uses
15881: domain for current $env{'request.course.id'}.
15882: 
15883: Returns an array containing lines from the scantron format file for
15884: the domain of the course.
15885: 
15886: If a url for a custom.tab file is listed in domain's configuration.db,
15887: lines are from this file.
15888: 
15889: Otherwise, if a default.tab has been published in RES space by the
15890: domainconfig user, lines are from this file.
15891: 
15892: Otherwise, fall back to getting lines from the legacy file on the
15893: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15894: 
15895: =back
15896: 
15897: =head2 Resource Subroutines
15898: 
15899: =over 4
15900: 
15901: =item *
15902: 
15903: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15904: 
15905: =item *
15906: 
15907: repcopy($filename) : subscribes to the requested file, and attempts to
15908: replicate from the owning library server, Might return
15909: 'unavailable', 'not_found', 'forbidden', 'ok', or
15910: 'bad_request', also attempts to grab the metadata for the
15911: resource. Expects the local filesystem pathname
15912: (/home/httpd/html/res/....)
15913: 
15914: =back
15915: 
15916: =head2 Resource Information
15917: 
15918: =over 4
15919: 
15920: =item *
15921: 
15922: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15923: and returns the value of a variety of different possible values,
15924: $varname should be a request string, and the other parameters can be
15925: used to specify who and what one is asking about. Ordinarily, $cid 
15926: does not need to be specified, as it is retrived from 
15927: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15928: within lonuserstate::loadmap() when initializing a course, before
15929: $env{'request.course.id'} has been set, so it needs to be provided
15930: in that one case.
15931: 
15932: Possible values for $varname are environment.lastname (or other item
15933: from the envirnment hash), user.name (or someother aspect about the
15934: user), resource.0.maxtries (or some other part and parameter of a
15935: resource)
15936: 
15937: =item *
15938: 
15939: directcondval($number) : get current value of a condition; reads from a state
15940: string
15941: 
15942: =item *
15943: 
15944: condval($condidx) : value of condition index based on state
15945: 
15946: =item *
15947: 
15948: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15949: resource's metadata, $what should be either a specific key, or either
15950: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15951: packages that this resource currently uses, the last 3 arguments are 
15952: only used internally for recursive metadata.
15953: 
15954: the toolsymb is only used where the uri is for an external tool (for which
15955: the uri as well as the symb are guaranteed to be unique).
15956: 
15957: this function automatically caches all requests except any made recursively
15958: to retrieve a list of metadata keys for an imported library file ($liburi is 
15959: defined).
15960: 
15961: =item *
15962: 
15963: metadata_query($query,$custom,$customshow) : make a metadata query against the
15964: network of library servers; returns file handle of where SQL and regex results
15965: will be stored for query
15966: 
15967: =item *
15968: 
15969: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15970: return symbolic list entry (all arguments optional). 
15971: 
15972: Args: filename is the filename (including path) for the file for which a symb 
15973: is required; donotrecurse, if true will prevent calls to allowed() being made 
15974: to check access status if more than one resource was found in the bighash 
15975: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15976: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15977: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15978: cause possible symbs to be checked to determine if they are subject to content
15979: blocking, if so they will not be included as possible symbs; possibles is a
15980: ref to a hash, which, as a side effect, will be populated with all possible 
15981: symbs (content blocking not tested).
15982:  
15983: returns the data handle
15984: 
15985: =item *
15986: 
15987: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15988: and is a possible symb for the URL in $thisfn, and if is an encrypted
15989: resource that the user accessed using /enc/ returns a 1 on success, 0
15990: on failure, user must be in a course, as it assumes the existence of
15991: the course initial hash, and uses $env('request.course.id'}.  The third
15992: arg is an optional reference to a scalar.  If this arg is passed in the 
15993: call to symbverify, it will be set to 1 if the symb has been set to be 
15994: encrypted; otherwise it will be null.  
15995: 
15996: =item *
15997: 
15998: symbclean($symb) : removes versions numbers from a symb, returns the
15999: cleaned symb
16000: 
16001: =item *
16002: 
16003: is_on_map($uri) : checks if the $uri is somewhere on the current
16004: course map, user must be in a course for it to work.
16005: 
16006: =item *
16007: 
16008: numval($salt) : return random seed value (addend for rndseed)
16009: 
16010: =item *
16011: 
16012: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16013: a random seed, all arguments are optional, if they aren't sent it uses the
16014: environment to derive them. Note: if symb isn't sent and it can't get one
16015: from &symbread it will use the current time as its return value
16016: 
16017: =item *
16018: 
16019: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16020: unfakeable, receipt
16021: 
16022: =item *
16023: 
16024: receipt() : API to ireceipt working off of env values; given out to users
16025: 
16026: =item *
16027: 
16028: countacc($url) : count the number of accesses to a given URL
16029: 
16030: =item *
16031: 
16032: 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
16033: 
16034: =item *
16035: 
16036: 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)
16037: 
16038: =item *
16039: 
16040: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16041: 
16042: =item *
16043: 
16044: devalidate($symb) : devalidate temporary spreadsheet calculations,
16045: forcing spreadsheet to reevaluate the resource scores next time.
16046: 
16047: =item * 
16048: 
16049: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16050: when viewing in course context.
16051: 
16052:  input: six args -- filename (decluttered), course number, course domain,
16053:                     url, symb (if registered) and group (if this is a 
16054:                     group item -- e.g., bulletin board, group page etc.).
16055: 
16056:  output: array of five scalars --
16057:          $cfile -- url for file editing if editable on current server
16058:          $home -- homeserver of resource (i.e., for author if published,
16059:                                           or course if uploaded.).
16060:          $switchserver --  1 if server switch will be needed.
16061:          $forceedit -- 1 if icon/link should be to go to edit mode 
16062:          $forceview -- 1 if icon/link should be to go to view mode
16063: 
16064: =item *
16065: 
16066: is_course_upload($file,$cnum,$cdom)
16067: 
16068: Used in course context to determine if current file was uploaded to 
16069: the course (i.e., would be found in /userfiles/docs on the course's 
16070: homeserver.
16071: 
16072:   input: 3 args -- filename (decluttered), course number and course domain.
16073:   output: boolean -- 1 if file was uploaded.
16074: 
16075: =back
16076: 
16077: =head2 Storing/Retreiving Data
16078: 
16079: =over 4
16080: 
16081: =item *
16082: 
16083: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16084: permanently for this url; hashref needs to be given and should be a \%hashname;
16085: the remaining args aren't required and if they aren't passed or are '' they will
16086: be derived from the env (with the exception of $laststore, which is an 
16087: optional arg used when a user's submission is stored in grading).
16088: $laststore is $version=$timestamp, where $version is the most recent version
16089: number retrieved for the corresponding $symb in the $namespace db file, and
16090: $timestamp is the timestamp for that transaction (UNIX time).
16091: $laststore is currently only passed when cstore() is called by 
16092: structuretags::finalize_storage().
16093: 
16094: =item *
16095: 
16096: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16097: but uses critical subroutine
16098: 
16099: =item *
16100: 
16101: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16102: all args are optional
16103: 
16104: =item *
16105: 
16106: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
16107: dumps the complete (or key matching regexp) namespace into a hash
16108: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16109: normally &store()ed into
16110: 
16111: $range should be either an integer '100' (give me the first 100
16112:                                            matching records)
16113:               or be  two integers sperated by a - with no spaces
16114:                  '30-50' (give me the 30th through the 50th matching
16115:                           records)
16116: 
16117: 
16118: =item *
16119: 
16120: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16121: replaces a &store() version of data with a replacement set of data
16122: for a particular resource in a namespace passed in the $storehash hash 
16123: reference. If $tolog is true, the transaction is logged in the courselog
16124: with an action=PUTSTORE.
16125: 
16126: =item *
16127: 
16128: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16129: works very similar to store/cstore, but all data is stored in a
16130: temporary location and can be reset using tmpreset, $storehash should
16131: be a hash reference, returns nothing on success
16132: 
16133: =item *
16134: 
16135: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16136: similar to restore, but all data is stored in a temporary location and
16137: can be reset using tmpreset. Returns a hash of values on success,
16138: error string otherwise.
16139: 
16140: =item *
16141: 
16142: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16143: deltes all keys for $symb form the temporary storage hash.
16144: 
16145: =item *
16146: 
16147: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16148: reference filled in from namesp ($udom and $uname are optional)
16149: 
16150: =item *
16151: 
16152: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16153: namesp ($udom and $uname are optional)
16154: 
16155: =item *
16156: 
16157: dump($namespace,$udom,$uname,$regexp,$range) : 
16158: dumps the complete (or key matching regexp) namespace into a hash
16159: ($udom, $uname, $regexp, $range are optional)
16160: 
16161: $range should be either an integer '100' (give me the first 100
16162:                                            matching records)
16163:               or be  two integers sperated by a - with no spaces
16164:                  '30-50' (give me the 30th through the 50th matching
16165:                           records)
16166: =item *
16167: 
16168: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16169: $store can be a scalar, an array reference, or if the amount to be 
16170: incremented is > 1, a hash reference.
16171: 
16172: ($udom and $uname are optional)
16173: 
16174: =item *
16175: 
16176: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16177: ($udom and $uname are optional)
16178: 
16179: =item *
16180: 
16181: cput($namespace,$storehash,$udom,$uname) : critical put
16182: ($udom and $uname are optional)
16183: 
16184: =item *
16185: 
16186: newput($namespace,$storehash,$udom,$uname) :
16187: 
16188: Attempts to store the items in the $storehash, but only if they don't
16189: currently exist, if this succeeds you can be certain that you have 
16190: successfully created a new key value pair in the $namespace db.
16191: 
16192: 
16193: Args:
16194:  $namespace: name of database to store values to
16195:  $storehash: hashref to store to the db
16196:  $udom: (optional) domain of user containing the db
16197:  $uname: (optional) name of user caontaining the db
16198: 
16199: Returns:
16200:  'ok' -> succeeded in storing all keys of $storehash
16201:  'key_exists: <key>' -> failed to anything out of $storehash, as at
16202:                         least <key> already existed in the db (other
16203:                         requested keys may also already exist)
16204:  'error: <msg>' -> unable to tie the DB or other error occurred
16205:  'con_lost' -> unable to contact request server
16206:  'refused' -> action was not allowed by remote machine
16207: 
16208: 
16209: =item *
16210: 
16211: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16212: reference filled in from namesp (encrypts the return communication)
16213: ($udom and $uname are optional)
16214: 
16215: =item *
16216: 
16217: log($udom,$name,$home,$message) : write to permanent log for user; use
16218: critical subroutine
16219: 
16220: =item *
16221: 
16222: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16223: array reference filled in from namespace found in domain level on either
16224: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16225: 
16226: =item *
16227: 
16228: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16229: domain level either on specified domain server ($uhome) or primary domain 
16230: server ($udom and $uhome are optional)
16231: 
16232: =item * 
16233: 
16234: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16235: for: authentication, language, quotas, timezone, date locale, and portal URL in
16236: the target domain.
16237: 
16238: May also include additional key => value pairs for the following groups:
16239: 
16240: =over
16241: 
16242: =item
16243: disk quotas (MB allocated by default to portfolios and authoring spaces).
16244: 
16245: =over
16246: 
16247: =item defaultquota, authorquota
16248: 
16249: =back
16250: 
16251: =item
16252: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16253: portfolio for users).
16254: 
16255: =over
16256: 
16257: =item
16258: aboutme, blog, webdav, portfolio
16259: 
16260: =back
16261: 
16262: =item
16263: requestcourses: ability to request courses, and how requests are processed.
16264: 
16265: =over
16266: 
16267: =item
16268: official, unofficial, community, textbook, placement
16269: 
16270: =back
16271: 
16272: =item
16273: inststatus: types of institutional affiliation, and order in which they are displayed.
16274: 
16275: =over
16276: 
16277: =item
16278: inststatustypes, inststatusorder, inststatusguest
16279: 
16280: =back
16281: 
16282: =item
16283: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16284: for course's uploaded content.
16285: 
16286: =over
16287: 
16288: =item
16289: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16290: communityquota, textbookquota, placementquota
16291: 
16292: =back
16293: 
16294: =item
16295: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16296: on your servers.
16297: 
16298: =over
16299: 
16300: =item 
16301: remotesessions, hostedsessions
16302: 
16303: =back
16304: 
16305: =back
16306: 
16307: In cases where a domain coordinator has never used the "Set Domain Configuration"
16308: utility to create a configuration.db file on a domain's primary library server 
16309: only the following domain defaults: auth_def, auth_arg_def, lang_def
16310: -- corresponding values are authentication type (internal, krb4, krb5,
16311: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16312: will be available. Values are retrieved from cache (if current), unless the
16313: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16314: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16315: 
16316: Typical usage:
16317: 
16318: %domdefaults = &get_domain_defaults($target_domain);
16319: 
16320: =back
16321: 
16322: =head2 Network Status Functions
16323: 
16324: =over 4
16325: 
16326: =item *
16327: 
16328: dirlist() : return directory list based on URI (first arg).
16329: 
16330: Inputs: 1 required, 5 optional.
16331: 
16332: =over
16333: 
16334: =item 
16335: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16336: 
16337: =item
16338: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16339: 
16340: =item
16341: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16342: 
16343: =item
16344: $getpropath - boolean: 1 if prepend path using &propath(). 
16345: 
16346: =item
16347: $getuserdir - boolean: 1 if prepend path for "userfiles".
16348: 
16349: =item 
16350: $alternateRoot - path to prepend in place of path from $uri.
16351: 
16352: =back
16353: 
16354: Returns: Array of up to two items.
16355: 
16356: =over
16357: 
16358: a reference to an array of files/subdirectories
16359: 
16360: =over
16361: 
16362: Each element in the array of files/subdirectories is a & separated list of
16363: item name and the result of running stat on the item.  If dirlist was requested
16364: for a file instead of a directory, the item name will be ''. For a directory 
16365: listing, if the item is a metadata file, the element will end &N&M 
16366: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16367: default copyright set (1).  
16368: 
16369: =back
16370: 
16371: a scalar containing error condition (if encountered).
16372: 
16373: =over
16374: 
16375: =item 
16376: no_host (no homeserver identified for $username:$domain).
16377: 
16378: =item 
16379: no_such_host (server contacted for listing not identified as valid host).
16380: 
16381: =item 
16382: con_lost (connection to remote server failed).
16383: 
16384: =item 
16385: refused (invalid $username:$domain received on lond side).
16386: 
16387: =item 
16388: no_such_dir (directory at specified path on lond side does not exist). 
16389: 
16390: =item 
16391: empty (directory at specified path on lond side is empty).
16392: 
16393: =over
16394: 
16395: This is currently not encountered because the &ls3, &ls2, 
16396: &ls (_handler) routines on the lond side do not filter out
16397: . and .. from a directory listing. 
16398: 
16399: =back
16400: 
16401: =back
16402: 
16403: =back
16404: 
16405: =item *
16406: 
16407: spareserver() : find server with least workload from spare.tab
16408: 
16409: 
16410: =item *
16411: 
16412: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16413: if there is no corresponding loncapa host.
16414: 
16415: =back
16416: 
16417: 
16418: =head2 Apache Request
16419: 
16420: =over 4
16421: 
16422: =item *
16423: 
16424: ssi($url,%hash) : server side include, does a complete request cycle on url to
16425: localhost, posts hash
16426: 
16427: =back
16428: 
16429: =head2 Data to String to Data
16430: 
16431: =over 4
16432: 
16433: =item *
16434: 
16435: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16436: and '&' separators, supports elements that are arrayrefs and hashrefs
16437: 
16438: =item *
16439: 
16440: hashref2str($hashref) : convert a hashref into a string complete with
16441: escaping and '=' and '&' separators, supports elements that are
16442: arrayrefs and hashrefs
16443: 
16444: =item *
16445: 
16446: arrayref2str($arrayref) : convert an arrayref into a string complete
16447: with escaping and '&' separators, supports elements that are arrayrefs
16448: and hashrefs
16449: 
16450: =item *
16451: 
16452: str2hash($string) : convert string to hash using unescaping and
16453: splitting on '=' and '&', supports elements that are arrayrefs and
16454: hashrefs
16455: 
16456: =item *
16457: 
16458: str2array($string) : convert string to hash using unescaping and
16459: splitting on '&', supports elements that are arrayrefs and hashrefs
16460: 
16461: =back
16462: 
16463: =head2 Logging Routines
16464: 
16465: 
16466: These routines allow one to make log messages in the lonnet.log and
16467: lonnet.perm logfiles.
16468: 
16469: =over 4
16470: 
16471: =item *
16472: 
16473: logtouch() : make sure the logfile, lonnet.log, exists
16474: 
16475: =item *
16476: 
16477: logthis() : append message to the normal lonnet.log file, it gets
16478: preiodically rolled over and deleted.
16479: 
16480: =item *
16481: 
16482: logperm() : append a permanent message to lonnet.perm.log, this log
16483: file never gets deleted by any automated portion of the system, only
16484: messages of critical importance should go in here.
16485: 
16486: 
16487: =back
16488: 
16489: =head2 General File Helper Routines
16490: 
16491: =over 4
16492: 
16493: =item *
16494: 
16495: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16496: (a) files in /uploaded
16497:   (i) If a local copy of the file exists - 
16498:       compares modification date of local copy with last-modified date for 
16499:       definitive version stored on home server for course. If local copy is 
16500:       stale, requests a new version from the home server and stores it. 
16501:       If the original has been removed from the home server, then local copy 
16502:       is unlinked.
16503:   (ii) If local copy does not exist -
16504:       requests the file from the home server and stores it. 
16505:   
16506:   If $caller is 'uploadrep':  
16507:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16508:     for request for files originally uploaded via DOCS. 
16509:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16510:   
16511:   Otherwise:
16512:      This indicates a call from the content generation phase of the request.
16513:      -  returns the entire contents of the file or -1.
16514:      
16515: (b) files in /res
16516:    - returns the entire contents of a file or -1; 
16517:    it properly subscribes to and replicates the file if neccessary.
16518: 
16519: 
16520: =item *
16521: 
16522: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16523:                   reference
16524: 
16525: returns either a stat() list of data about the file or an empty list
16526: if the file doesn't exist or couldn't find out about it (connection
16527: problems or user unknown)
16528: 
16529: =item *
16530: 
16531: filelocation($dir,$file) : returns file system location of a file
16532: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16533: directory that relative $file lookups are to looked in ($dir of /a/dir
16534: and a file of ../bob will become /a/bob)
16535: 
16536: =item *
16537: 
16538: hreflocation($dir,$file) : returns file system location or a URL; same as
16539: filelocation except for hrefs
16540: 
16541: =item *
16542: 
16543: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16544: also removes beginning /home/httpd/html unless /priv/ follows it.
16545: 
16546: =back
16547: 
16548: =head2 Usererfile file routines (/uploaded*)
16549: 
16550: =over 4
16551: 
16552: =item *
16553: 
16554: userfileupload(): main rotine for putting a file in a user or course's
16555:                   filespace, arguments are,
16556: 
16557:  formname - required - this is the name of the element in $env where the
16558:            filename, and the contents of the file to create/modifed exist
16559:            the filename is in $env{'form.'.$formname.'.filename'} and the
16560:            contents of the file is located in $env{'form.'.$formname}
16561:  context - if coursedoc, store the file in the course of the active role
16562:              of the current user; 
16563:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16564:            if 'canceloverwrite': delete file in tmp/overwrites directory
16565:  subdir - required - subdirectory to put the file in under ../userfiles/
16566:          if undefined, it will be placed in "unknown"
16567: 
16568:  (This routine calls clean_filename() to remove any dangerous
16569:  characters from the filename, and then calls finuserfileupload() to
16570:  complete the transaction)
16571: 
16572:  returns either the url of the uploaded file (/uploaded/....) if successful
16573:  and /adm/notfound.html if unsuccessful
16574: 
16575: =item *
16576: 
16577: clean_filename(): routine for cleaing a filename up for storage in
16578:                  userfile space, argument is:
16579: 
16580:  filename - proposed filename
16581: 
16582: returns: the new clean filename
16583: 
16584: =item *
16585: 
16586: finishuserfileupload(): routine that creates and sends the file to
16587: userspace, probably shouldn't be called directly
16588: 
16589:   docuname: username or courseid of destination for the file
16590:   docudom: domain of user/course of destination for the file
16591:   formname: same as for userfileupload()
16592:   fname: filename (including subdirectories) for the file
16593:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16594:           if hashref, and context is scantron, will convert csv format to standard format
16595:   allfiles: reference to hash used to store objects found by parser
16596:   codebase: reference to hash used for codebases of java objects found by parser
16597:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16598:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16599:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16600:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16601:   context: if 'overwrite', will move the uploaded file from its temporary location to
16602:             userfiles to facilitate overwriting a previously uploaded file with same name.
16603:   mimetype: reference to scalar to accommodate mime type determined
16604:             from File::MMagic if $parser = parse.
16605: 
16606:  returns either the url of the uploaded file (/uploaded/....) if successful
16607:  and /adm/notfound.html if unsuccessful (or an error message if context 
16608:  was 'overwrite').
16609:  
16610: 
16611: =item *
16612: 
16613: renameuserfile(): renames an existing userfile to a new name
16614: 
16615:   Args:
16616:    docuname: username or courseid of destination for the file
16617:    docudom: domain of user/course of destination for the file
16618:    old: current file name (including any subdirs under userfiles)
16619:    new: desired file name (including any subdirs under userfiles)
16620: 
16621: =item *
16622: 
16623: mkdiruserfile(): creates a directory is a userfiles dir
16624: 
16625:   Args:
16626:    docuname: username or courseid of destination for the file
16627:    docudom: domain of user/course of destination for the file
16628:    dir: dir to create (including any subdirs under userfiles)
16629: 
16630: =item *
16631: 
16632: removeuserfile(): removes a file that exists in userfiles
16633: 
16634:   Args:
16635:    docuname: username or courseid of destination for the file
16636:    docudom: domain of user/course of destination for the file
16637:    fname: filname to delete (including any subdirs under userfiles)
16638: 
16639: =item *
16640: 
16641: removeuploadedurl(): convience function for removeuserfile()
16642: 
16643:   Args:
16644:    url:  a full /uploaded/... url to delete
16645: 
16646: =item * 
16647: 
16648: get_portfile_permissions():
16649:   Args:
16650:     domain: domain of user or course contain the portfolio files
16651:     user: name of user or num of course contain the portfolio files
16652:   Returns:
16653:     hashref of a dump of the proper file_permissions.db
16654:    
16655: 
16656: =item * 
16657: 
16658: get_access_controls():
16659: 
16660: Args:
16661:   current_permissions: the hash ref returned from get_portfile_permissions()
16662:   group: (optional) the group you want the files associated with
16663:   file: (optional) the file you want access info on
16664: 
16665: Returns:
16666:     a hash (keys are file names) of hashes containing
16667:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16668:         values are XML containing access control settings (see below) 
16669: 
16670: Internal notes:
16671: 
16672:  access controls are stored in file_permissions.db as key=value pairs.
16673:     key -> path to file/file_name\0uniqueID:scope_end_start
16674:         where scope -> public,guest,course,group,domains or users.
16675:               end -> UNIX time for end of access (0 -> no end date)
16676:               start -> UNIX time for start of access
16677: 
16678:     value -> XML description of access control
16679:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16680:             <start></start>
16681:             <end></end>
16682: 
16683:             <password></password>  for scope type = guest
16684: 
16685:             <domain></domain>     for scope type = course or group
16686:             <number></number>
16687:             <roles id="">
16688:              <role></role>
16689:              <access></access>
16690:              <section></section>
16691:              <group></group>
16692:             </roles>
16693: 
16694:             <dom></dom>         for scope type = domains
16695: 
16696:             <users>             for scope type = users
16697:              <user>
16698:               <uname></uname>
16699:               <udom></udom>
16700:              </user>
16701:             </users>
16702:            </scope> 
16703:               
16704:  Access data is also aggregated for each file in an additional key=value pair:
16705:  key -> path to file/file_name\0accesscontrol 
16706:  value -> reference to hash
16707:           hash contains key = value pairs
16708:           where key = uniqueID:scope_end_start
16709:                 value = UNIX time record was last updated
16710: 
16711:           Used to improve speed of look-ups of access controls for each file.  
16712:  
16713:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16714: 
16715: =item *
16716: 
16717: modify_access_controls():
16718: 
16719: Modifies access controls for a portfolio file
16720: Args
16721: 1. file name
16722: 2. reference to hash of required changes,
16723: 3. domain
16724: 4. username
16725:   where domain,username are the domain of the portfolio owner 
16726:   (either a user or a course) 
16727: 
16728: Returns:
16729: 1. result of additions or updates ('ok' or 'error', with error message). 
16730: 2. result of deletions ('ok' or 'error', with error message).
16731: 3. reference to hash of any new or updated access controls.
16732: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16733:    key = integer (inbound ID)
16734:    value = uniqueID
16735: 
16736: =item *
16737: 
16738: get_timebased_id():
16739: 
16740: Attempts to get a unique timestamp-based suffix for use with items added to a 
16741: course via the Course Editor (e.g., folders, composite pages, 
16742: group bulletin boards).
16743: 
16744: Args: (first three required; six others optional)
16745: 
16746: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16747:    docssequence, or name of group
16748: 
16749: 2. keyid (alphanumeric): name of temporary locking key in hash,
16750:    e.g., num, boardids
16751: 
16752: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16753:    file will be named nohist_namespace.db
16754: 
16755: 4. cdom: domain of course; default is current course domain from %env
16756: 
16757: 5. cnum: course number; default is current course number from %env
16758: 
16759: 6. idtype: set to concat if an additional digit is to be appended to the 
16760:    unix timestamp to form the suffix, if the plain timestamp is already
16761:    in use.  Default is to not do this, but simply increment the unix 
16762:    timestamp by 1 until a unique key is obtained.
16763: 
16764: 7. who: holder of locking key; defaults to user:domain for user.
16765: 
16766: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16767:    retrying); default is 3.
16768: 
16769: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16770: 
16771: Returns:
16772: 
16773: 1. suffix obtained (numeric)
16774: 
16775: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16776: 
16777: 3. error: contains (localized) error message if an error occurred.
16778: 
16779: 
16780: =back
16781: 
16782: =head2 HTTP Helper Routines
16783: 
16784: =over 4
16785: 
16786: =item *
16787: 
16788: escape() : unpack non-word characters into CGI-compatible hex codes
16789: 
16790: =item *
16791: 
16792: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16793: 
16794: =back
16795: 
16796: =head1 PRIVATE SUBROUTINES
16797: 
16798: =head2 Underlying communication routines (Shouldn't call)
16799: 
16800: =over 4
16801: 
16802: =item *
16803: 
16804: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16805: 
16806: =item *
16807: 
16808: reply() : uses subreply to send a message to remote machine, logs all failures
16809: 
16810: =item *
16811: 
16812: critical() : passes a critical message to another server; if cannot
16813: get through then place message in connection buffer directory and
16814: returns con_delayed, if incapable of saving message, returns
16815: con_failed
16816: 
16817: =item *
16818: 
16819: reconlonc() : tries to reconnect lonc client processes.
16820: 
16821: =back
16822: 
16823: =head2 Resource Access Logging
16824: 
16825: =over 4
16826: 
16827: =item *
16828: 
16829: flushcourselogs() : flush (save) buffer logs and access logs
16830: 
16831: =item *
16832: 
16833: courselog($what) : save message for course in hash
16834: 
16835: =item *
16836: 
16837: courseacclog($what) : save message for course using &courselog().  Perform
16838: special processing for specific resource types (problems, exams, quizzes, etc).
16839: 
16840: =item *
16841: 
16842: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16843: as a PerlChildExitHandler
16844: 
16845: =back
16846: 
16847: =head2 Other
16848: 
16849: =over 4
16850: 
16851: =item *
16852: 
16853: symblist($mapname,%newhash) : update symbolic storage links
16854: 
16855: =back
16856: 
16857: =cut
16858: 

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