File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1420: download - view: text, annotated - select for diffs
Mon Mar 30 11:04:08 2020 UTC (4 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Last activity data for course users from server's in course's domain on
  "What's New" page.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1420 2020/03/30 11:04:08 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 delbalcookie {
 1154:     my ($cookie,$balancer) =@_;
 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("delbalcookie:$cookie",$balancer);
 1163:         }
 1164:     }
 1165: }
 1166: 
 1167: # -------------------------------- ask if server already has a session for user
 1168: sub has_user_session {
 1169:     my ($lonid,$udom,$uname) = @_;
 1170:     my $result = &reply(join(':','userhassession',
 1171: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1172:     return 1 if ($result eq 'ok');
 1173: 
 1174:     return 0;
 1175: }
 1176: 
 1177: # --------- determine least loaded server in a user's domain which allows login
 1178: 
 1179: sub choose_server {
 1180:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1181:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1182:     my %servers = &get_servers($udom);
 1183:     my $lowest_load = 30000;
 1184:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1185:     if ($skiploadbal) {
 1186:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1187:         unless (defined($cached)) {
 1188:             my $cachetime = 60*60*24;
 1189:             my %domconfig =
 1190:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1191:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1192:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1193:                                            $cachetime);
 1194:             }
 1195:         }
 1196:     }
 1197:     foreach my $lonhost (keys(%servers)) {
 1198:         if ($skiploadbal) {
 1199:             if (ref($balancers) eq 'HASH') {
 1200:                 next if (exists($balancers->{$lonhost}));
 1201:             }
 1202:         }
 1203:         my $loginvia;
 1204:         if ($checkloginvia) {
 1205:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1206:             if ($loginvia) {
 1207:                 my ($server,$path) = split(/:/,$loginvia);
 1208:                 ($login_host, $lowest_load) =
 1209:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1210:                 if ($login_host eq $server) {
 1211:                     $portal_path = $path;
 1212:                     $isredirect = 1;
 1213:                 }
 1214:             } else {
 1215:                 ($login_host, $lowest_load) =
 1216:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1217:                 if ($login_host eq $lonhost) {
 1218:                     $portal_path = '';
 1219:                     $isredirect = ''; 
 1220:                 }
 1221:             }
 1222:         } else {
 1223:             ($login_host, $lowest_load) =
 1224:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1225:         }
 1226:     }
 1227:     if ($login_host ne '') {
 1228:         $hostname = &hostname($login_host);
 1229:     }
 1230:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1231: }
 1232: 
 1233: sub get_course_sessions {
 1234:     my ($cnum,$cdom,$lastactivity) = @_;
 1235:     my %servers = &internet_dom_servers($cdom);
 1236:     my %returnhash;
 1237:     foreach my $server (sort(keys(%servers))) {
 1238:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1239:         my @pairs=split(/\&/,$rep);
 1240:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1241:             foreach my $item (@pairs) {
 1242:                 my ($key,$value)=split(/=/,$item,2);
 1243:                 $key = &unescape($key);
 1244:                 next if ($key =~ /^error: 2 /);
 1245:                 if (exists($returnhash{$key})) {
 1246:                     next if ($value < $returnhash{$key});
 1247:                 }
 1248:                 $returnhash{$key}=$value;
 1249:             }
 1250:         }
 1251:     }
 1252:     return %returnhash;
 1253: }
 1254: 
 1255: # --------------------------------------------- Try to change a user's password
 1256: 
 1257: sub changepass {
 1258:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1259:     $currentpass = &escape($currentpass);
 1260:     $newpass     = &escape($newpass);
 1261:     my $lonhost = $perlvar{'lonHostID'};
 1262:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1263: 		       $server);
 1264:     if (! $answer) {
 1265: 	&logthis("No reply on password change request to $server ".
 1266: 		 "by $uname in domain $udom.");
 1267:     } elsif ($answer =~ "^ok") {
 1268:         &logthis("$uname in $udom successfully changed their password ".
 1269: 		 "on $server.");
 1270:     } elsif ($answer =~ "^pwchange_failure") {
 1271: 	&logthis("$uname in $udom was unable to change their password ".
 1272: 		 "on $server.  The action was blocked by either lcpasswd ".
 1273: 		 "or pwchange");
 1274:     } elsif ($answer =~ "^non_authorized") {
 1275:         &logthis("$uname in $udom did not get their password correct when ".
 1276: 		 "attempting to change it on $server.");
 1277:     } elsif ($answer =~ "^auth_mode_error") {
 1278:         &logthis("$uname in $udom attempted to change their password despite ".
 1279: 		 "not being locally or internally authenticated on $server.");
 1280:     } elsif ($answer =~ "^unknown_user") {
 1281:         &logthis("$uname in $udom attempted to change their password ".
 1282: 		 "on $server but were unable to because $server is not ".
 1283: 		 "their home server.");
 1284:     } elsif ($answer =~ "^refused") {
 1285: 	&logthis("$server refused to change $uname in $udom password because ".
 1286: 		 "it was sent an unencrypted request to change the password.");
 1287:     } elsif ($answer =~ "invalid_client") {
 1288:         &logthis("$server refused to change $uname in $udom password because ".
 1289:                  "it was a reset by e-mail originating from an invalid server.");
 1290:     } elsif ($answer =~ "^prioruse") {
 1291:        &logthis("$server refused to change $uname in $udom password because ".
 1292:                 "the password had been used before");
 1293:     }
 1294:     return $answer;
 1295: }
 1296: 
 1297: # ----------------------- Try to determine user's current authentication scheme
 1298: 
 1299: sub queryauthenticate {
 1300:     my ($uname,$udom)=@_;
 1301:     my $uhome=&homeserver($uname,$udom);
 1302:     if (!$uhome) {
 1303: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1304: 	return 'no_host';
 1305:     }
 1306:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1307:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1308: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1309:     }
 1310:     return $answer;
 1311: }
 1312: 
 1313: # --------- Try to authenticate user from domain's lib servers (first this one)
 1314: 
 1315: sub authenticate {
 1316:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1317:     $upass=&escape($upass);
 1318:     $uname= &LONCAPA::clean_username($uname);
 1319:     my $uhome=&homeserver($uname,$udom,1);
 1320:     my $newhome;
 1321:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1322: # Maybe the machine was offline and only re-appeared again recently?
 1323:         &reconlonc();
 1324: # One more
 1325: 	$uhome=&homeserver($uname,$udom,1);
 1326:         if (($uhome eq 'no_host') && $checkdefauth) {
 1327:             if (defined(&domain($udom,'primary'))) {
 1328:                 $newhome=&domain($udom,'primary');
 1329:             }
 1330:             if ($newhome ne '') {
 1331:                 $uhome = $newhome;
 1332:             }
 1333:         }
 1334: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1335: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1336: 	    return 'no_host';
 1337:         }
 1338:     }
 1339:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1340:     if ($answer eq 'authorized') {
 1341:         if ($newhome) {
 1342:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1343:             return 'no_account_on_host'; 
 1344:         } else {
 1345:             &logthis("User $uname at $udom authorized by $uhome");
 1346:             return $uhome;
 1347:         }
 1348:     }
 1349:     if ($answer eq 'non_authorized') {
 1350: 	&logthis("User $uname at $udom rejected by $uhome");
 1351: 	return 'no_host'; 
 1352:     }
 1353:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1354:     return 'no_host';
 1355: }
 1356: 
 1357: sub can_host_session {
 1358:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1359:     my $canhost = 1;
 1360:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1361:     if (ref($remotesessions) eq 'HASH') {
 1362:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1363:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1364:                 $canhost = 0;
 1365:             } else {
 1366:                 $canhost = 1;
 1367:             }
 1368:         }
 1369:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1370:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1371:                 $canhost = 1;
 1372:             } else {
 1373:                 $canhost = 0;
 1374:             }
 1375:         }
 1376:         if ($canhost) {
 1377:             if ($remotesessions->{'version'} ne '') {
 1378:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1379:                 if ($reqmajor ne '' && $reqminor ne '') {
 1380:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1381:                         my $major = $1;
 1382:                         my $minor = $2;
 1383:                         if (($major < $reqmajor ) ||
 1384:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1385:                             $canhost = 0;
 1386:                         }
 1387:                     } else {
 1388:                         $canhost = 0;
 1389:                     }
 1390:                 }
 1391:             }
 1392:         }
 1393:     }
 1394:     if ($canhost) {
 1395:         if (ref($hostedsessions) eq 'HASH') {
 1396:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1397:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1398:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1399:                 if (($uint_dom ne '') && 
 1400:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1401:                     $canhost = 0;
 1402:                 } else {
 1403:                     $canhost = 1;
 1404:                 }
 1405:             }
 1406:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1407:                 if (($uint_dom ne '') && 
 1408:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1409:                     $canhost = 1;
 1410:                 } else {
 1411:                     $canhost = 0;
 1412:                 }
 1413:             }
 1414:         }
 1415:     }
 1416:     return $canhost;
 1417: }
 1418: 
 1419: sub spare_can_host {
 1420:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1421:     my $canhost=1;
 1422:     my $try_server_hostname = &hostname($try_server);
 1423:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1424:     my $serverhomedom = &host_domain($serverhomeID);
 1425:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1426:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1427:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1428:             $canhost = 0;
 1429:         }
 1430:     }
 1431:     if (($canhost) && ($uint_dom)) {
 1432:         my @intdoms;
 1433:         my $internet_names = &get_internet_names($try_server);
 1434:         if (ref($internet_names) eq 'ARRAY') {
 1435:             @intdoms = @{$internet_names};
 1436:         }
 1437:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1438:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1439:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1440:                                          $remotesessions,
 1441:                                          $defdomdefaults{'hostedsessions'});
 1442:         }
 1443:     }
 1444:     return $canhost;
 1445: }
 1446: 
 1447: sub this_host_spares {
 1448:     my ($dom) = @_;
 1449:     my ($dom_in_use,$lonhost_in_use,$result);
 1450:     my @hosts = &current_machine_ids();
 1451:     foreach my $lonhost (@hosts) {
 1452:         if (&host_domain($lonhost) eq $dom) {
 1453:             $dom_in_use = $dom;
 1454:             $lonhost_in_use = $lonhost;
 1455:             last;
 1456:         }
 1457:     }
 1458:     if ($dom_in_use ne '') {
 1459:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1460:     }
 1461:     if (ref($result) ne 'HASH') {
 1462:         $lonhost_in_use = $perlvar{'lonHostID'};
 1463:         $dom_in_use = &host_domain($lonhost_in_use);
 1464:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1465:         if (ref($result) ne 'HASH') {
 1466:             $result = \%spareid;
 1467:         }
 1468:     }
 1469:     return $result;
 1470: }
 1471: 
 1472: sub spares_for_offload  {
 1473:     my ($dom_in_use,$lonhost_in_use) = @_;
 1474:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1475:     if (defined($cached)) {
 1476:         return $result;
 1477:     } else {
 1478:         my $cachetime = 60*60*24;
 1479:         my %domconfig =
 1480:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1481:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1482:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1483:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1484:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1485:                 }
 1486:             }
 1487:         }
 1488:     }
 1489:     return;
 1490: }
 1491: 
 1492: sub get_lonbalancer_config {
 1493:     my ($servers) = @_;
 1494:     my ($currbalancer,$currtargets);
 1495:     if (ref($servers) eq 'HASH') {
 1496:         foreach my $server (keys(%{$servers})) {
 1497:             my %what = (
 1498:                          spareid => 1,
 1499:                          perlvar => 1,
 1500:                        );
 1501:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1502:             if ($result eq 'ok') {
 1503:                 if (ref($returnhash) eq 'HASH') {
 1504:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1505:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1506:                             $currbalancer = $server;
 1507:                             $currtargets = {};
 1508:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1509:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1510:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1511:                                 }
 1512:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1513:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1514:                                 }
 1515:                             }
 1516:                             last;
 1517:                         }
 1518:                     }
 1519:                 }
 1520:             }
 1521:         }
 1522:     }
 1523:     return ($currbalancer,$currtargets);
 1524: }
 1525: 
 1526: sub check_loadbalancing {
 1527:     my ($uname,$udom,$caller) = @_;
 1528:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1529:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1530:     my $lonhost = $perlvar{'lonHostID'};
 1531:     my @hosts = &current_machine_ids();
 1532:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1533:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1534:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1535:     my $serverhomedom = &host_domain($lonhost);
 1536:     my $domneedscache;
 1537:     my $cachetime = 60*60*24;
 1538: 
 1539:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1540:         $dom_in_use = $udom;
 1541:         $homeintdom = 1;
 1542:     } else {
 1543:         $dom_in_use = $serverhomedom;
 1544:     }
 1545:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1546:     unless (defined($cached)) {
 1547:         my %domconfig =
 1548:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1549:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1550:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1551:         } else {
 1552:             $domneedscache = $dom_in_use;
 1553:         }
 1554:     }
 1555:     if (ref($result) eq 'HASH') {
 1556:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1557:             &check_balancer_result($result,@hosts);
 1558:         if ($is_balancer) {
 1559:             if (ref($currrules) eq 'HASH') {
 1560:                 if ($homeintdom) {
 1561:                     if ($uname ne '') {
 1562:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1563:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1564:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1565:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1566:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1567:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1568:                             }
 1569:                         }
 1570:                         if ($rule_in_effect eq '') {
 1571:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1572:                             if ($userenv{'inststatus'} ne '') {
 1573:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1574:                                 my ($othertitle,$usertypes,$types) =
 1575:                                     &Apache::loncommon::sorted_inst_types($udom);
 1576:                                 if (ref($types) eq 'ARRAY') {
 1577:                                     foreach my $type (@{$types}) {
 1578:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1579:                                             if (exists($currrules->{$type})) {
 1580:                                                 $rule_in_effect = $currrules->{$type};
 1581:                                             }
 1582:                                         }
 1583:                                     }
 1584:                                 }
 1585:                             } else {
 1586:                                 if (exists($currrules->{'default'})) {
 1587:                                     $rule_in_effect = $currrules->{'default'};
 1588:                                 }
 1589:                             }
 1590:                         }
 1591:                     } else {
 1592:                         if (exists($currrules->{'default'})) {
 1593:                             $rule_in_effect = $currrules->{'default'};
 1594:                         }
 1595:                     }
 1596:                 } else {
 1597:                     if ($currrules->{'_LC_external'} ne '') {
 1598:                         $rule_in_effect = $currrules->{'_LC_external'};
 1599:                     }
 1600:                 }
 1601:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1602:                                                        $uname,$udom);
 1603:             }
 1604:         }
 1605:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1606:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1607:         unless (defined($cached)) {
 1608:             my %domconfig =
 1609:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1610:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1611:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1612:             } else {
 1613:                 $domneedscache = $serverhomedom;
 1614:             }
 1615:         }
 1616:         if (ref($result) eq 'HASH') {
 1617:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1618:                 &check_balancer_result($result,@hosts);
 1619:             if ($is_balancer) {
 1620:                 if (ref($currrules) eq 'HASH') {
 1621:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1622:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1623:                     }
 1624:                 }
 1625:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1626:                                                        $uname,$udom);
 1627:             }
 1628:         } else {
 1629:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1630:                 $is_balancer = 1;
 1631:                 $offloadto = &this_host_spares($dom_in_use);
 1632:             }
 1633:             unless (defined($cached)) {
 1634:                 $domneedscache = $serverhomedom;
 1635:             }
 1636:         }
 1637:     } else {
 1638:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1639:             $is_balancer = 1;
 1640:             $offloadto = &this_host_spares($dom_in_use);
 1641:         }
 1642:         unless (defined($cached)) {
 1643:             $domneedscache = $serverhomedom;
 1644:         }
 1645:     }
 1646:     if ($domneedscache) {
 1647:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1648:     }
 1649:     if ($is_balancer) {
 1650:         my $lowest_load = 30000;
 1651:         if (ref($offloadto) eq 'HASH') {
 1652:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1653:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1654:                     ($otherserver,$lowest_load) =
 1655:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1656:                 }
 1657:             }
 1658:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1659: 
 1660:             if (!$found_server) {
 1661:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1662:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1663:                         ($otherserver,$lowest_load) =
 1664:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1665:                     }
 1666:                 }
 1667:             }
 1668:         } elsif (ref($offloadto) eq 'ARRAY') {
 1669:             if (@{$offloadto} == 1) {
 1670:                 $otherserver = $offloadto->[0];
 1671:             } elsif (@{$offloadto} > 1) {
 1672:                 foreach my $try_server (@{$offloadto}) {
 1673:                     ($otherserver,$lowest_load) =
 1674:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1675:                 }
 1676:             }
 1677:         }
 1678:         unless ($caller eq 'login') {
 1679:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1680:                 $is_balancer = 0;
 1681:                 if ($uname ne '' && $udom ne '') {
 1682:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1683:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1684:                                  'user.loadbalcheck.time' => time});
 1685:                     }
 1686:                 }
 1687:             }
 1688:         }
 1689:         unless ($homeintdom) {
 1690:             undef($setcookie);
 1691:         }
 1692:     }
 1693:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1694: }
 1695: 
 1696: sub check_balancer_result {
 1697:     my ($result,@hosts) = @_;
 1698:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1699:     if (ref($result) eq 'HASH') {
 1700:         if ($result->{'lonhost'} ne '') {
 1701:             my $currbalancer = $result->{'lonhost'};
 1702:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1703:                 $is_balancer = 1;
 1704:                 $currtargets = $result->{'targets'};
 1705:                 $currrules = $result->{'rules'};
 1706:             }
 1707:             $dom_balancers = $currbalancer;
 1708:         } else {
 1709:             if (keys(%{$result})) {
 1710:                 foreach my $key (keys(%{$result})) {
 1711:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1712:                         (ref($result->{$key}) eq 'HASH')) {
 1713:                         $is_balancer = 1;
 1714:                         $currrules = $result->{$key}{'rules'};
 1715:                         $currtargets = $result->{$key}{'targets'};
 1716:                         $setcookie = $result->{$key}{'cookie'};
 1717:                         last;
 1718:                     }
 1719:                 }
 1720:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1721:             }
 1722:         }
 1723:     }
 1724:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1725: }
 1726: 
 1727: sub get_loadbalancer_targets {
 1728:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1729:     my $offloadto;
 1730:     if ($rule_in_effect eq 'none') {
 1731:         return [$perlvar{'lonHostID'}];
 1732:     } elsif ($rule_in_effect eq '') {
 1733:         $offloadto = $currtargets;
 1734:     } else {
 1735:         if ($rule_in_effect eq 'homeserver') {
 1736:             my $homeserver = &homeserver($uname,$udom);
 1737:             if ($homeserver ne 'no_host') {
 1738:                 $offloadto = [$homeserver];
 1739:             }
 1740:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1741:             my %domconfig =
 1742:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1743:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1744:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1745:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1746:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1747:                     }
 1748:                 }
 1749:             } else {
 1750:                 my %servers = &internet_dom_servers($udom);
 1751:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1752:                 if (&hostname($remotebalancer) ne '') {
 1753:                     $offloadto = [$remotebalancer];
 1754:                 }
 1755:             }
 1756:         } elsif (&hostname($rule_in_effect) ne '') {
 1757:             $offloadto = [$rule_in_effect];
 1758:         }
 1759:     }
 1760:     return $offloadto;
 1761: }
 1762: 
 1763: sub internet_dom_servers {
 1764:     my ($dom) = @_;
 1765:     my (%uniqservers,%servers);
 1766:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1767:     my @machinedoms = &machine_domains($primaryserver);
 1768:     foreach my $mdom (@machinedoms) {
 1769:         my %currservers = %servers;
 1770:         my %server = &get_servers($mdom);
 1771:         %servers = (%currservers,%server);
 1772:     }
 1773:     my %by_hostname;
 1774:     foreach my $id (keys(%servers)) {
 1775:         push(@{$by_hostname{$servers{$id}}},$id);
 1776:     }
 1777:     foreach my $hostname (sort(keys(%by_hostname))) {
 1778:         if (@{$by_hostname{$hostname}} > 1) {
 1779:             my $match = 0;
 1780:             foreach my $id (@{$by_hostname{$hostname}}) {
 1781:                 if (&host_domain($id) eq $dom) {
 1782:                     $uniqservers{$id} = $hostname;
 1783:                     $match = 1;
 1784:                 }
 1785:             }
 1786:             unless ($match) {
 1787:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1788:             }
 1789:         } else {
 1790:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1791:         }
 1792:     }
 1793:     return %uniqservers;
 1794: }
 1795: 
 1796: sub trusted_domains {
 1797:     my ($cmdtype,$calldom) = @_;
 1798:     my ($trusted,$untrusted);
 1799:     if (&domain($calldom) eq '') {
 1800:         return ($trusted,$untrusted);
 1801:     }
 1802:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1803:         return ($trusted,$untrusted);
 1804:     }
 1805:     my $callprimary = &domain($calldom,'primary');
 1806:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1807:     if ($intcalldom eq '') {
 1808:         return ($trusted,$untrusted);
 1809:     }
 1810: 
 1811:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1812:     unless (defined($cached)) {
 1813:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1814:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1815:         $trustconfig = $domconfig{'trust'};
 1816:     }
 1817:     if (ref($trustconfig)) {
 1818:         my (%possexc,%possinc,@allexc,@allinc); 
 1819:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1820:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1821:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1822:             }
 1823:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1824:                 $possinc{$intcalldom} = 1;
 1825:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1826:             }
 1827:         }
 1828:         if (keys(%possexc)) {
 1829:             if (keys(%possinc)) {
 1830:                 foreach my $key (sort(keys(%possexc))) {
 1831:                     next if ($key eq $intcalldom);
 1832:                     unless ($possinc{$key}) {
 1833:                         push(@allexc,$key);
 1834:                     }
 1835:                 }
 1836:             } else {
 1837:                 @allexc = sort(keys(%possexc));
 1838:             }
 1839:         }
 1840:         if (keys(%possinc)) {
 1841:             $possinc{$intcalldom} = 1;
 1842:             @allinc = sort(keys(%possinc));
 1843:         }
 1844:         if ((@allexc > 0) || (@allinc > 0)) {
 1845:             my %doms_by_intdom;
 1846:             my %allintdoms = &all_host_intdom();
 1847:             my %alldoms = &all_host_domain();
 1848:             foreach my $key (%allintdoms) {
 1849:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1850:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1851:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1852:                     }
 1853:                 } else {
 1854:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1855:                 }
 1856:             }
 1857:             foreach my $exc (@allexc) {
 1858:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1859:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1860:                 }
 1861:             }
 1862:             foreach my $inc (@allinc) {
 1863:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1864:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1865:                 }
 1866:             }
 1867:         }
 1868:     }
 1869:     return ($trusted,$untrusted);
 1870: }
 1871: 
 1872: sub will_trust {
 1873:     my ($cmdtype,$domain,$possdom) = @_;
 1874:     return 1 if ($domain eq $possdom);
 1875:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1876:     my $willtrust; 
 1877:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1878:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1879:             $willtrust = 1;
 1880:         }
 1881:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1882:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1883:             $willtrust = 1;
 1884:         }
 1885:     } else {
 1886:         $willtrust = 1;
 1887:     }
 1888:     return $willtrust;
 1889: }
 1890: 
 1891: # ---------------------- Find the homebase for a user from domain's lib servers
 1892: 
 1893: my %homecache;
 1894: sub homeserver {
 1895:     my ($uname,$udom,$ignoreBadCache)=@_;
 1896:     my $index="$uname:$udom";
 1897: 
 1898:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1899: 
 1900:     my %servers = &get_servers($udom,'library');
 1901:     foreach my $tryserver (keys(%servers)) {
 1902:         next if ($ignoreBadCache ne 'true' && 
 1903: 		 exists($badServerCache{$tryserver}));
 1904: 
 1905: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1906: 	if ($answer eq 'found') {
 1907: 	    delete($badServerCache{$tryserver}); 
 1908: 	    return $homecache{$index}=$tryserver;
 1909: 	} elsif ($answer eq 'no_host') {
 1910: 	    $badServerCache{$tryserver}=1;
 1911: 	}
 1912:     }    
 1913:     return 'no_host';
 1914: }
 1915: 
 1916: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1917: 
 1918: sub idget {
 1919:     my ($udom,$idsref,$namespace)=@_;
 1920:     my %returnhash=();
 1921:     my @ids=(); 
 1922:     if (ref($idsref) eq 'ARRAY') {
 1923:         @ids = @{$idsref};
 1924:     } else {
 1925:         return %returnhash; 
 1926:     }
 1927:     if ($namespace eq '') {
 1928:         $namespace = 'ids';
 1929:     }
 1930:     
 1931:     my %servers = &get_servers($udom,'library');
 1932:     foreach my $tryserver (keys(%servers)) {
 1933: 	my $idlist=join('&', map { &escape($_); } @ids);
 1934: 	if ($namespace eq 'ids') {
 1935: 	    $idlist=~tr/A-Z/a-z/;
 1936: 	}
 1937: 	my $reply;
 1938: 	if ($namespace eq 'ids') {
 1939: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1940: 	} else {
 1941: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1942: 	}
 1943: 	my @answer=();
 1944: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1945: 	    @answer=split(/\&/,$reply);
 1946: 	}                    ;
 1947: 	my $i;
 1948: 	for ($i=0;$i<=$#ids;$i++) {
 1949: 	    if ($answer[$i]) {
 1950: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1951: 	    }
 1952: 	}
 1953:     }
 1954:     return %returnhash;
 1955: }
 1956: 
 1957: # ------------------------------------- Find the IDs behind a list of usernames
 1958: 
 1959: sub idrget {
 1960:     my ($udom,@unames)=@_;
 1961:     my %returnhash=();
 1962:     foreach my $uname (@unames) {
 1963:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1964:     }
 1965:     return %returnhash;
 1966: }
 1967: 
 1968: # Store away a list of names and associated student/employee IDs or clicker IDs
 1969: 
 1970: sub idput {
 1971:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1972:     my %servers=();
 1973:     my %ids=();
 1974:     my %byid = ();
 1975:     if (ref($idsref) eq 'HASH') {
 1976:         %ids=%{$idsref};
 1977:     }
 1978:     if ($namespace eq '') {
 1979:         $namespace = 'ids'; 
 1980:     }
 1981:     foreach my $uname (keys(%ids)) {
 1982: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1983:         if ($uhom eq '') {
 1984:             $uhom=&homeserver($uname,$udom);
 1985:         }
 1986:         if ($uhom ne 'no_host') {
 1987:             my $esc_unam=&escape($uname);
 1988:             if ($namespace eq 'ids') {
 1989:                 my $id=&escape($ids{$uname});
 1990:                 $id=~tr/A-Z/a-z/;
 1991:                 my $esc_unam=&escape($uname);
 1992:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1993:             } else {
 1994:                 my @currids = split(/,/,$ids{$uname});
 1995:                 foreach my $id (@currids) {
 1996:                     $byid{$uhom}{$id} .= $uname.',';
 1997:                 }
 1998:             }
 1999:         }
 2000:     }
 2001:     if ($namespace eq 'clickers') {
 2002:         foreach my $server (keys(%byid)) {
 2003:             if (ref($byid{$server}) eq 'HASH') {
 2004:                 foreach my $id (keys(%{$byid{$server}})) {
 2005:                     $byid{$server} =~ s/,$//;
 2006:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2007:                 }
 2008:             }
 2009:         }
 2010:     }
 2011:     foreach my $server (keys(%servers)) {
 2012:         $servers{$server} =~ s/\&$//;
 2013:         if ($namespace eq 'ids') {     
 2014:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2015:         } else {
 2016:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2017:         }
 2018:     }
 2019: }
 2020: 
 2021: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2022: 
 2023: sub iddel {
 2024:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2025:     my %result=();
 2026:     my %ids=();
 2027:     my %byid = ();
 2028:     if (ref($idshashref) eq 'HASH') {
 2029:         %ids=%{$idshashref};
 2030:     } else {
 2031:         return %result;
 2032:     }
 2033:     if ($namespace eq '') {
 2034:         $namespace = 'ids';
 2035:     }
 2036:     my %servers=();
 2037:     while (my ($id,$unamestr) = each(%ids)) {
 2038:         if ($namespace eq 'ids') {
 2039:             my $uhom = $uhome;
 2040:             if ($uhom eq '') { 
 2041:                 $uhom=&homeserver($unamestr,$udom);
 2042:             }
 2043:             if ($uhom ne 'no_host') {
 2044:                 $servers{$uhom}.='&'.&escape($id);
 2045:             }
 2046:          } else {
 2047:             my @curritems = split(/,/,$ids{$id});
 2048:             foreach my $uname (@curritems) {
 2049:                 my $uhom = $uhome;
 2050:                 if ($uhom eq '') {
 2051:                     $uhom=&homeserver($uname,$udom);
 2052:                 }
 2053:                 if ($uhom ne 'no_host') { 
 2054:                     $byid{$uhom}{$id} .= $uname.',';
 2055:                 }
 2056:             }
 2057:         }
 2058:     }
 2059:     if ($namespace eq 'clickers') {
 2060:         foreach my $server (keys(%byid)) {
 2061:             if (ref($byid{$server}) eq 'HASH') {
 2062:                 foreach my $id (keys(%{$byid{$server}})) {
 2063:                     $byid{$server}{$id} =~ s/,$//;
 2064:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2065:                 }
 2066:             }
 2067:         }
 2068:     }
 2069:     foreach my $server (keys(%servers)) {
 2070:         $servers{$server} =~ s/\&$//;
 2071:         if ($namespace eq 'ids') {
 2072:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2073:         } elsif ($namespace eq 'clickers') {
 2074:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2075:         }
 2076:     }
 2077:     return %result;
 2078: }
 2079: 
 2080: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2081: 
 2082: sub updateclickers {
 2083:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2084:     my %clickers;
 2085:     if (ref($idshashref) eq 'HASH') {
 2086:         %clickers=%{$idshashref};
 2087:     } else {
 2088:         return;
 2089:     }
 2090:     my $items='';
 2091:     foreach my $item (keys(%clickers)) {
 2092:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2093:     }
 2094:     $items=~s/\&$//;
 2095:     my $request = "updateclickers:$udom:$action:$items";
 2096:     if ($critical) {
 2097:         return &critical($request,$uhome);
 2098:     } else {
 2099:         return &reply($request,$uhome);
 2100:     }
 2101: }
 2102: 
 2103: # ------------------------------dump from db file owned by domainconfig user
 2104: sub dump_dom {
 2105:     my ($namespace, $udom, $regexp) = @_;
 2106: 
 2107:     $udom ||= $env{'user.domain'};
 2108: 
 2109:     return () unless $udom;
 2110: 
 2111:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2112: }
 2113: 
 2114: # ------------------------------------------ get items from domain db files   
 2115: 
 2116: sub get_dom {
 2117:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2118:     return if ($udom eq 'public');
 2119:     my $items='';
 2120:     foreach my $item (@$storearr) {
 2121:         $items.=&escape($item).'&';
 2122:     }
 2123:     $items=~s/\&$//;
 2124:     if (!$udom) {
 2125:         $udom=$env{'user.domain'};
 2126:         return if ($udom eq 'public');
 2127:         if (defined(&domain($udom,'primary'))) {
 2128:             $uhome=&domain($udom,'primary');
 2129:         } else {
 2130:             undef($uhome);
 2131:         }
 2132:     } else {
 2133:         if (!$uhome) {
 2134:             if (defined(&domain($udom,'primary'))) {
 2135:                 $uhome=&domain($udom,'primary');
 2136:             }
 2137:         }
 2138:     }
 2139:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2140:         my $rep;
 2141:         if ($namespace =~ /^enc/) {
 2142:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2143:         } else {
 2144:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2145:         }
 2146:         my %returnhash;
 2147:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2148:             return %returnhash;
 2149:         }
 2150:         my @pairs=split(/\&/,$rep);
 2151:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2152:             return @pairs;
 2153:         }
 2154:         my $i=0;
 2155:         foreach my $item (@$storearr) {
 2156:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2157:             $i++;
 2158:         }
 2159:         return %returnhash;
 2160:     } else {
 2161:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2162:     }
 2163: }
 2164: 
 2165: # -------------------------------------------- put items in domain db files 
 2166: 
 2167: sub put_dom {
 2168:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2169:     if (!$udom) {
 2170:         $udom=$env{'user.domain'};
 2171:         if (defined(&domain($udom,'primary'))) {
 2172:             $uhome=&domain($udom,'primary');
 2173:         } else {
 2174:             undef($uhome);
 2175:         }
 2176:     } else {
 2177:         if (!$uhome) {
 2178:             if (defined(&domain($udom,'primary'))) {
 2179:                 $uhome=&domain($udom,'primary');
 2180:             }
 2181:         }
 2182:     } 
 2183:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2184:         my $items='';
 2185:         foreach my $item (keys(%$storehash)) {
 2186:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2187:         }
 2188:         $items=~s/\&$//;
 2189:         if ($namespace =~ /^enc/) {
 2190:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2191:         } else {
 2192:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2193:         }
 2194:     } else {
 2195:         &logthis("put_dom failed - no homeserver and/or domain");
 2196:     }
 2197: }
 2198: 
 2199: # --------------------- newput for items in db file owned by domainconfig user
 2200: sub newput_dom {
 2201:     my ($namespace,$storehash,$udom) = @_;
 2202:     my $result;
 2203:     if (!$udom) {
 2204:         $udom=$env{'user.domain'};
 2205:     }
 2206:     if ($udom) {
 2207:         my $uname = &get_domainconfiguser($udom);
 2208:         $result = &newput($namespace,$storehash,$udom,$uname);
 2209:     }
 2210:     return $result;
 2211: }
 2212: 
 2213: # --------------------- delete for items in db file owned by domainconfig user
 2214: sub del_dom {
 2215:     my ($namespace,$storearr,$udom)=@_;
 2216:     if (ref($storearr) eq 'ARRAY') {
 2217:         if (!$udom) {
 2218:             $udom=$env{'user.domain'};
 2219:         }
 2220:         if ($udom) {
 2221:             my $uname = &get_domainconfiguser($udom); 
 2222:             return &del($namespace,$storearr,$udom,$uname);
 2223:         }
 2224:     }
 2225: }
 2226: 
 2227: # ----------------------------------construct domainconfig user for a domain 
 2228: sub get_domainconfiguser {
 2229:     my ($udom) = @_;
 2230:     return $udom.'-domainconfig';
 2231: }
 2232: 
 2233: sub retrieve_inst_usertypes {
 2234:     my ($udom) = @_;
 2235:     my (%returnhash,@order);
 2236:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2237:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2238:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2239:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2240:     } else {
 2241:         if (defined(&domain($udom,'primary'))) {
 2242:             my $uhome=&domain($udom,'primary');
 2243:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2244:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2245:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2246:                 return (\%returnhash,\@order);
 2247:             }
 2248:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2249:             my @pairs=split(/\&/,$hashitems);
 2250:             foreach my $item (@pairs) {
 2251:                 my ($key,$value)=split(/=/,$item,2);
 2252:                 $key = &unescape($key);
 2253:                 next if ($key =~ /^error: 2 /);
 2254:                 $returnhash{$key}=&thaw_unescape($value);
 2255:             }
 2256:             my @esc_order = split(/\&/,$orderitems);
 2257:             foreach my $item (@esc_order) {
 2258:                 push(@order,&unescape($item));
 2259:             }
 2260:         } else {
 2261:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2262:         }
 2263:         return (\%returnhash,\@order);
 2264:     }
 2265: }
 2266: 
 2267: sub is_domainimage {
 2268:     my ($url) = @_;
 2269:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2270:         if (&domain($1) ne '') {
 2271:             return '1';
 2272:         }
 2273:     }
 2274:     return;
 2275: }
 2276: 
 2277: sub inst_directory_query {
 2278:     my ($srch) = @_;
 2279:     my $udom = $srch->{'srchdomain'};
 2280:     my %results;
 2281:     my $homeserver = &domain($udom,'primary');
 2282:     my $outcome;
 2283:     if ($homeserver ne '') {
 2284:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2285:             if ($srch->{'srchby'} eq 'email') {
 2286:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2287:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2288:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2289:                     (($major == 2) && ($minor < 12))) {
 2290:                     return;
 2291:                 }
 2292:             }
 2293:         }
 2294: 	my $queryid=&reply("querysend:instdirsearch:".
 2295: 			   &escape($srch->{'srchby'}).':'.
 2296: 			   &escape($srch->{'srchterm'}).':'.
 2297: 			   &escape($srch->{'srchtype'}),$homeserver);
 2298: 	my $host=&hostname($homeserver);
 2299: 	if ($queryid !~/^\Q$host\E\_/) {
 2300: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2301: 	    return;
 2302: 	}
 2303: 	my $response = &get_query_reply($queryid);
 2304: 	my $maxtries = 5;
 2305: 	my $tries = 1;
 2306: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2307: 	    $response = &get_query_reply($queryid);
 2308: 	    $tries ++;
 2309: 	}
 2310: 
 2311:         if (!&error($response) && $response ne 'refused') {
 2312:             if ($response eq 'unavailable') {
 2313:                 $outcome = $response;
 2314:             } else {
 2315:                 $outcome = 'ok';
 2316:                 my @matches = split(/\n/,$response);
 2317:                 foreach my $match (@matches) {
 2318:                     my ($key,$value) = split(/=/,$match);
 2319:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2320:                 }
 2321:             }
 2322:         }
 2323:     }
 2324:     return ($outcome,%results);
 2325: }
 2326: 
 2327: sub usersearch {
 2328:     my ($srch) = @_;
 2329:     my $dom = $srch->{'srchdomain'};
 2330:     my %results;
 2331:     my %libserv = &all_library();
 2332:     my $query = 'usersearch';
 2333:     foreach my $tryserver (keys(%libserv)) {
 2334:         if (&host_domain($tryserver) eq $dom) {
 2335:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2336:                 if ($srch->{'srchby'} eq 'email') {
 2337:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2338:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2339:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2340:                              (($major == 2) && ($minor < 12)));
 2341:                 }
 2342:             }
 2343:             my $host=&hostname($tryserver);
 2344:             my $queryid=
 2345:                 &reply("querysend:".&escape($query).':'.
 2346:                        &escape($srch->{'srchby'}).':'.
 2347:                        &escape($srch->{'srchtype'}).':'.
 2348:                        &escape($srch->{'srchterm'}),$tryserver);
 2349:             if ($queryid !~/^\Q$host\E\_/) {
 2350:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2351:                 next;
 2352:             }
 2353:             my $reply = &get_query_reply($queryid);
 2354:             my $maxtries = 1;
 2355:             my $tries = 1;
 2356:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2357:                 $reply = &get_query_reply($queryid);
 2358:                 $tries ++;
 2359:             }
 2360:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2361:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2362:             } else {
 2363:                 my @matches;
 2364:                 if ($reply =~ /\n/) {
 2365:                     @matches = split(/\n/,$reply);
 2366:                 } else {
 2367:                     @matches = split(/\&/,$reply);
 2368:                 }
 2369:                 foreach my $match (@matches) {
 2370:                     my ($uname,$udom,%userhash);
 2371:                     foreach my $entry (split(/:/,$match)) {
 2372:                         my ($key,$value) =
 2373:                             map {&unescape($_);} split(/=/,$entry);
 2374:                         $userhash{$key} = $value;
 2375:                         if ($key eq 'username') {
 2376:                             $uname = $value;
 2377:                         } elsif ($key eq 'domain') {
 2378:                             $udom = $value;
 2379:                         }
 2380:                     }
 2381:                     $results{$uname.':'.$udom} = \%userhash;
 2382:                 }
 2383:             }
 2384:         }
 2385:     }
 2386:     return %results;
 2387: }
 2388: 
 2389: sub get_instuser {
 2390:     my ($udom,$uname,$id) = @_;
 2391:     my $homeserver = &domain($udom,'primary');
 2392:     my ($outcome,%results);
 2393:     if ($homeserver ne '') {
 2394:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2395:                            &escape($id).':'.&escape($udom),$homeserver);
 2396:         my $host=&hostname($homeserver);
 2397:         if ($queryid !~/^\Q$host\E\_/) {
 2398:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2399:             return;
 2400:         }
 2401:         my $response = &get_query_reply($queryid);
 2402:         my $maxtries = 5;
 2403:         my $tries = 1;
 2404:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2405:             $response = &get_query_reply($queryid);
 2406:             $tries ++;
 2407:         }
 2408:         if (!&error($response) && $response ne 'refused') {
 2409:             if ($response eq 'unavailable') {
 2410:                 $outcome = $response;
 2411:             } else {
 2412:                 $outcome = 'ok';
 2413:                 my @matches = split(/\n/,$response);
 2414:                 foreach my $match (@matches) {
 2415:                     my ($key,$value) = split(/=/,$match);
 2416:                     $results{&unescape($key)} = &thaw_unescape($value);
 2417:                 }
 2418:             }
 2419:         }
 2420:     }
 2421:     my %userinfo;
 2422:     if (ref($results{$uname}) eq 'HASH') {
 2423:         %userinfo = %{$results{$uname}};
 2424:     } 
 2425:     return ($outcome,%userinfo);
 2426: }
 2427: 
 2428: sub get_multiple_instusers {
 2429:     my ($udom,$users,$caller) = @_;
 2430:     my ($outcome,$results);
 2431:     if (ref($users) eq 'HASH') {
 2432:         my $count = keys(%{$users}); 
 2433:         my $requested = &freeze_escape($users);
 2434:         my $homeserver = &domain($udom,'primary');
 2435:         if ($homeserver ne '') {
 2436:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2437:             my $host=&hostname($homeserver);
 2438:             if ($queryid !~/^\Q$host\E\_/) {
 2439:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2440:                          ' for host: '.$homeserver.'in domain '.$udom);
 2441:                 return ($outcome,$results);
 2442:             }
 2443:             my $response = &get_query_reply($queryid);
 2444:             my $maxtries = 5;
 2445:             if ($count > 100) {
 2446:                 $maxtries = 1+int($count/20);
 2447:             }
 2448:             my $tries = 1;
 2449:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2450:                 $response = &get_query_reply($queryid);
 2451:                 $tries ++;
 2452:             }
 2453:             if ($response eq '') {
 2454:                 $results = {};
 2455:                 foreach my $key (keys(%{$users})) {
 2456:                     my ($uname,$id);
 2457:                     if ($caller eq 'id') {
 2458:                         $id = $key;
 2459:                     } else {
 2460:                         $uname = $key;
 2461:                     }
 2462:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2463:                     $outcome = $resp;
 2464:                     if ($resp eq 'ok') {
 2465:                         %{$results} = (%{$results}, %info);
 2466:                     } else {
 2467:                         last;
 2468:                     }
 2469:                 }
 2470:             } elsif(!&error($response) && ($response ne 'refused')) {
 2471:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2472:                     $outcome = $response;
 2473:                 } else {
 2474:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2475:                     if ($outcome eq 'ok') {
 2476:                         $results = &thaw_unescape($userdata); 
 2477:                     }
 2478:                 }
 2479:             }
 2480:         }
 2481:     }
 2482:     return ($outcome,$results);
 2483: }
 2484: 
 2485: sub inst_rulecheck {
 2486:     my ($udom,$uname,$id,$item,$rules) = @_;
 2487:     my %returnhash;
 2488:     if ($udom ne '') {
 2489:         if (ref($rules) eq 'ARRAY') {
 2490:             @{$rules} = map {&escape($_);} (@{$rules});
 2491:             my $rulestr = join(':',@{$rules});
 2492:             my $homeserver=&domain($udom,'primary');
 2493:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2494:                 my $response;
 2495:                 if ($item eq 'username') {                
 2496:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2497:                                               ':'.&escape($uname).':'.$rulestr,
 2498:                                               $homeserver));
 2499:                 } elsif ($item eq 'id') {
 2500:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2501:                                               ':'.&escape($id).':'.$rulestr,
 2502:                                               $homeserver));
 2503:                 } elsif ($item eq 'selfcreate') {
 2504:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2505:                                                &escape($udom).':'.&escape($uname).
 2506:                                               ':'.$rulestr,$homeserver));
 2507:                 }
 2508:                 if ($response ne 'refused') {
 2509:                     my @pairs=split(/\&/,$response);
 2510:                     foreach my $item (@pairs) {
 2511:                         my ($key,$value)=split(/=/,$item,2);
 2512:                         $key = &unescape($key);
 2513:                         next if ($key =~ /^error: 2 /);
 2514:                         $returnhash{$key}=&thaw_unescape($value);
 2515:                     }
 2516:                 }
 2517:             }
 2518:         }
 2519:     }
 2520:     return %returnhash;
 2521: }
 2522: 
 2523: sub inst_userrules {
 2524:     my ($udom,$check) = @_;
 2525:     my (%ruleshash,@ruleorder);
 2526:     if ($udom ne '') {
 2527:         my $homeserver=&domain($udom,'primary');
 2528:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2529:             my $response;
 2530:             if ($check eq 'id') {
 2531:                 $response=&reply('instidrules:'.&escape($udom),
 2532:                                  $homeserver);
 2533:             } elsif ($check eq 'email') {
 2534:                 $response=&reply('instemailrules:'.&escape($udom),
 2535:                                  $homeserver);
 2536:             } else {
 2537:                 $response=&reply('instuserrules:'.&escape($udom),
 2538:                                  $homeserver);
 2539:             }
 2540:             if (($response ne 'refused') && ($response ne 'error') && 
 2541:                 ($response ne 'unknown_cmd') && 
 2542:                 ($response ne 'no_such_host')) {
 2543:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2544:                 my @pairs=split(/\&/,$hashitems);
 2545:                 foreach my $item (@pairs) {
 2546:                     my ($key,$value)=split(/=/,$item,2);
 2547:                     $key = &unescape($key);
 2548:                     next if ($key =~ /^error: 2 /);
 2549:                     $ruleshash{$key}=&thaw_unescape($value);
 2550:                 }
 2551:                 my @esc_order = split(/\&/,$orderitems);
 2552:                 foreach my $item (@esc_order) {
 2553:                     push(@ruleorder,&unescape($item));
 2554:                 }
 2555:             }
 2556:         }
 2557:     }
 2558:     return (\%ruleshash,\@ruleorder);
 2559: }
 2560: 
 2561: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2562: 
 2563: sub get_domain_defaults {
 2564:     my ($domain,$ignore_cache) = @_;
 2565:     return if (($domain eq '') || ($domain eq 'public'));
 2566:     my $cachetime = 60*60*24;
 2567:     unless ($ignore_cache) {
 2568:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2569:         if (defined($cached)) {
 2570:             if (ref($result) eq 'HASH') {
 2571:                 return %{$result};
 2572:             }
 2573:         }
 2574:     }
 2575:     my %domdefaults;
 2576:     my %domconfig =
 2577:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2578:                                   'requestcourses','inststatus',
 2579:                                   'coursedefaults','usersessions',
 2580:                                   'requestauthor','selfenrollment',
 2581:                                   'coursecategories','ssl','autoenroll',
 2582:                                   'trust','helpsettings'],$domain);
 2583:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2584:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2585:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2586:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2587:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2588:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2589:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2590:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2591:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2592:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2593:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2594:     } else {
 2595:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2596:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2597:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2598:     }
 2599:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2600:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2601:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2602:         } else {
 2603:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2604:         }
 2605:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2606:         foreach my $item (@usertools) {
 2607:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2608:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2609:             }
 2610:         }
 2611:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2612:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2613:         }
 2614:     }
 2615:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2616:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2617:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2618:         }
 2619:     }
 2620:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2621:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2622:     }
 2623:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2624:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2625:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2626:         }
 2627:     }
 2628:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2629:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2630:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2631:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2632:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2633:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2634:         }
 2635:         foreach my $type (@coursetypes) {
 2636:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2637:                 unless ($type eq 'community') {
 2638:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2639:                 }
 2640:             }
 2641:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2642:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2643:             }
 2644:             if ($domdefaults{'postsubmit'} eq 'on') {
 2645:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2646:                     $domdefaults{$type.'postsubtimeout'} = 
 2647:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2648:                 }
 2649:             }
 2650:         }
 2651:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2652:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2653:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2654:                 if (@clonecodes) {
 2655:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2656:                 }
 2657:             }
 2658:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2659:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2660:         }
 2661:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2662:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2663:         } 
 2664:     }
 2665:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2666:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2667:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2668:         }
 2669:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2670:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2671:         }
 2672:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2673:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2674:         }
 2675:     }
 2676:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2677:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2678:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2679:                             'approval','limit');
 2680:             foreach my $type (@coursetypes) {
 2681:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2682:                     my @mgrdc = ();
 2683:                     foreach my $item (@settings) {
 2684:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2685:                             push(@mgrdc,$item);
 2686:                         }
 2687:                     }
 2688:                     if (@mgrdc) {
 2689:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2690:                     }
 2691:                 }
 2692:             }
 2693:         }
 2694:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2695:             foreach my $type (@coursetypes) {
 2696:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2697:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2698:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2699:                     }
 2700:                 }
 2701:             }
 2702:         }
 2703:     }
 2704:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2705:         $domdefaults{'catauth'} = 'std';
 2706:         $domdefaults{'catunauth'} = 'std';
 2707:         if ($domconfig{'coursecategories'}{'auth'}) {
 2708:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2709:         }
 2710:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2711:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2712:         }
 2713:     }
 2714:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2715:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2716:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2717:         }
 2718:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2719:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2720:         }
 2721:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2722:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2723:         }
 2724:     }
 2725:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2726:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2727:         foreach my $prefix (@prefixes) {
 2728:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2729:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2730:             }
 2731:         }
 2732:     }
 2733:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2734:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2735:     }
 2736:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2737:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2738:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2739:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2740:         }
 2741:     }
 2742:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2743:     return %domdefaults;
 2744: }
 2745: 
 2746: sub get_dom_cats {
 2747:     my ($dom) = @_;
 2748:     return unless (&domain($dom));
 2749:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2750:     unless (defined($cached)) {
 2751:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2752:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2753:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2754:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2755:             } else {
 2756:                 $cats = {};
 2757:             }
 2758:         } else {
 2759:             $cats = {};
 2760:         }
 2761:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2762:     }
 2763:     return $cats;
 2764: }
 2765: 
 2766: sub get_dom_instcats {
 2767:     my ($dom) = @_;
 2768:     return unless (&domain($dom));
 2769:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2770:     unless (defined($cached)) {
 2771:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2772:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2773:         if ($totcodes > 0) {
 2774:             my $caller = 'global';
 2775:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2776:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2777:                 $instcats = {
 2778:                                 codes => \%codes,
 2779:                                 codetitles => \@codetitles,
 2780:                                 cat_titles => \%cat_titles,
 2781:                                 cat_order => \%cat_order,
 2782:                             };
 2783:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2784:             }
 2785:         }
 2786:     }
 2787:     return $instcats;
 2788: }
 2789: 
 2790: sub retrieve_instcodes {
 2791:     my ($coursecodes,$dom) = @_;
 2792:     my $totcodes;
 2793:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2794:     foreach my $course (keys(%courses)) {
 2795:         if (ref($courses{$course}) eq 'HASH') {
 2796:             if ($courses{$course}{'inst_code'} ne '') {
 2797:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2798:                 $totcodes ++;
 2799:             }
 2800:         }
 2801:     }
 2802:     return $totcodes;
 2803: }
 2804: 
 2805: sub course_portal_url {
 2806:     my ($cnum,$cdom) = @_;
 2807:     my $chome = &homeserver($cnum,$cdom);
 2808:     my $hostname = &hostname($chome);
 2809:     my $protocol = $protocol{$chome};
 2810:     $protocol = 'http' if ($protocol ne 'https');
 2811:     my %domdefaults = &get_domain_defaults($cdom);
 2812:     my $firsturl;
 2813:     if ($domdefaults{'portal_def'}) {
 2814:         $firsturl = $domdefaults{'portal_def'};
 2815:     } else {
 2816:         $firsturl = $protocol.'://'.$hostname;
 2817:     }
 2818:     return $firsturl;
 2819: }
 2820: 
 2821: # --------------------------------------------- Get domain config for passwords
 2822: 
 2823: sub get_passwdconf {
 2824:     my ($dom) = @_;
 2825:     my (%passwdconf,$gotconf,$lookup);
 2826:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2827:     if (defined($cached)) {
 2828:         if (ref($result) eq 'HASH') {
 2829:             %passwdconf = %{$result};
 2830:             $gotconf = 1;
 2831:         }
 2832:     }
 2833:     unless ($gotconf) {
 2834:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2835:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2836:             %passwdconf = %{$domconfig{'passwords'}};
 2837:         }
 2838:         my $cachetime = 24*60*60;
 2839:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2840:     }
 2841:     return %passwdconf;
 2842: }
 2843: 
 2844: # --------------------------------------------------- Assign a key to a student
 2845: 
 2846: sub assign_access_key {
 2847: #
 2848: # a valid key looks like uname:udom#comments
 2849: # comments are being appended
 2850: #
 2851:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2852:     $kdom=
 2853:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2854:     $knum=
 2855:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2856:     $cdom=
 2857:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2858:     $cnum=
 2859:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2860:     $udom=$env{'user.name'} unless (defined($udom));
 2861:     $uname=$env{'user.domain'} unless (defined($uname));
 2862:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2863:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2864:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2865:                                                   # assigned to this person
 2866:                                                   # - this should not happen,
 2867:                                                   # unless something went wrong
 2868:                                                   # the first time around
 2869: # ready to assign
 2870:         $logentry=$1.'; '.$logentry;
 2871:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2872:                                                  $kdom,$knum) eq 'ok') {
 2873: # key now belongs to user
 2874: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2875:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2876:                 &appenv({'environment.'.$envkey => $ckey});
 2877:                 return 'ok';
 2878:             } else {
 2879:                 return 
 2880:   'error: Count not permanently assign key, will need to be re-entered later.';
 2881: 	    }
 2882:         } else {
 2883:             return 'error: Could not assign key, try again later.';
 2884:         }
 2885:     } elsif (!$existing{$ckey}) {
 2886: # the key does not exist
 2887: 	return 'error: The key does not exist';
 2888:     } else {
 2889: # the key is somebody else's
 2890: 	return 'error: The key is already in use';
 2891:     }
 2892: }
 2893: 
 2894: # ------------------------------------------ put an additional comment on a key
 2895: 
 2896: sub comment_access_key {
 2897: #
 2898: # a valid key looks like uname:udom#comments
 2899: # comments are being appended
 2900: #
 2901:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2902:     $cdom=
 2903:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2904:     $cnum=
 2905:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2906:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2907:     if ($existing{$ckey}) {
 2908:         $existing{$ckey}.='; '.$logentry;
 2909: # ready to assign
 2910:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2911:                                                  $cdom,$cnum) eq 'ok') {
 2912: 	    return 'ok';
 2913:         } else {
 2914: 	    return 'error: Count not store comment.';
 2915:         }
 2916:     } else {
 2917: # the key does not exist
 2918: 	return 'error: The key does not exist';
 2919:     }
 2920: }
 2921: 
 2922: # ------------------------------------------------------ Generate a set of keys
 2923: 
 2924: sub generate_access_keys {
 2925:     my ($number,$cdom,$cnum,$logentry)=@_;
 2926:     $cdom=
 2927:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2928:     $cnum=
 2929:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2930:     unless (&allowed('mky',$cdom)) { return 0; }
 2931:     unless (($cdom) && ($cnum)) { return 0; }
 2932:     if ($number>10000) { return 0; }
 2933:     sleep(2); # make sure don't get same seed twice
 2934:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2935:     my $total=0;
 2936:     for (my $i=1;$i<=$number;$i++) {
 2937:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2938:                   sprintf("%lx",int(100000*rand)).'-'.
 2939:                   sprintf("%lx",int(100000*rand));
 2940:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2941:        $newkey=~s/0/h/g; # and also 0 and O
 2942:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2943:        if ($existing{$newkey}) {
 2944:            $i--;
 2945:        } else {
 2946: 	  if (&put('accesskeys',
 2947:               { $newkey => '# generated '.localtime().
 2948:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2949:                            '; '.$logentry },
 2950: 		   $cdom,$cnum) eq 'ok') {
 2951:               $total++;
 2952: 	  }
 2953:        }
 2954:     }
 2955:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2956:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2957:     return $total;
 2958: }
 2959: 
 2960: # ------------------------------------------------------- Validate an accesskey
 2961: 
 2962: sub validate_access_key {
 2963:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2964:     $cdom=
 2965:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2966:     $cnum=
 2967:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2968:     $udom=$env{'user.domain'} unless (defined($udom));
 2969:     $uname=$env{'user.name'} unless (defined($uname));
 2970:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2971:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2972: }
 2973: 
 2974: # ------------------------------------- Find the section of student in a course
 2975: sub devalidate_getsection_cache {
 2976:     my ($udom,$unam,$courseid)=@_;
 2977:     my $hashid="$udom:$unam:$courseid";
 2978:     &devalidate_cache_new('getsection',$hashid);
 2979: }
 2980: 
 2981: sub courseid_to_courseurl {
 2982:     my ($courseid) = @_;
 2983:     #already url style courseid
 2984:     return $courseid if ($courseid =~ m{^/});
 2985: 
 2986:     if (exists($env{'course.'.$courseid.'.num'})) {
 2987: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2988: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2989: 	return "/$cdom/$cnum";
 2990:     }
 2991: 
 2992:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2993:     if (exists($courseinfo{'num'})) {
 2994: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2995:     }
 2996: 
 2997:     return undef;
 2998: }
 2999: 
 3000: sub getsection {
 3001:     my ($udom,$unam,$courseid)=@_;
 3002:     my $cachetime=1800;
 3003: 
 3004:     my $hashid="$udom:$unam:$courseid";
 3005:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3006:     if (defined($cached)) { return $result; }
 3007: 
 3008:     my %Pending; 
 3009:     my %Expired;
 3010:     #
 3011:     # Each role can either have not started yet (pending), be active, 
 3012:     #    or have expired.
 3013:     #
 3014:     # If there is an active role, we are done.
 3015:     #
 3016:     # If there is more than one role which has not started yet, 
 3017:     #     choose the one which will start sooner
 3018:     # If there is one role which has not started yet, return it.
 3019:     #
 3020:     # If there is more than one expired role, choose the one which ended last.
 3021:     # If there is a role which has expired, return it.
 3022:     #
 3023:     $courseid = &courseid_to_courseurl($courseid);
 3024:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3025:     foreach my $key (keys(%roleshash)) {
 3026:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3027:         my $section=$1;
 3028:         if ($key eq $courseid.'_st') { $section=''; }
 3029:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3030:         my $now=time;
 3031:         if (defined($end) && $end && ($now > $end)) {
 3032:             $Expired{$end}=$section;
 3033:             next;
 3034:         }
 3035:         if (defined($start) && $start && ($now < $start)) {
 3036:             $Pending{$start}=$section;
 3037:             next;
 3038:         }
 3039:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3040:     }
 3041:     #
 3042:     # Presumedly there will be few matching roles from the above
 3043:     # loop and the sorting time will be negligible.
 3044:     if (scalar(keys(%Pending))) {
 3045:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3046:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3047:     } 
 3048:     if (scalar(keys(%Expired))) {
 3049:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3050:         my $time = pop(@sorted);
 3051:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3052:     }
 3053:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3054: }
 3055: 
 3056: sub save_cache {
 3057:     &purge_remembered();
 3058:     #&Apache::loncommon::validate_page();
 3059:     undef(%env);
 3060:     undef($env_loaded);
 3061: }
 3062: 
 3063: my $to_remember=-1;
 3064: my %remembered;
 3065: my %accessed;
 3066: my $kicks=0;
 3067: my $hits=0;
 3068: sub make_key {
 3069:     my ($name,$id) = @_;
 3070:     if (length($id) > 65 
 3071: 	&& length(&escape($id)) > 200) {
 3072: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3073:     }
 3074:     return &escape($name.':'.$id);
 3075: }
 3076: 
 3077: sub devalidate_cache_new {
 3078:     my ($name,$id,$debug) = @_;
 3079:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3080:     my $remembered_id=$name.':'.$id;
 3081:     $id=&make_key($name,$id);
 3082:     $memcache->delete($id);
 3083:     delete($remembered{$remembered_id});
 3084:     delete($accessed{$remembered_id});
 3085: }
 3086: 
 3087: sub is_cached_new {
 3088:     my ($name,$id,$debug) = @_;
 3089:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3090:     if (exists($remembered{$remembered_id})) {
 3091: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3092: 	$accessed{$remembered_id}=[&gettimeofday()];
 3093: 	$hits++;
 3094: 	return ($remembered{$remembered_id},1);
 3095:     }
 3096:     $id=&make_key($name,$id);
 3097:     my $value = $memcache->get($id);
 3098:     if (!(defined($value))) {
 3099: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3100: 	return (undef,undef);
 3101:     }
 3102:     if ($value eq '__undef__') {
 3103: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3104: 	$value=undef;
 3105:     }
 3106:     &make_room($remembered_id,$value,$debug);
 3107:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3108:     return ($value,1);
 3109: }
 3110: 
 3111: sub do_cache_new {
 3112:     my ($name,$id,$value,$time,$debug) = @_;
 3113:     my $remembered_id=$name.':'.$id;
 3114:     $id=&make_key($name,$id);
 3115:     my $setvalue=$value;
 3116:     if (!defined($setvalue)) {
 3117: 	$setvalue='__undef__';
 3118:     }
 3119:     if (!defined($time) ) {
 3120: 	$time=600;
 3121:     }
 3122:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3123:     my $result = $memcache->set($id,$setvalue,$time);
 3124:     if (! $result) {
 3125: 	&logthis("caching of id -> $id  failed");
 3126: 	$memcache->disconnect_all();
 3127:     }
 3128:     # need to make a copy of $value
 3129:     &make_room($remembered_id,$value,$debug);
 3130:     return $value;
 3131: }
 3132: 
 3133: sub make_room {
 3134:     my ($remembered_id,$value,$debug)=@_;
 3135: 
 3136:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3137:                                     : $value;
 3138:     if ($to_remember<0) { return; }
 3139:     $accessed{$remembered_id}=[&gettimeofday()];
 3140:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3141:     my $to_kick;
 3142:     my $max_time=0;
 3143:     foreach my $other (keys(%accessed)) {
 3144: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3145: 	    $to_kick=$other;
 3146: 	    $max_time=&tv_interval($accessed{$other});
 3147: 	}
 3148:     }
 3149:     delete($remembered{$to_kick});
 3150:     delete($accessed{$to_kick});
 3151:     $kicks++;
 3152:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3153:     return;
 3154: }
 3155: 
 3156: sub purge_remembered {
 3157:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3158:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3159:     undef(%remembered);
 3160:     undef(%accessed);
 3161: }
 3162: # ------------------------------------- Read an entry from a user's environment
 3163: 
 3164: sub userenvironment {
 3165:     my ($udom,$unam,@what)=@_;
 3166:     my $items;
 3167:     foreach my $item (@what) {
 3168:         $items.=&escape($item).'&';
 3169:     }
 3170:     $items=~s/\&$//;
 3171:     my %returnhash=();
 3172:     my $uhome = &homeserver($unam,$udom);
 3173:     unless ($uhome eq 'no_host') {
 3174:         my @answer=split(/\&/, 
 3175:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3176:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3177:             return %returnhash;
 3178:         }
 3179:         my $i;
 3180:         for ($i=0;$i<=$#what;$i++) {
 3181: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3182:         }
 3183:     }
 3184:     return %returnhash;
 3185: }
 3186: 
 3187: # ---------------------------------------------------------- Get a studentphoto
 3188: sub studentphoto {
 3189:     my ($udom,$unam,$ext) = @_;
 3190:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3191:     if (defined($env{'request.course.id'})) {
 3192:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3193:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3194:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3195:             } else {
 3196:                 my ($result,$perm_reqd)=
 3197: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3198:                 if ($result eq 'ok') {
 3199:                     if (!($perm_reqd eq 'yes')) {
 3200:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3201:                     }
 3202:                 }
 3203:             }
 3204:         }
 3205:     } else {
 3206:         my ($result,$perm_reqd) = 
 3207: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3208:         if ($result eq 'ok') {
 3209:             if (!($perm_reqd eq 'yes')) {
 3210:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3211:             }
 3212:         }
 3213:     }
 3214:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3215: }
 3216: 
 3217: sub retrievestudentphoto {
 3218:     my ($udom,$unam,$ext,$type) = @_;
 3219:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3220:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3221:     if ($ret eq 'ok') {
 3222:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3223:         if ($type eq 'thumbnail') {
 3224:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3225:         }
 3226:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3227:         return $tokenurl;
 3228:     } else {
 3229:         if ($type eq 'thumbnail') {
 3230:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3231:         } else { 
 3232:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3233:         }
 3234:     }
 3235: }
 3236: 
 3237: # -------------------------------------------------------------------- New chat
 3238: 
 3239: sub chatsend {
 3240:     my ($newentry,$anon,$group)=@_;
 3241:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3242:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3243:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3244:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3245: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3246: 		   &escape($newentry)).':'.$group,$chome);
 3247: }
 3248: 
 3249: # ------------------------------------------ Find current version of a resource
 3250: 
 3251: sub getversion {
 3252:     my $fname=&clutter(shift);
 3253:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3254:     return &currentversion(&filelocation('',$fname));
 3255: }
 3256: 
 3257: sub currentversion {
 3258:     my $fname=shift;
 3259:     my $author=$fname;
 3260:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3261:     my ($udom,$uname)=split(/\//,$author);
 3262:     my $home=&homeserver($uname,$udom);
 3263:     if ($home eq 'no_host') { 
 3264:         return -1; 
 3265:     }
 3266:     my $answer=&reply("currentversion:$fname",$home);
 3267:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3268: 	return -1;
 3269:     }
 3270:     return $answer;
 3271: }
 3272: 
 3273: #
 3274: # Return special version number of resource if set by override, empty otherwise
 3275: #
 3276: sub usedversion {
 3277:     my $fname=shift;
 3278:     unless ($fname) { $fname=$env{'request.uri'}; }
 3279:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3280:     if ($urlversion) { return $urlversion; }
 3281:     return '';
 3282: }
 3283: 
 3284: # ----------------------------- Subscribe to a resource, return URL if possible
 3285: 
 3286: sub subscribe {
 3287:     my $fname=shift;
 3288:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3289:     $fname=~s/[\n\r]//g;
 3290:     my $author=$fname;
 3291:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3292:     my ($udom,$uname)=split(/\//,$author);
 3293:     my $home=homeserver($uname,$udom);
 3294:     if ($home eq 'no_host') {
 3295:         return 'not_found';
 3296:     }
 3297:     my $answer=reply("sub:$fname",$home);
 3298:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3299: 	$answer.=' by '.$home;
 3300:     }
 3301:     return $answer;
 3302: }
 3303:     
 3304: # -------------------------------------------------------------- Replicate file
 3305: 
 3306: sub repcopy {
 3307:     my $filename=shift;
 3308:     $filename=~s/\/+/\//g;
 3309:     my $londocroot = $perlvar{'lonDocRoot'};
 3310:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3311:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3312:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3313: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3314: 	return &repcopy_userfile($filename);
 3315:     }
 3316:     $filename=~s/[\n\r]//g;
 3317:     my $transname="$filename.in.transfer";
 3318: # FIXME: this should flock
 3319:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3320:     my $remoteurl=subscribe($filename);
 3321:     if ($remoteurl =~ /^con_lost by/) {
 3322: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3323:            return 'unavailable';
 3324:     } elsif ($remoteurl eq 'not_found') {
 3325: 	   #&logthis("Subscribe returned not_found: $filename");
 3326: 	   return 'not_found';
 3327:     } elsif ($remoteurl =~ /^rejected by/) {
 3328: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3329:            return 'forbidden';
 3330:     } elsif ($remoteurl eq 'directory') {
 3331:            return 'ok';
 3332:     } else {
 3333:         my $author=$filename;
 3334:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3335:         my ($udom,$uname)=split(/\//,$author);
 3336:         my $home=homeserver($uname,$udom);
 3337:         unless ($home eq $perlvar{'lonHostID'}) {
 3338:            my @parts=split(/\//,$filename);
 3339:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3340:            if ($path ne "$londocroot/res") {
 3341:                &logthis("Malconfiguration for replication: $filename");
 3342: 	       return 'bad_request';
 3343:            }
 3344:            my $count;
 3345:            for ($count=5;$count<$#parts;$count++) {
 3346:                $path.="/$parts[$count]";
 3347:                if ((-e $path)!=1) {
 3348: 		   mkdir($path,0777);
 3349:                }
 3350:            }
 3351:            my $request=new HTTP::Request('GET',"$remoteurl");
 3352:            my $response;
 3353:            if ($remoteurl =~ m{/raw/}) {
 3354:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3355:            } else {
 3356:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3357:            }
 3358:            if ($response->is_error()) {
 3359: 	       unlink($transname);
 3360:                my $message=$response->status_line;
 3361:                &logthis("<font color=\"blue\">WARNING:"
 3362:                        ." LWP get: $message: $filename</font>");
 3363:                return 'unavailable';
 3364:            } else {
 3365: 	       if ($remoteurl!~/\.meta$/) {
 3366:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3367:                   my $mresponse;
 3368:                   if ($remoteurl =~ m{/raw/}) {
 3369:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3370:                   } else {
 3371:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3372:                   }
 3373:                   if ($mresponse->is_error()) {
 3374: 		      unlink($filename.'.meta');
 3375:                       &logthis(
 3376:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3377:                   }
 3378: 	       }
 3379:                rename($transname,$filename);
 3380:                return 'ok';
 3381:            }
 3382:        }
 3383:     }
 3384: }
 3385: 
 3386: # ------------------------------------------------ Get server side include body
 3387: sub ssi_body {
 3388:     my ($filelink,%form)=@_;
 3389:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3390:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3391:     }
 3392:     my $output='';
 3393:     my $response;
 3394:     if ($filelink=~/^https?\:/) {
 3395:        ($output,$response)=&externalssi($filelink);
 3396:     } else {
 3397:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3398:        $filelink .= 'inhibitmenu=yes';
 3399:        ($output,$response)=&ssi($filelink,%form);
 3400:     }
 3401:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3402:     $output=~s/^.*?\<body[^\>]*\>//si;
 3403:     $output=~s/\<\/body\s*\>.*?$//si;
 3404:     if (wantarray) {
 3405:         return ($output, $response);
 3406:     } else {
 3407:         return $output;
 3408:     }
 3409: }
 3410: 
 3411: # --------------------------------------------------------- Server Side Include
 3412: 
 3413: sub absolute_url {
 3414:     my ($host_name) = @_;
 3415:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3416:     if ($host_name eq '') {
 3417: 	$host_name = $ENV{'SERVER_NAME'};
 3418:     }
 3419:     return $protocol.$host_name;
 3420: }
 3421: 
 3422: #
 3423: #   Server side include.
 3424: # Parameters:
 3425: #  fn     Possibly encrypted resource name/id.
 3426: #  form   Hash that describes how the rendering should be done
 3427: #         and other things.
 3428: # Returns:
 3429: #   Scalar context: The content of the response.
 3430: #   Array context:  2 element list of the content and the full response object.
 3431: #     
 3432: sub ssi {
 3433: 
 3434:     my ($fn,%form)=@_;
 3435:     my $request;
 3436: 
 3437:     $form{'no_update_last_known'}=1;
 3438:     &Apache::lonenc::check_encrypt(\$fn);
 3439:     if (%form) {
 3440:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3441:       $request->content(join('&',map { 
 3442:             my $name = escape($_);
 3443:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3444:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3445:             : &escape($form{$_}) );    
 3446:         } keys(%form)));
 3447:     } else {
 3448:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3449:     }
 3450: 
 3451:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3452:     my $lonhost = $perlvar{'lonHostID'};
 3453:     my $islocal;
 3454:     if (($env{'request.course.id'}) &&
 3455:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3456:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3457:         ($form{'grade_symb'} ne '') &&
 3458:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3459:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3460:         $islocal = 1;
 3461:     }
 3462:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3463:                                                 '','','',$islocal);
 3464: 
 3465:     if (wantarray) {
 3466: 	return ($response->content, $response);
 3467:     } else {
 3468: 	return $response->content;
 3469:     }
 3470: }
 3471: 
 3472: sub externalssi {
 3473:     my ($url)=@_;
 3474:     my $request=new HTTP::Request('GET',$url);
 3475:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3476:     if (wantarray) {
 3477:         return ($response->content, $response);
 3478:     } else {
 3479:         return $response->content;
 3480:     }
 3481: }
 3482: 
 3483: 
 3484: # If the local copy of a replicated resource is outdated, trigger a  
 3485: # connection from the homeserver to flush the delayed queue. If no update 
 3486: # happens, remove local copies of outdated resource (and corresponding
 3487: # metadata file).
 3488: 
 3489: sub remove_stale_resfile {
 3490:     my ($url) = @_;
 3491:     my $removed;
 3492:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3493:         my $audom = $1;
 3494:         my $auname = $2;
 3495:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3496:             my $homeserver = &homeserver($auname,$audom);
 3497:             unless (($homeserver eq 'no_host') ||
 3498:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3499:                 my $fname = &filelocation('',$url);
 3500:                 if (-e $fname) {
 3501:                     my $hostname = &hostname($homeserver);
 3502:                     if ($hostname) {
 3503:                         my $protocol = $protocol{$homeserver};
 3504:                         $protocol = 'http' if ($protocol ne 'https');
 3505:                         my $uri = &declutter($url);
 3506:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3507:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3508:                         if ($response->is_success()) {
 3509:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3510:                             my $locmodtime = (stat($fname))[9];
 3511:                             if ($locmodtime < $remmodtime) {
 3512:                                 my $stale;
 3513:                                 my $answer = &reply('pong',$homeserver);
 3514:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3515:                                     sleep(0.2);
 3516:                                     $locmodtime = (stat($fname))[9];
 3517:                                     if ($locmodtime < $remmodtime) {
 3518:                                         my $posstransfer = $fname.'.in.transfer';
 3519:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3520:                                             $removed = 1;
 3521:                                         } else {
 3522:                                             $stale = 1;
 3523:                                         }
 3524:                                     } else {
 3525:                                         $removed = 1;
 3526:                                     }
 3527:                                 } else {
 3528:                                     $stale = 1;
 3529:                                 }
 3530:                                 if ($stale) {
 3531:                                     unlink($fname);
 3532:                                     if ($uri!~/\.meta$/) {
 3533:                                         unlink($fname.'.meta');
 3534:                                     }
 3535:                                     &reply("unsub:$fname",$homeserver);
 3536:                                     $removed = 1;
 3537:                                 }
 3538:                             }
 3539:                         }
 3540:                     }
 3541:                 }
 3542:             }
 3543:         }
 3544:     }
 3545:     return $removed;
 3546: }
 3547: 
 3548: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3549: 
 3550: sub allowuploaded {
 3551:     my ($srcurl,$url)=@_;
 3552:     $url=&clutter(&declutter($url));
 3553:     my $dir=$url;
 3554:     $dir=~s/\/[^\/]+$//;
 3555:     my %httpref=();
 3556:     my $httpurl=&hreflocation('',$url);
 3557:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3558:     &Apache::lonnet::appenv(\%httpref);
 3559: }
 3560: 
 3561: #
 3562: # Determine if the current user should be able to edit a particular resource,
 3563: # when viewing in course context.
 3564: # (a) When viewing resource used to determine if "Edit" item is included in 
 3565: #     Functions.
 3566: # (b) When displaying folder contents in course editor, used to determine if
 3567: #     "Edit" link will be displayed alongside resource.
 3568: #
 3569: #  input: six args -- filename (decluttered), course number, course domain,
 3570: #                   url, symb (if registered) and group (if this is a group
 3571: #                   item -- e.g., bulletin board, group page etc.).
 3572: #  output: array of five scalars -- 
 3573: #          $cfile -- url for file editing if editable on current server
 3574: #          $home -- homeserver of resource (i.e., for author if published,
 3575: #                                           or course if uploaded.).
 3576: #          $switchserver --  1 if server switch will be needed.
 3577: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3578: #          $forceview -- 1 if icon/link should be to go to view mode
 3579: #
 3580: 
 3581: sub can_edit_resource {
 3582:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3583:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3584: #
 3585: # For aboutme pages user can only edit his/her own.
 3586: #
 3587:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3588:         my ($sdom,$sname) = ($1,$2);
 3589:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3590:             $home = $env{'user.home'};
 3591:             $cfile = $resurl;
 3592:             if ($env{'form.forceedit'}) {
 3593:                 $forceview = 1;
 3594:             } else {
 3595:                 $forceedit = 1;
 3596:             }
 3597:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3598:         } else {
 3599:             return;
 3600:         }
 3601:     }
 3602: 
 3603:     if ($env{'request.course.id'}) {
 3604:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3605:         if ($group ne '') {
 3606: # if this is a group homepage or group bulletin board, check group privs
 3607:             my $allowed = 0;
 3608:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3609:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3610:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3611:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3612:                     $allowed = 1;
 3613:                 }
 3614:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3615:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3616:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3617:                     $allowed = 1;
 3618:                 }
 3619:             }
 3620:             if ($allowed) {
 3621:                 $home=&homeserver($cnum,$cdom);
 3622:                 if ($env{'form.forceedit'}) {
 3623:                     $forceview = 1;
 3624:                 } else {
 3625:                     $forceedit = 1;
 3626:                 }
 3627:                 $cfile = $resurl;
 3628:             } else {
 3629:                 return;
 3630:             }
 3631:         } else {
 3632:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3633:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3634:                     return;
 3635:                 }
 3636:             } elsif (!$crsedit) {
 3637: #
 3638: # No edit allowed where CC has switched to student role.
 3639: #
 3640:                 return;
 3641:             }
 3642:         }
 3643:     }
 3644: 
 3645:     if ($file ne '') {
 3646:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3647:             if (&is_course_upload($file,$cnum,$cdom)) {
 3648:                 $uploaded = 1;
 3649:                 $incourse = 1;
 3650:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3651:                     $cfile = &hreflocation('',$file);
 3652:                     if ($env{'form.forceedit'}) {
 3653:                         $forceview = 1;
 3654:                     } else {
 3655:                         $forceedit = 1;
 3656:                     }
 3657:                 }
 3658:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3659:                 $incourse = 1;
 3660:                 if ($env{'form.forceedit'}) {
 3661:                     $forceview = 1;
 3662:                 } else {
 3663:                     $forceedit = 1;
 3664:                 }
 3665:                 $cfile = $resurl;
 3666:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3667:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3668:                     $incourse = 1;
 3669:                     if ($env{'form.forceedit'}) {
 3670:                         $forceview = 1;
 3671:                     } else {
 3672:                         $forceedit = 1;
 3673:                     }
 3674:                     $cfile = $resurl;
 3675:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3676:                     $incourse = 1;
 3677:                     $cfile = $resurl.'/smpedit';
 3678:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3679:                     $incourse = 1;
 3680:                     if ($env{'form.forceedit'}) {
 3681:                         $forceview = 1;
 3682:                     } else {
 3683:                         $forceedit = 1;
 3684:                     }
 3685:                     $cfile = $resurl;
 3686:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3687:                     my ($map,$id,$res) = &decode_symb($symb);
 3688:                     if ($map =~ /\.page$/) {
 3689:                         $incourse = 1;
 3690:                         if ($env{'form.forceedit'}) {
 3691:                             $forceview = 1;
 3692:                             $cfile = $map;
 3693:                         } else {
 3694:                             $forceedit = 1;
 3695:                             $cfile =  '/adm/wrapper'.$resurl;
 3696:                         }
 3697:                     }
 3698:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3699:                     $incourse = 1;
 3700:                     if ($env{'form.forceedit'}) {
 3701:                         $forceview = 1;
 3702:                     } else {
 3703:                         $forceedit = 1;
 3704:                     }
 3705:                     $cfile = $resurl;
 3706:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3707:                     $incourse = 1;
 3708:                     if ($env{'form.forceedit'}) {
 3709:                         $forceview = 1;
 3710:                     } else {
 3711:                         $forceedit = 1;
 3712:                     }
 3713:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3714:                 }
 3715:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3716:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3717:                 if (&is_on_map($template)) { 
 3718:                     $incourse = 1;
 3719:                     $forceview = 1;
 3720:                     $cfile = $template;
 3721:                 }
 3722:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3723:                 $incourse = 1;
 3724:                 if ($env{'form.forceedit'}) {
 3725:                     $forceview = 1;
 3726:                 } else {
 3727:                     $forceedit = 1;
 3728:                 }
 3729:                 $cfile = $resurl;
 3730:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3731:                 $incourse = 1;
 3732:                 if ($env{'form.forceedit'}) {
 3733:                     $forceview = 1;
 3734:                 } else {
 3735:                     $forceedit = 1;
 3736:                 }
 3737:                 $cfile = $resurl;
 3738:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3739:                 $incourse = 1;
 3740:                 $forceview = 1;
 3741:                 if ($symb) {
 3742:                     my ($map,$id,$res)=&decode_symb($symb);
 3743:                     $env{'request.symb'} = $symb;
 3744:                     $cfile = &clutter($res);
 3745:                 } else {
 3746:                     $cfile = $env{'form.suppurl'};
 3747:                     my $escfile = &unescape($cfile);
 3748:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3749:                         $cfile = '/adm/wrapper'.$escfile;
 3750:                     } else {
 3751:                         $escfile =~ s{^http://}{};
 3752:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3753:                     }
 3754:                 }
 3755:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3756:                 if ($env{'form.forceedit'}) {
 3757:                     $forceview = 1;
 3758:                 } else {
 3759:                     $forceedit = 1;
 3760:                 }
 3761:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3762:             }
 3763:         }
 3764:         if ($uploaded || $incourse) {
 3765:             $home=&homeserver($cnum,$cdom);
 3766:         } elsif ($file !~ m{/$}) {
 3767:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3768:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3769:             # Check that the user has permission to edit this resource
 3770:             my $setpriv = 1;
 3771:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3772:             if (defined($cfudom)) {
 3773:                 $home=&homeserver($cfuname,$cfudom);
 3774:                 $cfile=$file;
 3775:             }
 3776:         }
 3777:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3778:             (($home ne '') && ($home ne 'no_host'))) {
 3779:             my @ids=&current_machine_ids();
 3780:             unless (grep(/^\Q$home\E$/,@ids)) {
 3781:                 $switchserver=1;
 3782:             }
 3783:         }
 3784:     }
 3785:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3786: }
 3787: 
 3788: sub is_course_upload {
 3789:     my ($file,$cnum,$cdom) = @_;
 3790:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3791:     $uploadpath =~ s{^\/}{};
 3792:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3793:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3794:         return 1;
 3795:     }
 3796:     return;
 3797: }
 3798: 
 3799: sub in_course {
 3800:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3801:     if ($hideprivileged) {
 3802:         my $skipuser;
 3803:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3804:         my @possdoms = ($cdom);  
 3805:         if ($coursehash{'checkforpriv'}) { 
 3806:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3807:         }
 3808:         if (&privileged($uname,$udom,\@possdoms)) {
 3809:             $skipuser = 1;
 3810:             if ($coursehash{'nothideprivileged'}) {
 3811:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3812:                     my $user;
 3813:                     if ($item =~ /:/) {
 3814:                         $user = $item;
 3815:                     } else {
 3816:                         $user = join(':',split(/[\@]/,$item));
 3817:                     }
 3818:                     if ($user eq $uname.':'.$udom) {
 3819:                         undef($skipuser);
 3820:                         last;
 3821:                     }
 3822:                 }
 3823:             }
 3824:             if ($skipuser) {
 3825:                 return 0;
 3826:             }
 3827:         }
 3828:     }
 3829:     $type ||= 'any';
 3830:     if (!defined($cdom) || !defined($cnum)) {
 3831:         my $cid  = $env{'request.course.id'};
 3832:         $cdom = $env{'course.'.$cid.'.domain'};
 3833:         $cnum = $env{'course.'.$cid.'.num'};
 3834:     }
 3835:     my $typesref;
 3836:     if (($type eq 'any') || ($type eq 'all')) {
 3837:         $typesref = ['active','previous','future'];
 3838:     } elsif ($type eq 'previous' || $type eq 'future') {
 3839:         $typesref = [$type];
 3840:     }
 3841:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3842:                               $typesref,undef,[$cdom]);
 3843:     my ($tmp) = keys(%roles);
 3844:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3845:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3846:     if (@course_roles > 0) {
 3847:         return 1;
 3848:     }
 3849:     return 0;
 3850: }
 3851: 
 3852: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3853: # input: action, courseID, current domain, intended
 3854: #        path to file, source of file, instruction to parse file for objects,
 3855: #        ref to hash for embedded objects,
 3856: #        ref to hash for codebase of java objects.
 3857: #        reference to scalar to accommodate mime type determined
 3858: #          from File::MMagic if $parser = parse.
 3859: #
 3860: # output: url to file (if action was uploaddoc), 
 3861: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3862: #
 3863: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3864: # course.
 3865: #
 3866: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3867: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3868: #          course's home server.
 3869: #
 3870: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3871: #          be copied from $source (current location) to 
 3872: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3873: #         and will then be copied to
 3874: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3875: #         course's home server.
 3876: #
 3877: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3878: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3879: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3880: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3881: #         in course's home server.
 3882: #
 3883: 
 3884: sub process_coursefile {
 3885:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3886:         $mimetype)=@_;
 3887:     my $fetchresult;
 3888:     my $home=&homeserver($docuname,$docudom);
 3889:     if ($action eq 'propagate') {
 3890:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3891: 			     $home);
 3892:     } else {
 3893:         my $fpath = '';
 3894:         my $fname = $file;
 3895:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3896:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3897:         my $filepath = &build_filepath($fpath);
 3898:         if ($action eq 'copy') {
 3899:             if ($source eq '') {
 3900:                 $fetchresult = 'no source file';
 3901:                 return $fetchresult;
 3902:             } else {
 3903:                 my $destination = $filepath.'/'.$fname;
 3904:                 rename($source,$destination);
 3905:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3906:                                  $home);
 3907:             }
 3908:         } elsif ($action eq 'uploaddoc') {
 3909:             open(my $fh,'>',$filepath.'/'.$fname);
 3910:             print $fh $env{'form.'.$source};
 3911:             close($fh);
 3912:             if ($parser eq 'parse') {
 3913:                 my $mm = new File::MMagic;
 3914:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3915:                 if ($type eq 'text/html') {
 3916:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3917:                     unless ($parse_result eq 'ok') {
 3918:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3919:                     }
 3920:                 }
 3921:                 if (ref($mimetype)) {
 3922:                     $$mimetype = $type;
 3923:                 } 
 3924:             }
 3925:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3926:                                  $home);
 3927:             if ($fetchresult eq 'ok') {
 3928:                 return '/uploaded/'.$fpath.'/'.$fname;
 3929:             } else {
 3930:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3931:                         ' to host '.$home.': '.$fetchresult);
 3932:                 return '/adm/notfound.html';
 3933:             }
 3934:         }
 3935:     }
 3936:     unless ( $fetchresult eq 'ok') {
 3937:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3938:              ' to host '.$home.': '.$fetchresult);
 3939:     }
 3940:     return $fetchresult;
 3941: }
 3942: 
 3943: sub build_filepath {
 3944:     my ($fpath) = @_;
 3945:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3946:     unless ($fpath eq '') {
 3947:         my @parts=split('/',$fpath);
 3948:         foreach my $part (@parts) {
 3949:             $filepath.= '/'.$part;
 3950:             if ((-e $filepath)!=1) {
 3951:                 mkdir($filepath,0777);
 3952:             }
 3953:         }
 3954:     }
 3955:     return $filepath;
 3956: }
 3957: 
 3958: sub store_edited_file {
 3959:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3960:     my $file = $primary_url;
 3961:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3962:     my $fpath = '';
 3963:     my $fname = $file;
 3964:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3965:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3966:     my $filepath = &build_filepath($fpath);
 3967:     open(my $fh,'>',$filepath.'/'.$fname);
 3968:     print $fh $content;
 3969:     close($fh);
 3970:     my $home=&homeserver($docuname,$docudom);
 3971:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3972: 			  $home);
 3973:     if ($$fetchresult eq 'ok') {
 3974:         return '/uploaded/'.$fpath.'/'.$fname;
 3975:     } else {
 3976:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3977: 		 ' to host '.$home.': '.$$fetchresult);
 3978:         return '/adm/notfound.html';
 3979:     }
 3980: }
 3981: 
 3982: sub clean_filename {
 3983:     my ($fname,$args)=@_;
 3984: # Replace Windows backslashes by forward slashes
 3985:     $fname=~s/\\/\//g;
 3986:     if (!$args->{'keep_path'}) {
 3987:         # Get rid of everything but the actual filename
 3988: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3989:     }
 3990: # Replace spaces by underscores
 3991:     $fname=~s/\s+/\_/g;
 3992: # Transliterate non-ascii text to ascii
 3993:     my $lang = &Apache::lonlocal::current_language();
 3994:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 3995: # Replace all other weird characters by nothing
 3996:     $fname=~s{[^/\w\.\-]}{}g;
 3997: # Replace all .\d. sequences with _\d. so they no longer look like version
 3998: # numbers
 3999:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4000:     return $fname;
 4001: }
 4002: 
 4003: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4004: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4005: # image with the same aspect ratio as the original, but with dimensions which do 
 4006: # not exceed $resizewidth and $resizeheight.
 4007:  
 4008: sub resizeImage {
 4009:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4010:     my $ima = Image::Magick->new;
 4011:     my $resized;
 4012:     if (-e $img_path) {
 4013:         $ima->Read($img_path);
 4014:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4015:             my $width = $ima->Get('width');
 4016:             my $height = $ima->Get('height');
 4017:             if ($width > $resizewidth) {
 4018: 	        my $factor = $width/$resizewidth;
 4019:                 my $newheight = $height/$factor;
 4020:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4021:                 $resized = 1;
 4022:             }
 4023:         }
 4024:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4025:             my $width = $ima->Get('width');
 4026:             my $height = $ima->Get('height');
 4027:             if ($height > $resizeheight) {
 4028:                 my $factor = $height/$resizeheight;
 4029:                 my $newwidth = $width/$factor;
 4030:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4031:                 $resized = 1;
 4032:             }
 4033:         }
 4034:         if ($resized) {
 4035:             $ima->Write($img_path);
 4036:         }
 4037:     }
 4038:     return;
 4039: }
 4040: 
 4041: # --------------- Take an uploaded file and put it into the userfiles directory
 4042: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4043: #                    the desired filename is in $env{"form.$formname.filename"}
 4044: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4045: #                                    canceloverwrite, scantron or ''.
 4046: #                   if 'coursedoc': upload to the current course
 4047: #                   if 'existingfile': write file to tmp/overwrites directory 
 4048: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4049: #                   $context is passed as argument to &finishuserfileupload
 4050: #        $subdir - directory in userfile to store the file into
 4051: #        $parser - instruction to parse file for objects ($parser = parse) or
 4052: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4053: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4054: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4055: #        $allfiles - reference to hash for embedded objects
 4056: #        $codebase - reference to hash for codebase of java objects
 4057: #        $desuname - username for permanent storage of uploaded file
 4058: #        $dsetudom - domain for permanaent storage of uploaded file
 4059: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4060: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4061: #        $resizewidth - width (pixels) to which to resize uploaded image
 4062: #        $resizeheight - height (pixels) to which to resize uploaded image
 4063: #        $mimetype - reference to scalar to accommodate mime type determined
 4064: #                    from File::MMagic.
 4065: # 
 4066: # output: url of file in userspace, or error: <message> 
 4067: #             or /adm/notfound.html if failure to upload occurse
 4068: 
 4069: sub userfileupload {
 4070:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4071:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4072:     if (!defined($subdir)) { $subdir='unknown'; }
 4073:     my $fname=$env{'form.'.$formname.'.filename'};
 4074:     $fname=&clean_filename($fname);
 4075:     # See if there is anything left
 4076:     unless ($fname) { return 'error: no uploaded file'; }
 4077:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4078:     if ($fname =~ /^\./) {
 4079:         my ($s,$usec) = &gettimeofday();
 4080:         while (length($usec) < 6) {
 4081:             $usec = '0'.$usec;
 4082:         }
 4083:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4084:     }
 4085:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4086:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4087:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4088:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4089:         my $now = time;
 4090:         my $filepath;
 4091:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4092:              $filepath = 'tmp/helprequests/'.$now;
 4093:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4094:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4095:                          '_'.$env{'user.domain'}.'/pending';
 4096:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4097:             my ($docuname,$docudom);
 4098:             if ($destudom =~ /^$match_domain$/) {
 4099:                 $docudom = $destudom;
 4100:             } else {
 4101:                 $docudom = $env{'user.domain'};
 4102:             }
 4103:             if ($destuname =~ /^$match_username$/) {
 4104:                 $docuname = $destuname;
 4105:             } else {
 4106:                 $docuname = $env{'user.name'};
 4107:             }
 4108:             if (exists($env{'form.group'})) {
 4109:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4110:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4111:             }
 4112:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4113:             if ($context eq 'canceloverwrite') {
 4114:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4115:                 if (-e  $tempfile) {
 4116:                     my @info = stat($tempfile);
 4117:                     if ($info[9] eq $env{'form.timestamp'}) {
 4118:                         unlink($tempfile);
 4119:                     }
 4120:                 }
 4121:                 return;
 4122:             }
 4123:         }
 4124:         # Create the directory if not present
 4125:         my @parts=split(/\//,$filepath);
 4126:         my $fullpath = $perlvar{'lonDaemons'};
 4127:         for (my $i=0;$i<@parts;$i++) {
 4128:             $fullpath .= '/'.$parts[$i];
 4129:             if ((-e $fullpath)!=1) {
 4130:                 mkdir($fullpath,0777);
 4131:             }
 4132:         }
 4133:         open(my $fh,'>',$fullpath.'/'.$fname);
 4134:         print $fh $env{'form.'.$formname};
 4135:         close($fh);
 4136:         if ($context eq 'existingfile') {
 4137:             my @info = stat($fullpath.'/'.$fname);
 4138:             return ($fullpath.'/'.$fname,$info[9]);
 4139:         } else {
 4140:             return $fullpath.'/'.$fname;
 4141:         }
 4142:     }
 4143:     if ($subdir eq 'scantron') {
 4144:         $fname = 'scantron_orig_'.$fname;
 4145:     } else {
 4146:         $fname="$subdir/$fname";
 4147:     }
 4148:     if ($context eq 'coursedoc') {
 4149: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4150: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4151:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4152:             return &finishuserfileupload($docuname,$docudom,
 4153: 					 $formname,$fname,$parser,$allfiles,
 4154: 					 $codebase,$thumbwidth,$thumbheight,
 4155:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4156:         } else {
 4157:             if ($env{'form.folder'}) {
 4158:                 $fname=$env{'form.folder'}.'/'.$fname;
 4159:             }
 4160:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4161: 				       $fname,$formname,$parser,
 4162: 				       $allfiles,$codebase,$mimetype);
 4163:         }
 4164:     } elsif (defined($destuname)) {
 4165:         my $docuname=$destuname;
 4166:         my $docudom=$destudom;
 4167: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4168: 				     $parser,$allfiles,$codebase,
 4169:                                      $thumbwidth,$thumbheight,
 4170:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4171:     } else {
 4172:         my $docuname=$env{'user.name'};
 4173:         my $docudom=$env{'user.domain'};
 4174:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4175:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4176:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4177:         }
 4178: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4179: 				     $parser,$allfiles,$codebase,
 4180:                                      $thumbwidth,$thumbheight,
 4181:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4182:     }
 4183: }
 4184: 
 4185: sub finishuserfileupload {
 4186:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4187:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4188:     my $path=$docudom.'/'.$docuname.'/';
 4189:     my $filepath=$perlvar{'lonDocRoot'};
 4190:   
 4191:     my ($fnamepath,$file,$fetchthumb);
 4192:     $file=$fname;
 4193:     if ($fname=~m|/|) {
 4194:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4195: 	$path.=$fnamepath.'/';
 4196:     }
 4197:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4198:     my $count;
 4199:     for ($count=4;$count<=$#parts;$count++) {
 4200:         $filepath.="/$parts[$count]";
 4201:         if ((-e $filepath)!=1) {
 4202: 	    mkdir($filepath,0777);
 4203:         }
 4204:     }
 4205: 
 4206: # Save the file
 4207:     {
 4208: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4209: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4210: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4211: 	    return '/adm/notfound.html';
 4212: 	}
 4213:         if ($context eq 'overwrite') {
 4214:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4215:             my $target = $filepath.'/'.$file;
 4216:             if (-e $source) {
 4217:                 my @info = stat($source);
 4218:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4219:                     unless (&File::Copy::move($source,$target)) {
 4220:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4221:                         return "Moving from $source failed";
 4222:                     }
 4223:                 } else {
 4224:                     return "Temporary file: $source had unexpected date/time for last modification";
 4225:                 }
 4226:             } else {
 4227:                 return "Temporary file: $source missing";
 4228:             }
 4229:         } elsif (!print FH ($env{'form.'.$formname})) {
 4230: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4231: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4232: 	    return '/adm/notfound.html';
 4233: 	}
 4234: 	close(FH);
 4235:         if ($resizewidth && $resizeheight) {
 4236:             my $mm = new File::MMagic;
 4237:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4238:             if ($mime_type =~ m{^image/}) {
 4239: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4240:             }  
 4241: 	}
 4242:     }
 4243:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4244:         if (ref($mimetype)) {
 4245:             if ($$mimetype eq '') {
 4246:                 my $mm = new File::MMagic;
 4247:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4248:                 $$mimetype = $type;
 4249:             }
 4250:         }
 4251:     }
 4252:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4253:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4254:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4255:                                                        $allfiles,$codebase);
 4256:             unless ($parse_result eq 'ok') {
 4257:                 &logthis('Failed to parse '.$filepath.$file.
 4258: 	   	         ' for embedded media: '.$parse_result); 
 4259:             }
 4260:         }
 4261:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4262:         my $format = $env{'form.scantron_format'};
 4263:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4264:     }
 4265:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4266:         my $input = $filepath.'/'.$file;
 4267:         my $output = $filepath.'/'.'tn-'.$file;
 4268:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4269:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4270:         system({$args[0]} @args);
 4271:         if (-e $filepath.'/'.'tn-'.$file) {
 4272:             $fetchthumb  = 1; 
 4273:         }
 4274:     }
 4275:  
 4276: # Notify homeserver to grep it
 4277: #
 4278:     my $docuhome=&homeserver($docuname,$docudom);	
 4279:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4280:     if ($fetchresult eq 'ok') {
 4281:         if ($fetchthumb) {
 4282:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4283:             if ($thumbresult ne 'ok') {
 4284:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4285:                          $docuhome.': '.$thumbresult);
 4286:             }
 4287:         }
 4288: #
 4289: # Return the URL to it
 4290:         return '/uploaded/'.$path.$file;
 4291:     } else {
 4292:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4293: 		 ': '.$fetchresult);
 4294:         return '/adm/notfound.html';
 4295:     }
 4296: }
 4297: 
 4298: sub extract_embedded_items {
 4299:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4300:     my @state = ();
 4301:     my (%lastids,%related,%shockwave,%flashvars);
 4302:     my %javafiles = (
 4303:                       codebase => '',
 4304:                       code => '',
 4305:                       archive => ''
 4306:                     );
 4307:     my %mediafiles = (
 4308:                       src => '',
 4309:                       movie => '',
 4310:                      );
 4311:     my $p;
 4312:     if ($content) {
 4313:         $p = HTML::LCParser->new($content);
 4314:     } else {
 4315:         $p = HTML::LCParser->new($fullpath);
 4316:     }
 4317:     while (my $t=$p->get_token()) {
 4318: 	if ($t->[0] eq 'S') {
 4319: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4320: 	    push(@state, $tagname);
 4321:             if (lc($tagname) eq 'allow') {
 4322:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4323:             }
 4324: 	    if (lc($tagname) eq 'img') {
 4325: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4326: 	    }
 4327: 	    if (lc($tagname) eq 'a') {
 4328:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4329:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4330:                 }
 4331: 	    }
 4332:             if (lc($tagname) eq 'script') {
 4333:                 my $src;
 4334:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4335:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4336:                 } else {
 4337:                     if ($attr->{'src'} ne '') {
 4338:                         $src = $attr->{'src'};
 4339:                         &add_filetype($allfiles,$src,'src');
 4340:                     }
 4341:                 }
 4342:                 my $text = $p->get_trimmed_text();
 4343:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4344:                     my @swfargs = split(/,/,$1);
 4345:                     foreach my $item (@swfargs) {
 4346:                         $item =~ s/["']//g;
 4347:                         $item =~ s/^\s+//;
 4348:                         $item =~ s/\s+$//;
 4349:                     }
 4350:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4351:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4352:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4353:                         } else {
 4354:                             $related{$swfargs[0]} = [$swfargs[2]];
 4355:                         }
 4356:                     }
 4357:                 }
 4358:             }
 4359:             if (lc($tagname) eq 'link') {
 4360:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4361:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4362:                 }
 4363:             }
 4364: 	    if (lc($tagname) eq 'object' ||
 4365: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4366: 		foreach my $item (keys(%javafiles)) {
 4367: 		    $javafiles{$item} = '';
 4368: 		}
 4369:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4370:                     $lastids{lc($tagname)} = $attr->{'id'};
 4371:                 }
 4372: 	    }
 4373: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4374: 		my $name = lc($attr->{'name'});
 4375: 		foreach my $item (keys(%javafiles)) {
 4376: 		    if ($name eq $item) {
 4377: 			$javafiles{$item} = $attr->{'value'};
 4378: 			last;
 4379: 		    }
 4380: 		}
 4381:                 my $pathfrom;
 4382: 		foreach my $item (keys(%mediafiles)) {
 4383: 		    if ($name eq $item) {
 4384:                         $pathfrom = $attr->{'value'};
 4385:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4386: 			&add_filetype($allfiles,$pathfrom,$name);
 4387: 			last;
 4388: 		    }
 4389: 		}
 4390:                 if ($name eq 'flashvars') {
 4391:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4392:                 }
 4393:                 if ($pathfrom ne '') {
 4394:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4395:                                          $pathfrom);
 4396:                 }
 4397: 	    }
 4398: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4399: 		foreach my $item (keys(%javafiles)) {
 4400: 		    if ($attr->{$item}) {
 4401: 			$javafiles{$item} = $attr->{$item};
 4402: 			last;
 4403: 		    }
 4404: 		}
 4405: 		foreach my $item (keys(%mediafiles)) {
 4406: 		    if ($attr->{$item}) {
 4407: 			&add_filetype($allfiles,$attr->{$item},$item);
 4408: 			last;
 4409: 		    }
 4410: 		}
 4411:                 if (lc($tagname) eq 'embed') {
 4412:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4413:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4414:                                              $attr->{'src'});
 4415:                     }
 4416:                 }
 4417: 	    }
 4418:             if (lc($tagname) eq 'iframe') {
 4419:                 my $src = $attr->{'src'} ;
 4420:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4421:                     &add_filetype($allfiles,$src,'src');
 4422:                 } elsif ($src =~ m{^/}) {
 4423:                     if ($env{'request.course.id'}) {
 4424:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4425:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4426:                         my $url = &hreflocation('',$fullpath);
 4427:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4428:                             my $relpath = $1;
 4429:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4430:                                 &add_filetype($allfiles,$1,'src');
 4431:                             }
 4432:                         }
 4433:                     }
 4434:                 }
 4435:             }
 4436:             if ($t->[4] =~ m{/>$}) {
 4437:                 pop(@state);
 4438:             }
 4439: 	} elsif ($t->[0] eq 'E') {
 4440: 	    my ($tagname) = ($t->[1]);
 4441: 	    if ($javafiles{'codebase'} ne '') {
 4442: 		$javafiles{'codebase'} .= '/';
 4443: 	    }  
 4444: 	    if (lc($tagname) eq 'applet' ||
 4445: 		lc($tagname) eq 'object' ||
 4446: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4447: 		) {
 4448: 		foreach my $item (keys(%javafiles)) {
 4449: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4450: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4451: 			&add_filetype($allfiles,$file,$item);
 4452: 		    }
 4453: 		}
 4454: 	    } 
 4455: 	    pop @state;
 4456: 	}
 4457:     }
 4458:     foreach my $id (sort(keys(%flashvars))) {
 4459:         if ($shockwave{$id} ne '') {
 4460:             my @pairs = split(/\&/,$flashvars{$id});
 4461:             foreach my $pair (@pairs) {
 4462:                 my ($key,$value) = split(/\=/,$pair);
 4463:                 if ($key eq 'thumb') {
 4464:                     &add_filetype($allfiles,$value,$key);
 4465:                 } elsif ($key eq 'content') {
 4466:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4467:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4468:                     if ($ext ne '') {
 4469:                         &add_filetype($allfiles,$path.$value,$ext);
 4470:                     }
 4471:                 }
 4472:             }
 4473:         }
 4474:     }
 4475:     return 'ok';
 4476: }
 4477: 
 4478: sub add_filetype {
 4479:     my ($allfiles,$file,$type)=@_;
 4480:     if (exists($allfiles->{$file})) {
 4481: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4482: 	    push(@{$allfiles->{$file}}, &escape($type));
 4483: 	}
 4484:     } else {
 4485: 	@{$allfiles->{$file}} = (&escape($type));
 4486:     }
 4487: }
 4488: 
 4489: sub embedded_dependency {
 4490:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4491:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4492:         if (($identifier ne '') &&
 4493:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4494:             ($pathfrom ne '')) {
 4495:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4496:             foreach my $dep (@{$related->{$identifier}}) {
 4497:                 &add_filetype($allfiles,$path.$dep,'object');
 4498:             }
 4499:         }
 4500:     }
 4501:     return;
 4502: }
 4503: 
 4504: sub bubblesheet_converter {
 4505:     my ($cdom,$fullpath,$config,$format) = @_;
 4506:     if ((&domain($cdom) ne '') &&
 4507:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4508:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4509:         my (%csvcols,%csvoptions);
 4510:         if (ref($config->{'fields'}) eq 'HASH') {  
 4511:             %csvcols = %{$config->{'fields'}};
 4512:         }
 4513:         if (ref($config->{'options'}) eq 'HASH') {
 4514:             %csvoptions = %{$config->{'options'}};
 4515:         }
 4516:         my %csvbynum = reverse(%csvcols);
 4517:         my %scantronconf = &get_scantron_config($format,$cdom);
 4518:         if (keys(%scantronconf)) {
 4519:             my %bynum = (
 4520:                           $scantronconf{CODEstart} => 'CODEstart',
 4521:                           $scantronconf{IDstart}   => 'IDstart',
 4522:                           $scantronconf{PaperID}   => 'PaperID',
 4523:                           $scantronconf{FirstName} => 'FirstName',
 4524:                           $scantronconf{LastName}  => 'LastName',
 4525:                           $scantronconf{Qstart}    => 'Qstart',
 4526:                         );
 4527:             my @ordered;
 4528:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4529:                 push(@ordered,$bynum{$item});
 4530:             }
 4531:             my %mapstart = (
 4532:                               CODEstart => 'CODE',
 4533:                               IDstart   => 'ID',
 4534:                               PaperID   => 'PaperID',
 4535:                               FirstName => 'FirstName',
 4536:                               LastName  => 'LastName',
 4537:                               Qstart    => 'FirstQuestion',
 4538:                            );
 4539:             my %maplength = (
 4540:                               CODEstart => 'CODElength',
 4541:                               IDstart   => 'IDlength',
 4542:                               PaperID   => 'PaperIDlength',
 4543:                               FirstName => 'FirstNamelength',
 4544:                               LastName  => 'LastNamelength',
 4545:             );
 4546:             if (open(my $fh,'<',$fullpath)) {
 4547:                 my $output;
 4548:                 my %lettdig = &letter_to_digits();
 4549:                 my %diglett = reverse(%lettdig);
 4550:                 my $numletts = scalar(keys(%lettdig));
 4551:                 my $num = 0;
 4552:                 while (my $line=<$fh>) {
 4553:                     $num ++;
 4554:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4555:                     $line =~ s{[\r\n]+$}{};
 4556:                     my %found;
 4557:                     my @values = split(/,/,$line);
 4558:                     my ($qstart,$record);
 4559:                     for (my $i=0; $i<@values; $i++) {
 4560:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4561:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4562:                             if ($values[$i] eq '') {
 4563:                                 $values[$i] = $scantronconf{'Qoff'};
 4564:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4565:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4566:                                     $values[$i] = $lettdig{uc($values[$i])};
 4567:                                 }
 4568:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4569:                                 if ($values[$i] =~ /^[0-9]$/) {
 4570:                                     $values[$i] = $diglett{$values[$i]};
 4571:                                 }
 4572:                             } else {
 4573:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4574:                                     my $digit;
 4575:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4576:                                         $digit = $lettdig{uc($values[$i])}-1;
 4577:                                         if ($values[$i] eq 'J') {
 4578:                                             $digit += $numletts;
 4579:                                         }
 4580:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4581:                                         $digit = $values[$i]-1;
 4582:                                         if ($values[$i] eq '0') {
 4583:                                             $digit += $numletts;
 4584:                                         }
 4585:                                     }
 4586:                                     my $qval='';
 4587:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4588:                                         if ($j == $digit) {
 4589:                                             $qval .= $scantronconf{'Qon'};
 4590:                                         } else {
 4591:                                             $qval .= $scantronconf{'Qoff'};
 4592:                                         }
 4593:                                     }
 4594:                                     $values[$i] = $qval;
 4595:                                 }
 4596:                             }
 4597:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4598:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4599:                             }
 4600:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4601:                             if ($numblank > 0) {
 4602:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4603:                             }
 4604:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4605:                                 $qstart = $i;
 4606:                                 $found{$csvbynum{$i}} = $values[$i];
 4607:                             } else {
 4608:                                 $found{'FirstQuestion'} .= $values[$i];
 4609:                             }
 4610:                         } elsif (exists($csvbynum{$i})) {
 4611:                             if ($csvoptions{'rem'}) {
 4612:                                 $values[$i] =~ s/^\s+//;
 4613:                             }
 4614:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4615:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4616:                                     $values[$i] = '0'.$values[$i];
 4617:                                 }
 4618:                             }
 4619:                             $found{$csvbynum{$i}} = $values[$i];
 4620:                         }
 4621:                     }
 4622:                     foreach my $item (@ordered) {
 4623:                         my $currlength = 1+length($record);
 4624:                         my $numspaces = $scantronconf{$item} - $currlength;
 4625:                         if ($numspaces > 0) {
 4626:                             $record .= (' ' x $numspaces);
 4627:                         }
 4628:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4629:                             unless ($item eq 'Qstart') {
 4630:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4631:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4632:                                 }
 4633:                             }
 4634:                             $record .= $found{$mapstart{$item}};
 4635:                         }
 4636:                     }
 4637:                     $output .= "$record\n";
 4638:                 }
 4639:                 close($fh);
 4640:                 if ($output) {
 4641:                     if (open(my $fh,'>',$fullpath)) {
 4642:                         print $fh $output;
 4643:                         close($fh);
 4644:                     }
 4645:                 }
 4646:             }
 4647:         }
 4648:         return;
 4649:     }
 4650: }
 4651: 
 4652: sub letter_to_digits {
 4653:     my %lettdig = (
 4654:                     A => 1,
 4655:                     B => 2,
 4656:                     C => 3,
 4657:                     D => 4,
 4658:                     E => 5,
 4659:                     F => 6,
 4660:                     G => 7,
 4661:                     H => 8,
 4662:                     I => 9,
 4663:                     J => 0,
 4664:                   );
 4665:     return %lettdig;
 4666: }
 4667: 
 4668: sub get_scantron_config {
 4669:     my ($which,$cdom) = @_;
 4670:     my @lines = &get_scantronformat_file($cdom);
 4671:     my %config;
 4672:     #FIXME probably should move to XML it has already gotten a bit much now
 4673:     foreach my $line (@lines) {
 4674:         my ($name,$descrip)=split(/:/,$line);
 4675:         if ($name ne $which ) { next; }
 4676:         chomp($line);
 4677:         my @config=split(/:/,$line);
 4678:         $config{'name'}=$config[0];
 4679:         $config{'description'}=$config[1];
 4680:         $config{'CODElocation'}=$config[2];
 4681:         $config{'CODEstart'}=$config[3];
 4682:         $config{'CODElength'}=$config[4];
 4683:         $config{'IDstart'}=$config[5];
 4684:         $config{'IDlength'}=$config[6];
 4685:         $config{'Qstart'}=$config[7];
 4686:         $config{'Qlength'}=$config[8];
 4687:         $config{'Qoff'}=$config[9];
 4688:         $config{'Qon'}=$config[10];
 4689:         $config{'PaperID'}=$config[11];
 4690:         $config{'PaperIDlength'}=$config[12];
 4691:         $config{'FirstName'}=$config[13];
 4692:         $config{'FirstNamelength'}=$config[14];
 4693:         $config{'LastName'}=$config[15];
 4694:         $config{'LastNamelength'}=$config[16];
 4695:         $config{'BubblesPerRow'}=$config[17];
 4696:         last;
 4697:     }
 4698:     return %config;
 4699: }
 4700: 
 4701: sub get_scantronformat_file {
 4702:     my ($cdom) = @_;
 4703:     if ($cdom eq '') {
 4704:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4705:     }
 4706:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4707:     my $gottab = 0;
 4708:     my @lines;
 4709:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4710:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4711:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4712:             if ($formatfile ne '-1') {
 4713:                 @lines = split("\n",$formatfile,-1);
 4714:                 $gottab = 1;
 4715:             }
 4716:         }
 4717:     }
 4718:     if (!$gottab) {
 4719:         my $confname = $cdom.'-domainconfig';
 4720:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4721:         my $formatfile = &getfile($default);
 4722:         if ($formatfile ne '-1') {
 4723:             @lines = split("\n",$formatfile,-1);
 4724:             $gottab = 1;
 4725:         }
 4726:     }
 4727:     if (!$gottab) {
 4728:         my @domains = &current_machine_domains();
 4729:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4730:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4731:                 @lines = <$fh>;
 4732:                 close($fh);
 4733:             }
 4734:         } else {
 4735:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4736:                 @lines = <$fh>;
 4737:                 close($fh);
 4738:             }
 4739:         }
 4740:     }
 4741:     return @lines;
 4742: }
 4743: 
 4744: sub removeuploadedurl {
 4745:     my ($url)=@_;	
 4746:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4747:     return &removeuserfile($uname,$udom,$fname);
 4748: }
 4749: 
 4750: sub removeuserfile {
 4751:     my ($docuname,$docudom,$fname)=@_;
 4752:     my $home=&homeserver($docuname,$docudom);    
 4753:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4754:     if ($result eq 'ok') {	
 4755:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4756:             my $metafile = $fname.'.meta';
 4757:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4758: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4759:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4760:             my $sqlresult = 
 4761:                 &update_portfolio_table($docuname,$docudom,$file,
 4762:                                         'portfolio_metadata',$group,
 4763:                                         'delete');
 4764:         }
 4765:     }
 4766:     return $result;
 4767: }
 4768: 
 4769: sub mkdiruserfile {
 4770:     my ($docuname,$docudom,$dir)=@_;
 4771:     my $home=&homeserver($docuname,$docudom);
 4772:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4773: }
 4774: 
 4775: sub renameuserfile {
 4776:     my ($docuname,$docudom,$old,$new)=@_;
 4777:     my $home=&homeserver($docuname,$docudom);
 4778:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4779:                         &escape("$old").':'.&escape("$new"),$home);
 4780:     if ($result eq 'ok') {
 4781:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4782:             my $oldmeta = $old.'.meta';
 4783:             my $newmeta = $new.'.meta';
 4784:             my $metaresult = 
 4785:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4786: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4787:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4788:             my $sqlresult = 
 4789:                 &update_portfolio_table($docuname,$docudom,$file,
 4790:                                         'portfolio_metadata',$group,
 4791:                                         'delete');
 4792:         }
 4793:     }
 4794:     return $result;
 4795: }
 4796: 
 4797: # ------------------------------------------------------------------------- Log
 4798: 
 4799: sub log {
 4800:     my ($dom,$nam,$hom,$what)=@_;
 4801:     return critical("log:$dom:$nam:$what",$hom);
 4802: }
 4803: 
 4804: # ------------------------------------------------------------------ Course Log
 4805: #
 4806: # This routine flushes several buffers of non-mission-critical nature
 4807: #
 4808: 
 4809: sub flushcourselogs {
 4810:     &logthis('Flushing log buffers');
 4811: #
 4812: # course logs
 4813: # This is a log of all transactions in a course, which can be used
 4814: # for data mining purposes
 4815: #
 4816: # It also collects the courseid database, which lists last transaction
 4817: # times and course titles for all courseids
 4818: #
 4819:     my %courseidbuffer=();
 4820:     foreach my $crsid (keys(%courselogs)) {
 4821:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4822: 		          &escape($courselogs{$crsid}),
 4823: 		          $coursehombuf{$crsid}) eq 'ok') {
 4824: 	    delete $courselogs{$crsid};
 4825:         } else {
 4826:             &logthis('Failed to flush log buffer for '.$crsid);
 4827:             if (length($courselogs{$crsid})>40000) {
 4828:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4829:                         " exceeded maximum size, deleting.</font>");
 4830:                delete $courselogs{$crsid};
 4831:             }
 4832:         }
 4833:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4834:             'description' => $coursedescrbuf{$crsid},
 4835:             'inst_code'    => $courseinstcodebuf{$crsid},
 4836:             'type'        => $coursetypebuf{$crsid},
 4837:             'owner'       => $courseownerbuf{$crsid},
 4838:         };
 4839:     }
 4840: #
 4841: # Write course id database (reverse lookup) to homeserver of courses 
 4842: # Is used in pickcourse
 4843: #
 4844:     foreach my $crs_home (keys(%courseidbuffer)) {
 4845:         my $response = &courseidput(&host_domain($crs_home),
 4846:                                     $courseidbuffer{$crs_home},
 4847:                                     $crs_home,'timeonly');
 4848:     }
 4849: #
 4850: # File accesses
 4851: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4852: #
 4853:     foreach my $entry (keys(%accesshash)) {
 4854:         if ($entry =~ /___count$/) {
 4855:             my ($dom,$name);
 4856:             ($dom,$name,undef)=
 4857: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4858:             if (! defined($dom) || $dom eq '' || 
 4859:                 ! defined($name) || $name eq '') {
 4860:                 my $cid = $env{'request.course.id'};
 4861:                 $dom  = $env{'request.'.$cid.'.domain'};
 4862:                 $name = $env{'request.'.$cid.'.num'};
 4863:             }
 4864:             my $value = $accesshash{$entry};
 4865:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4866:             my %temphash=($url => $value);
 4867:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4868:             if ($result eq 'ok') {
 4869:                 delete $accesshash{$entry};
 4870:             }
 4871:         } else {
 4872:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4873:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4874:             my %temphash=($entry => $accesshash{$entry});
 4875:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4876:                 delete $accesshash{$entry};
 4877:             }
 4878:         }
 4879:     }
 4880: #
 4881: # Roles
 4882: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4883: #
 4884:     foreach my $entry (keys(%userrolehash)) {
 4885:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4886: 	    split(/\:/,$entry);
 4887:         if (&Apache::lonnet::put('nohist_userroles',
 4888:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4889:                 $rudom,$runame) eq 'ok') {
 4890: 	    delete $userrolehash{$entry};
 4891:         }
 4892:     }
 4893: #
 4894: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4895: #
 4896:     my %domrolebuffer = ();
 4897:     foreach my $entry (keys(%domainrolehash)) {
 4898:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4899:         if ($domrolebuffer{$rudom}) {
 4900:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4901:                       '='.&escape($domainrolehash{$entry});
 4902:         } else {
 4903:             $domrolebuffer{$rudom}.=&escape($entry).
 4904:                       '='.&escape($domainrolehash{$entry});
 4905:         }
 4906:         delete $domainrolehash{$entry};
 4907:     }
 4908:     foreach my $dom (keys(%domrolebuffer)) {
 4909: 	my %servers;
 4910: 	if (defined(&domain($dom,'primary'))) {
 4911: 	    my $primary=&domain($dom,'primary');
 4912: 	    my $hostname=&hostname($primary);
 4913: 	    $servers{$primary} = $hostname;
 4914: 	} else { 
 4915: 	    %servers = &get_servers($dom,'library');
 4916: 	}
 4917: 	foreach my $tryserver (keys(%servers)) {
 4918: 	    if (&reply('domroleput:'.$dom.':'.
 4919: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4920: 		last;
 4921: 	    } else {  
 4922: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4923: 	    }
 4924:         }
 4925:     }
 4926:     $dumpcount++;
 4927: }
 4928: 
 4929: sub courselog {
 4930:     my $what=shift;
 4931:     $what=time.':'.$what;
 4932:     unless ($env{'request.course.id'}) { return ''; }
 4933:     $coursedombuf{$env{'request.course.id'}}=
 4934:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4935:     $coursenumbuf{$env{'request.course.id'}}=
 4936:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4937:     $coursehombuf{$env{'request.course.id'}}=
 4938:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4939:     $coursedescrbuf{$env{'request.course.id'}}=
 4940:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4941:     $courseinstcodebuf{$env{'request.course.id'}}=
 4942:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4943:     $courseownerbuf{$env{'request.course.id'}}=
 4944:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4945:     $coursetypebuf{$env{'request.course.id'}}=
 4946:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4947:     if (defined $courselogs{$env{'request.course.id'}}) {
 4948: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4949:     } else {
 4950: 	$courselogs{$env{'request.course.id'}}.=$what;
 4951:     }
 4952:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4953: 	&flushcourselogs();
 4954:     }
 4955: }
 4956: 
 4957: sub courseacclog {
 4958:     my $fnsymb=shift;
 4959:     unless ($env{'request.course.id'}) { return ''; }
 4960:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4961:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4962:         $what.=':POST';
 4963:         # FIXME: Probably ought to escape things....
 4964: 	foreach my $key (keys(%env)) {
 4965:             if ($key=~/^form\.(.*)/) {
 4966:                 my $formitem = $1;
 4967:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4968:                     $what.=':'.$formitem.'='.$env{$key};
 4969:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4970:                     $what.=':'.$formitem.'='.$env{$key};
 4971:                 }
 4972:             }
 4973:         }
 4974:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4975:         # FIXME: We should not be depending on a form parameter that someone
 4976:         # editing lonsearchcat.pm might change in the future.
 4977:         if ($env{'form.phase'} eq 'course_search') {
 4978:             $what.= ':POST';
 4979:             # FIXME: Probably ought to escape things....
 4980:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4981:                                  'crsdiscuss') {
 4982:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4983:             }
 4984:         }
 4985:     }
 4986:     &courselog($what);
 4987: }
 4988: 
 4989: sub countacc {
 4990:     my $url=&declutter(shift);
 4991:     return if (! defined($url) || $url eq '');
 4992:     unless ($env{'request.course.id'}) { return ''; }
 4993: #
 4994: # Mark that this url was used in this course
 4995: #
 4996:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4997: #
 4998: # Increase the access count for this resource in this child process
 4999: #
 5000:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5001:     $accesshash{$key}++;
 5002: }
 5003: 
 5004: sub linklog {
 5005:     my ($from,$to)=@_;
 5006:     $from=&declutter($from);
 5007:     $to=&declutter($to);
 5008:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5009:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5010: }
 5011: 
 5012: sub statslog {
 5013:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5014:     if ($users<2) { return; }
 5015:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5016:             'course'       => $env{'request.course.id'},
 5017:             'sections'     => '"all"',
 5018:             'num_students' => $users,
 5019:             'part'         => $part,
 5020:             'symb'         => $symb,
 5021:             'mean_tries'   => $av_attempts,
 5022:             'deg_of_diff'  => $degdiff});
 5023:     foreach my $key (keys(%dynstore)) {
 5024:         $accesshash{$key}=$dynstore{$key};
 5025:     }
 5026: }
 5027:   
 5028: sub userrolelog {
 5029:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5030:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5031:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5032:        $userrolehash
 5033:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5034:                     =$tend.':'.$tstart;
 5035:     }
 5036:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5037:        $userrolehash
 5038:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5039:                     =$tend.':'.$tstart;
 5040:     }
 5041:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5042:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5043:        $domainrolehash
 5044:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5045:                     = $tend.':'.$tstart;
 5046:     }
 5047: }
 5048: 
 5049: sub courserolelog {
 5050:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5051:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5052:         my $cdom = $1;
 5053:         my $cnum = $2;
 5054:         my $sec = $3;
 5055:         my $namespace = 'rolelog';
 5056:         my %storehash = (
 5057:                            role    => $trole,
 5058:                            start   => $tstart,
 5059:                            end     => $tend,
 5060:                            selfenroll => $selfenroll,
 5061:                            context    => $context,
 5062:                         );
 5063:         if ($trole eq 'gr') {
 5064:             $namespace = 'groupslog';
 5065:             $storehash{'group'} = $sec;
 5066:         } else {
 5067:             $storehash{'section'} = $sec;
 5068:         }
 5069:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5070:                    $domain,$cnum,$cdom);
 5071:         if (($trole ne 'st') || ($sec ne '')) {
 5072:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5073:         }
 5074:     }
 5075:     return;
 5076: }
 5077: 
 5078: sub domainrolelog {
 5079:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5080:     if ($area =~ m{^/($match_domain)/$}) {
 5081:         my $cdom = $1;
 5082:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5083:         my $namespace = 'rolelog';
 5084:         my %storehash = (
 5085:                            role    => $trole,
 5086:                            start   => $tstart,
 5087:                            end     => $tend,
 5088:                            context => $context,
 5089:                         );
 5090:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5091:                    $domain,$domconfiguser,$cdom);
 5092:     }
 5093:     return;
 5094: 
 5095: }
 5096: 
 5097: sub coauthorrolelog {
 5098:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5099:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5100:         my $audom = $1;
 5101:         my $auname = $2;
 5102:         my $namespace = 'rolelog';
 5103:         my %storehash = (
 5104:                            role    => $trole,
 5105:                            start   => $tstart,
 5106:                            end     => $tend,
 5107:                            context => $context,
 5108:                         );
 5109:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5110:                    $domain,$auname,$audom);
 5111:     }
 5112:     return;
 5113: }
 5114: 
 5115: sub get_course_adv_roles {
 5116:     my ($cid,$codes) = @_;
 5117:     $cid=$env{'request.course.id'} unless (defined($cid));
 5118:     my %coursehash=&coursedescription($cid);
 5119:     my $crstype = &Apache::loncommon::course_type($cid);
 5120:     my %nothide=();
 5121:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5122:         if ($user !~ /:/) {
 5123: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5124:         } else {
 5125:             $nothide{$user}=1;
 5126:         }
 5127:     }
 5128:     my @possdoms = ($coursehash{'domain'});
 5129:     if ($coursehash{'checkforpriv'}) {
 5130:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5131:     }
 5132:     my %returnhash=();
 5133:     my %dumphash=
 5134:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5135:     my $now=time;
 5136:     my %privileged;
 5137:     foreach my $entry (keys(%dumphash)) {
 5138: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5139:         if (($tstart) && ($tstart<0)) { next; }
 5140:         if (($tend) && ($tend<$now)) { next; }
 5141:         if (($tstart) && ($now<$tstart)) { next; }
 5142:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5143: 	if ($username eq '' || $domain eq '') { next; }
 5144:         if ((&privileged($username,$domain,\@possdoms)) &&
 5145:             (!$nothide{$username.':'.$domain})) { next; }
 5146: 	if ($role eq 'cr') { next; }
 5147:         if ($codes) {
 5148:             if ($section) { $role .= ':'.$section; }
 5149:             if ($returnhash{$role}) {
 5150:                 $returnhash{$role}.=','.$username.':'.$domain;
 5151:             } else {
 5152:                 $returnhash{$role}=$username.':'.$domain;
 5153:             }
 5154:         } else {
 5155:             my $key=&plaintext($role,$crstype);
 5156:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5157:             if ($returnhash{$key}) {
 5158: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5159:             } else {
 5160:                 $returnhash{$key}=$username.':'.$domain;
 5161:             }
 5162:         }
 5163:     }
 5164:     return %returnhash;
 5165: }
 5166: 
 5167: sub get_my_roles {
 5168:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5169:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5170:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5171:     my (%dumphash,%nothide);
 5172:     if ($context eq 'userroles') {
 5173:         %dumphash = &dump('roles',$udom,$uname);
 5174:     } else {
 5175:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5176:         if ($hidepriv) {
 5177:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5178:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5179:                 if ($user !~ /:/) {
 5180:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5181:                 } else {
 5182:                     $nothide{$user} = 1;
 5183:                 }
 5184:             }
 5185:         }
 5186:     }
 5187:     my %returnhash=();
 5188:     my $now=time;
 5189:     my %privileged;
 5190:     foreach my $entry (keys(%dumphash)) {
 5191:         my ($role,$tend,$tstart);
 5192:         if ($context eq 'userroles') {
 5193:             next if ($entry =~ /^rolesdef/);
 5194: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5195:         } else {
 5196:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5197:         }
 5198:         if (($tstart) && ($tstart<0)) { next; }
 5199:         my $status = 'active';
 5200:         if (($tend) && ($tend<=$now)) {
 5201:             $status = 'previous';
 5202:         } 
 5203:         if (($tstart) && ($now<$tstart)) {
 5204:             $status = 'future';
 5205:         }
 5206:         if (ref($types) eq 'ARRAY') {
 5207:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5208:                 next;
 5209:             } 
 5210:         } else {
 5211:             if ($status ne 'active') {
 5212:                 next;
 5213:             }
 5214:         }
 5215:         my ($rolecode,$username,$domain,$section,$area);
 5216:         if ($context eq 'userroles') {
 5217:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5218:             (undef,$domain,$username,$section) = split(/\//,$area);
 5219:         } else {
 5220:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5221:         }
 5222:         if (ref($roledoms) eq 'ARRAY') {
 5223:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5224:                 next;
 5225:             }
 5226:         }
 5227:         if (ref($roles) eq 'ARRAY') {
 5228:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5229:                 if ($role =~ /^cr\//) {
 5230:                     if (!grep(/^cr$/,@{$roles})) {
 5231:                         next;
 5232:                     }
 5233:                 } elsif ($role =~ /^gr\//) {
 5234:                     if (!grep(/^gr$/,@{$roles})) {
 5235:                         next;
 5236:                     }
 5237:                 } else {
 5238:                     next;
 5239:                 }
 5240:             }
 5241:         }
 5242:         if ($hidepriv) {
 5243:             my @privroles = ('dc','su');
 5244:             if ($context eq 'userroles') {
 5245:                 next if (grep(/^\Q$role\E$/,@privroles));
 5246:             } else {
 5247:                 my $possdoms = [$domain];
 5248:                 if (ref($roledoms) eq 'ARRAY') {
 5249:                    push(@{$possdoms},@{$roledoms}); 
 5250:                 }
 5251:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5252:                     if (!$nothide{$username.':'.$domain}) {
 5253:                         next;
 5254:                     }
 5255:                 }
 5256:             }
 5257:         }
 5258:         if ($withsec) {
 5259:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5260:                 $tstart.':'.$tend;
 5261:         } else {
 5262:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5263:         }
 5264:     }
 5265:     return %returnhash;
 5266: }
 5267: 
 5268: sub get_all_adhocroles {
 5269:     my ($dom) = @_;
 5270:     my @roles_by_num = ();
 5271:     my %domdefaults = &get_domain_defaults($dom);
 5272:     my (%description,%access_in_dom,%access_info);
 5273:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5274:         my $count = 0;
 5275:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5276:         my %ordered;
 5277:         foreach my $role (sort(keys(%domcurrent))) {
 5278:             my ($order,$desc,$access_in_dom);
 5279:             if (ref($domcurrent{$role}) eq 'HASH') {
 5280:                 $order = $domcurrent{$role}{'order'};
 5281:                 $desc = $domcurrent{$role}{'desc'};
 5282:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5283:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5284:             }
 5285:             if ($order eq '') {
 5286:                 $order = $count;
 5287:             }
 5288:             $ordered{$order} = $role;
 5289:             if ($desc ne '') {
 5290:                 $description{$role} = $desc;
 5291:             } else {
 5292:                 $description{$role}= $role;
 5293:             }
 5294:             $count++;
 5295:         }
 5296:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5297:             push(@roles_by_num,$ordered{$item});
 5298:         }
 5299:     }
 5300:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5301: }
 5302: 
 5303: sub get_my_adhocroles {
 5304:     my ($cid,$checkreg) = @_;
 5305:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5306:     if ($env{'request.course.id'} eq $cid) {
 5307:         $cdom = $env{'course.'.$cid.'.domain'};
 5308:         $cnum = $env{'course.'.$cid.'.num'};
 5309:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5310:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5311:         $cdom = $1;
 5312:         $cnum = $2;
 5313:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5314:                                      $cdom,$cnum);
 5315:     }
 5316:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5317:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5318:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5319:         if ($rosterhash{$user} ne '') {
 5320:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5321:             return ([],{}) if ($type eq 'auto');
 5322:         }
 5323:     }
 5324:     if (($cdom ne '') && ($cnum ne ''))  {
 5325:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5326:             my $then=$env{'user.login.time'};
 5327:             my $update=$env{'user.update.time'};
 5328:             if (!$update) {
 5329:                 $update = $then;
 5330:             }
 5331:             my @liveroles;
 5332:             foreach my $role ('dh','da') {
 5333:                 if ($env{"user.role.$role./$cdom/"}) {
 5334:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5335:                     my $limit = $update;
 5336:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5337:                         $limit = $then;
 5338:                     }
 5339:                     my $activerole = 1;
 5340:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5341:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5342:                     if ($activerole) {
 5343:                         push(@liveroles,$role);
 5344:                     }
 5345:                 }
 5346:             }
 5347:             if (@liveroles) {
 5348:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5349:                     my ($accessref,$accessinfo,%access_in_dom);
 5350:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5351:                     if (ref($roles_by_num) eq 'ARRAY') {
 5352:                         if (@{$roles_by_num}) {
 5353:                             my %settings;
 5354:                             if ($env{'request.course.id'} eq $cid) {
 5355:                                 foreach my $envkey (keys(%env)) {
 5356:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5357:                                         $settings{$1} = $env{$envkey};
 5358:                                     }
 5359:                                 }
 5360:                             } else {
 5361:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5362:                             }
 5363:                             my %setincrs;
 5364:                             if ($settings{'internal.adhocaccess'}) {
 5365:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5366:                             }
 5367:                             my @statuses;
 5368:                             if ($env{'environment.inststatus'}) {
 5369:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5370:                             }
 5371:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5372:                             if (ref($accessref) eq 'HASH') {
 5373:                                 %access_in_dom = %{$accessref};
 5374:                             }
 5375:                             foreach my $role (@{$roles_by_num}) {
 5376:                                 my ($curraccess,@okstatus,@personnel);
 5377:                                 if ($setincrs{$role}) {
 5378:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5379:                                     if ($curraccess eq 'status') {
 5380:                                         @okstatus = split(/\&/,$rest);
 5381:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5382:                                         @personnel = split(/\&/,$rest);
 5383:                                     }
 5384:                                 } else {
 5385:                                     $curraccess = $access_in_dom{$role};
 5386:                                     if (ref($accessinfo) eq 'HASH') {
 5387:                                         if ($curraccess eq 'status') {
 5388:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5389:                                                 @okstatus = @{$accessinfo->{$role}};
 5390:                                             }
 5391:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5392:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5393:                                                 @personnel = @{$accessinfo->{$role}};
 5394:                                             }
 5395:                                         }
 5396:                                     }
 5397:                                 }
 5398:                                 if ($curraccess eq 'none') {
 5399:                                     next;
 5400:                                 } elsif ($curraccess eq 'all') {
 5401:                                     push(@possroles,$role);
 5402:                                 } elsif ($curraccess eq 'dh') {
 5403:                                     if (grep(/^dh$/,@liveroles)) {
 5404:                                         push(@possroles,$role);
 5405:                                     } else {
 5406:                                         next;
 5407:                                     }
 5408:                                 } elsif ($curraccess eq 'da') {
 5409:                                     if (grep(/^da$/,@liveroles)) {
 5410:                                         push(@possroles,$role);
 5411:                                     } else {
 5412:                                         next;
 5413:                                     }
 5414:                                 } elsif ($curraccess eq 'status') {
 5415:                                     if (@okstatus) {
 5416:                                         if (!@statuses) {
 5417:                                             if (grep(/^default$/,@okstatus)) {
 5418:                                                 push(@possroles,$role);
 5419:                                             }
 5420:                                         } else {
 5421:                                             foreach my $status (@okstatus) {
 5422:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5423:                                                     push(@possroles,$role);
 5424:                                                     last;
 5425:                                                 }
 5426:                                             }
 5427:                                         }
 5428:                                     }
 5429:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5430:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5431:                                         if ($curraccess eq 'exc') {
 5432:                                             push(@possroles,$role);
 5433:                                         }
 5434:                                     } elsif ($curraccess eq 'inc') {
 5435:                                         push(@possroles,$role);
 5436:                                     }
 5437:                                 }
 5438:                             }
 5439:                         }
 5440:                     }
 5441:                 }
 5442:             }
 5443:         }
 5444:     }
 5445:     unless (ref($description) eq 'HASH') {
 5446:         if (ref($roles_by_num) eq 'ARRAY') {
 5447:             my %desc;
 5448:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5449:             $description = \%desc;
 5450:         } else {
 5451:             $description = {};
 5452:         }
 5453:     }
 5454:     return (\@possroles,$description);
 5455: }
 5456: 
 5457: # ----------------------------------------------------- Frontpage Announcements
 5458: #
 5459: #
 5460: 
 5461: sub postannounce {
 5462:     my ($server,$text)=@_;
 5463:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5464:     unless ($text=~/\w/) { $text=''; }
 5465:     return &reply('setannounce:'.&escape($text),$server);
 5466: }
 5467: 
 5468: sub getannounce {
 5469: 
 5470:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5471: 	my $announcement='';
 5472: 	while (my $line = <$fh>) { $announcement .= $line; }
 5473: 	close($fh);
 5474: 	if ($announcement=~/\w/) { 
 5475: 	    return 
 5476:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5477:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5478: 	} else {
 5479: 	    return '';
 5480: 	}
 5481:     } else {
 5482: 	return '';
 5483:     }
 5484: }
 5485: 
 5486: # ---------------------------------------------------------- Course ID routines
 5487: # Deal with domain's nohist_courseid.db files
 5488: #
 5489: 
 5490: sub courseidput {
 5491:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5492:     return unless (ref($storehash) eq 'HASH');
 5493:     my $outcome;
 5494:     if ($caller eq 'timeonly') {
 5495:         my $cids = '';
 5496:         foreach my $item (keys(%$storehash)) {
 5497:             $cids.=&escape($item).'&';
 5498:         }
 5499:         $cids=~s/\&$//;
 5500:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5501:                           $coursehome);       
 5502:     } else {
 5503:         my $items = '';
 5504:         foreach my $item (keys(%$storehash)) {
 5505:             $items.= &escape($item).'='.
 5506:                      &freeze_escape($$storehash{$item}).'&';
 5507:         }
 5508:         $items=~s/\&$//;
 5509:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5510:                           $coursehome);
 5511:     }
 5512:     if ($outcome eq 'unknown_cmd') {
 5513:         my $what;
 5514:         foreach my $cid (keys(%$storehash)) {
 5515:             $what .= &escape($cid).'=';
 5516:             foreach my $item ('description','inst_code','owner','type') {
 5517:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5518:             }
 5519:             $what =~ s/\:$/&/;
 5520:         }
 5521:         $what =~ s/\&$//;  
 5522:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5523:     } else {
 5524:         return $outcome;
 5525:     }
 5526: }
 5527: 
 5528: sub courseiddump {
 5529:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5530:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5531:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5532:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5533:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5534:     my $as_hash = 1;
 5535:     my %returnhash;
 5536:     if (!$domfilter) { $domfilter=''; }
 5537:     my %libserv = &all_library();
 5538:     foreach my $tryserver (keys(%libserv)) {
 5539:         if ( (  $hostidflag == 1 
 5540: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5541: 	     || (!defined($hostidflag)) ) {
 5542: 
 5543: 	    if (($domfilter eq '') ||
 5544: 		(&host_domain($tryserver) eq $domfilter)) {
 5545:                 my $rep;
 5546:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5547:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5548:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5549:                                 &escape($descfilter), &escape($instcodefilter), 
 5550:                                 &escape($ownerfilter), &escape($coursefilter),
 5551:                                 &escape($typefilter), &escape($regexp_ok), 
 5552:                                 $as_hash, &escape($selfenrollonly), 
 5553:                                 &escape($catfilter), $showhidden, $caller, 
 5554:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5555:                                 &escape($createdbefore), &escape($createdafter), 
 5556:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5557:                                 $reqcrsdom,&escape($reqinstcode))));
 5558:                 } else {
 5559:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5560:                              $sincefilter.':'.&escape($descfilter).':'.
 5561:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5562:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5563:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5564:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5565:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5566:                              &escape($cc_clone).':'.$cloneonly.':'.
 5567:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5568:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5569:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5570:                 }
 5571:                      
 5572:                 my @pairs=split(/\&/,$rep);
 5573:                 foreach my $item (@pairs) {
 5574:                     my ($key,$value)=split(/\=/,$item,2);
 5575:                     $key = &unescape($key);
 5576:                     next if ($key =~ /^error: 2 /);
 5577:                     my $result = &thaw_unescape($value);
 5578:                     if (ref($result) eq 'HASH') {
 5579:                         $returnhash{$key}=$result;
 5580:                     } else {
 5581:                         my @responses = split(/:/,$value);
 5582:                         my @items = ('description','inst_code','owner','type');
 5583:                         for (my $i=0; $i<@responses; $i++) {
 5584:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5585:                         }
 5586:                     }
 5587:                 }
 5588:             }
 5589:         }
 5590:     }
 5591:     return %returnhash;
 5592: }
 5593: 
 5594: sub courselastaccess {
 5595:     my ($cdom,$cnum,$hostidref) = @_;
 5596:     my %returnhash;
 5597:     if ($cdom && $cnum) {
 5598:         my $chome = &homeserver($cnum,$cdom);
 5599:         if ($chome ne 'no_host') {
 5600:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5601:             &extract_lastaccess(\%returnhash,$rep);
 5602:         }
 5603:     } else {
 5604:         if (!$cdom) { $cdom=''; }
 5605:         my %libserv = &all_library();
 5606:         foreach my $tryserver (keys(%libserv)) {
 5607:             if (ref($hostidref) eq 'ARRAY') {
 5608:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5609:             } 
 5610:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5611:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5612:                 &extract_lastaccess(\%returnhash,$rep);
 5613:             }
 5614:         }
 5615:     }
 5616:     return %returnhash;
 5617: }
 5618: 
 5619: sub extract_lastaccess {
 5620:     my ($returnhash,$rep) = @_;
 5621:     if (ref($returnhash) eq 'HASH') {
 5622:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5623:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5624:                  $rep eq '') {
 5625:             my @pairs=split(/\&/,$rep);
 5626:             foreach my $item (@pairs) {
 5627:                 my ($key,$value)=split(/\=/,$item,2);
 5628:                 $key = &unescape($key);
 5629:                 next if ($key =~ /^error: 2 /);
 5630:                 $returnhash->{$key} = &thaw_unescape($value);
 5631:             }
 5632:         }
 5633:     }
 5634:     return;
 5635: }
 5636: 
 5637: # ---------------------------------------------------------- DC e-mail
 5638: 
 5639: sub dcmailput {
 5640:     my ($domain,$msgid,$message,$server)=@_;
 5641:     my $status = &Apache::lonnet::critical(
 5642:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5643:        &escape($message),$server);
 5644:     return $status;
 5645: }
 5646: 
 5647: sub dcmaildump {
 5648:     my ($dom,$startdate,$enddate,$senders) = @_;
 5649:     my %returnhash=();
 5650: 
 5651:     if (defined(&domain($dom,'primary'))) {
 5652:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5653:                                                          &escape($enddate).':';
 5654: 	my @esc_senders=map { &escape($_)} @$senders;
 5655: 	$cmd.=&escape(join('&',@esc_senders));
 5656: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5657:             my ($key,$value) = split(/\=/,$line,2);
 5658:             if (($key) && ($value)) {
 5659:                 $returnhash{&unescape($key)} = &unescape($value);
 5660:             }
 5661:         }
 5662:     }
 5663:     return %returnhash;
 5664: }
 5665: # ---------------------------------------------------------- Domain roles
 5666: 
 5667: sub get_domain_roles {
 5668:     my ($dom,$roles,$startdate,$enddate)=@_;
 5669:     if ((!defined($startdate)) || ($startdate eq '')) {
 5670:         $startdate = '.';
 5671:     }
 5672:     if ((!defined($enddate)) || ($enddate eq '')) {
 5673:         $enddate = '.';
 5674:     }
 5675:     my $rolelist;
 5676:     if (ref($roles) eq 'ARRAY') {
 5677:         $rolelist = join('&',@{$roles});
 5678:     }
 5679:     my %personnel = ();
 5680: 
 5681:     my %servers = &get_servers($dom,'library');
 5682:     foreach my $tryserver (keys(%servers)) {
 5683: 	%{$personnel{$tryserver}}=();
 5684: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5685: 					    &escape($startdate).':'.
 5686: 					    &escape($enddate).':'.
 5687: 					    &escape($rolelist), $tryserver))) {
 5688: 	    my ($key,$value) = split(/\=/,$line,2);
 5689: 	    if (($key) && ($value)) {
 5690: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5691: 	    }
 5692: 	}
 5693:     }
 5694:     return %personnel;
 5695: }
 5696: 
 5697: sub get_active_domroles {
 5698:     my ($dom,$roles) = @_;
 5699:     return () unless (ref($roles) eq 'ARRAY');
 5700:     my $now = time;
 5701:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5702:     my %domroles;
 5703:     foreach my $server (keys(%dompersonnel)) {
 5704:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5705:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5706:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5707:         }
 5708:     }
 5709:     return %domroles;
 5710: }
 5711: 
 5712: # ----------------------------------------------------------- Interval timing 
 5713: 
 5714: {
 5715: # Caches needed for speedup of navmaps
 5716: # We don't want to cache this for very long at all (5 seconds at most)
 5717: # 
 5718: # The user for whom we cache
 5719: my $cachedkey='';
 5720: # The cached times for this user
 5721: my %cachedtimes=();
 5722: # When this was last done
 5723: my $cachedtime='';
 5724: 
 5725: sub load_all_first_access {
 5726:     my ($uname,$udom,$ignorecache)=@_;
 5727:     if (($cachedkey eq $uname.':'.$udom) &&
 5728:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5729:         (!$ignorecache)) {
 5730:         return;
 5731:     }
 5732:     $cachedtime=time;
 5733:     $cachedkey=$uname.':'.$udom;
 5734:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5735: }
 5736: 
 5737: sub get_first_access {
 5738:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5739:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5740:     if ($argsymb) { $symb=$argsymb; }
 5741:     my ($map,$id,$res)=&decode_symb($symb);
 5742:     if ($argmap) { $map = $argmap; }
 5743:     if ($type eq 'course') {
 5744: 	$res='course';
 5745:     } elsif ($type eq 'map') {
 5746: 	$res=&symbread($map);
 5747:     } else {
 5748: 	$res=$symb;
 5749:     }
 5750:     &load_all_first_access($uname,$udom,$ignorecache);
 5751:     return $cachedtimes{"$courseid\0$res"};
 5752: }
 5753: 
 5754: sub set_first_access {
 5755:     my ($type,$interval)=@_;
 5756:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5757:     my ($map,$id,$res)=&decode_symb($symb);
 5758:     if ($type eq 'course') {
 5759: 	$res='course';
 5760:     } elsif ($type eq 'map') {
 5761: 	$res=&symbread($map);
 5762:     } else {
 5763: 	$res=$symb;
 5764:     }
 5765:     $cachedkey='';
 5766:     my $firstaccess=&get_first_access($type,$symb,$map);
 5767:     if ($firstaccess) {
 5768:         &logthis("First access time already set ($firstaccess) when attempting ".
 5769:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5770:                  "in $courseid");
 5771:         return 'already_set';
 5772:     } else {
 5773:         my $start = time;
 5774: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5775:                           $udom,$uname);
 5776:         if ($putres eq 'ok') {
 5777:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5778:                  $udom,$uname); 
 5779:             &appenv(
 5780:                      {
 5781:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5782:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5783:                      }
 5784:                   );
 5785:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5786:                 $cachedtimes{"$courseid\0$res"} = $start;
 5787:             }
 5788:         } elsif ($putres ne 'refused') {
 5789:             &logthis("Result: $putres when attempting to set first access time ".
 5790:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5791:         }
 5792:         return $putres;
 5793:     }
 5794:     return 'already_set';
 5795: }
 5796: }
 5797: 
 5798: # --------------------------------------------- Set Expire Date for Spreadsheet
 5799: 
 5800: sub expirespread {
 5801:     my ($uname,$udom,$stype,$usymb)=@_;
 5802:     my $cid=$env{'request.course.id'}; 
 5803:     if ($cid) {
 5804:        my $now=time;
 5805:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5806:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5807:                             $env{'course.'.$cid.'.num'}.
 5808: 	        	    ':nohist_expirationdates:'.
 5809:                             &escape($key).'='.$now,
 5810:                             $env{'course.'.$cid.'.home'})
 5811:     }
 5812:     return 'ok';
 5813: }
 5814: 
 5815: # ----------------------------------------------------- Devalidate Spreadsheets
 5816: 
 5817: sub devalidate {
 5818:     my ($symb,$uname,$udom)=@_;
 5819:     my $cid=$env{'request.course.id'}; 
 5820:     if ($cid) {
 5821:         # delete the stored spreadsheets for
 5822:         # - the student level sheet of this user in course's homespace
 5823:         # - the assessment level sheet for this resource 
 5824:         #   for this user in user's homespace
 5825: 	# - current conditional state info
 5826: 	my $key=$uname.':'.$udom.':';
 5827:         my $status=
 5828: 	    &del('nohist_calculatedsheets',
 5829: 		 [$key.'studentcalc:'],
 5830: 		 $env{'course.'.$cid.'.domain'},
 5831: 		 $env{'course.'.$cid.'.num'})
 5832: 		.' '.
 5833: 	    &del('nohist_calculatedsheets_'.$cid,
 5834: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5835:         unless ($status eq 'ok ok') {
 5836:            &logthis('Could not devalidate spreadsheet '.
 5837:                     $uname.' at '.$udom.' for '.
 5838: 		    $symb.': '.$status);
 5839:         }
 5840: 	&delenv('user.state.'.$cid);
 5841:     }
 5842: }
 5843: 
 5844: sub get_scalar {
 5845:     my ($string,$end) = @_;
 5846:     my $value;
 5847:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5848: 	$value = $1;
 5849:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5850: 	$value = $1;
 5851:     }
 5852:     return &unescape($value);
 5853: }
 5854: 
 5855: sub array2str {
 5856:   my (@array) = @_;
 5857:   my $result=&arrayref2str(\@array);
 5858:   $result=~s/^__ARRAY_REF__//;
 5859:   $result=~s/__END_ARRAY_REF__$//;
 5860:   return $result;
 5861: }
 5862: 
 5863: sub arrayref2str {
 5864:   my ($arrayref) = @_;
 5865:   my $result='__ARRAY_REF__';
 5866:   foreach my $elem (@$arrayref) {
 5867:     if(ref($elem) eq 'ARRAY') {
 5868:       $result.=&arrayref2str($elem).'&';
 5869:     } elsif(ref($elem) eq 'HASH') {
 5870:       $result.=&hashref2str($elem).'&';
 5871:     } elsif(ref($elem)) {
 5872:       #print("Got a ref of ".(ref($elem))." skipping.");
 5873:     } else {
 5874:       $result.=&escape($elem).'&';
 5875:     }
 5876:   }
 5877:   $result=~s/\&$//;
 5878:   $result .= '__END_ARRAY_REF__';
 5879:   return $result;
 5880: }
 5881: 
 5882: sub hash2str {
 5883:   my (%hash) = @_;
 5884:   my $result=&hashref2str(\%hash);
 5885:   $result=~s/^__HASH_REF__//;
 5886:   $result=~s/__END_HASH_REF__$//;
 5887:   return $result;
 5888: }
 5889: 
 5890: sub hashref2str {
 5891:   my ($hashref)=@_;
 5892:   my $result='__HASH_REF__';
 5893:   foreach my $key (sort(keys(%$hashref))) {
 5894:     if (ref($key) eq 'ARRAY') {
 5895:       $result.=&arrayref2str($key).'=';
 5896:     } elsif (ref($key) eq 'HASH') {
 5897:       $result.=&hashref2str($key).'=';
 5898:     } elsif (ref($key)) {
 5899:       $result.='=';
 5900:       #print("Got a ref of ".(ref($key))." skipping.");
 5901:     } else {
 5902: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5903:     }
 5904: 
 5905:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5906:       $result.=&arrayref2str($hashref->{$key}).'&';
 5907:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5908:       $result.=&hashref2str($hashref->{$key}).'&';
 5909:     } elsif(ref($hashref->{$key})) {
 5910:        $result.='&';
 5911:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5912:     } else {
 5913:       $result.=&escape($hashref->{$key}).'&';
 5914:     }
 5915:   }
 5916:   $result=~s/\&$//;
 5917:   $result .= '__END_HASH_REF__';
 5918:   return $result;
 5919: }
 5920: 
 5921: sub str2hash {
 5922:     my ($string)=@_;
 5923:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5924:     return %$hash;
 5925: }
 5926: 
 5927: sub str2hashref {
 5928:   my ($string) = @_;
 5929: 
 5930:   my %hash;
 5931: 
 5932:   if($string !~ /^__HASH_REF__/) {
 5933:       if (! ($string eq '' || !defined($string))) {
 5934: 	  $hash{'error'}='Not hash reference';
 5935:       }
 5936:       return (\%hash, $string);
 5937:   }
 5938: 
 5939:   $string =~ s/^__HASH_REF__//;
 5940: 
 5941:   while($string !~ /^__END_HASH_REF__/) {
 5942:       #key
 5943:       my $key='';
 5944:       if($string =~ /^__HASH_REF__/) {
 5945:           ($key, $string)=&str2hashref($string);
 5946:           if(defined($key->{'error'})) {
 5947:               $hash{'error'}='Bad data';
 5948:               return (\%hash, $string);
 5949:           }
 5950:       } elsif($string =~ /^__ARRAY_REF__/) {
 5951:           ($key, $string)=&str2arrayref($string);
 5952:           if($key->[0] eq 'Array reference error') {
 5953:               $hash{'error'}='Bad data';
 5954:               return (\%hash, $string);
 5955:           }
 5956:       } else {
 5957:           $string =~ s/^(.*?)=//;
 5958: 	  $key=&unescape($1);
 5959:       }
 5960:       $string =~ s/^=//;
 5961: 
 5962:       #value
 5963:       my $value='';
 5964:       if($string =~ /^__HASH_REF__/) {
 5965:           ($value, $string)=&str2hashref($string);
 5966:           if(defined($value->{'error'})) {
 5967:               $hash{'error'}='Bad data';
 5968:               return (\%hash, $string);
 5969:           }
 5970:       } elsif($string =~ /^__ARRAY_REF__/) {
 5971:           ($value, $string)=&str2arrayref($string);
 5972:           if($value->[0] eq 'Array reference error') {
 5973:               $hash{'error'}='Bad data';
 5974:               return (\%hash, $string);
 5975:           }
 5976:       } else {
 5977: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5978:       }
 5979:       $string =~ s/^&//;
 5980: 
 5981:       $hash{$key}=$value;
 5982:   }
 5983: 
 5984:   $string =~ s/^__END_HASH_REF__//;
 5985: 
 5986:   return (\%hash, $string);
 5987: }
 5988: 
 5989: sub str2array {
 5990:     my ($string)=@_;
 5991:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5992:     return @$array;
 5993: }
 5994: 
 5995: sub str2arrayref {
 5996:   my ($string) = @_;
 5997:   my @array;
 5998: 
 5999:   if($string !~ /^__ARRAY_REF__/) {
 6000:       if (! ($string eq '' || !defined($string))) {
 6001: 	  $array[0]='Array reference error';
 6002:       }
 6003:       return (\@array, $string);
 6004:   }
 6005: 
 6006:   $string =~ s/^__ARRAY_REF__//;
 6007: 
 6008:   while($string !~ /^__END_ARRAY_REF__/) {
 6009:       my $value='';
 6010:       if($string =~ /^__HASH_REF__/) {
 6011:           ($value, $string)=&str2hashref($string);
 6012:           if(defined($value->{'error'})) {
 6013:               $array[0] ='Array reference error';
 6014:               return (\@array, $string);
 6015:           }
 6016:       } elsif($string =~ /^__ARRAY_REF__/) {
 6017:           ($value, $string)=&str2arrayref($string);
 6018:           if($value->[0] eq 'Array reference error') {
 6019:               $array[0] ='Array reference error';
 6020:               return (\@array, $string);
 6021:           }
 6022:       } else {
 6023: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6024:       }
 6025:       $string =~ s/^&//;
 6026: 
 6027:       push(@array, $value);
 6028:   }
 6029: 
 6030:   $string =~ s/^__END_ARRAY_REF__//;
 6031: 
 6032:   return (\@array, $string);
 6033: }
 6034: 
 6035: # -------------------------------------------------------------------Temp Store
 6036: 
 6037: sub tmpreset {
 6038:   my ($symb,$namespace,$domain,$stuname) = @_;
 6039:   if (!$symb) {
 6040:     $symb=&symbread();
 6041:     if (!$symb) { $symb= $env{'request.url'}; }
 6042:   }
 6043:   $symb=escape($symb);
 6044: 
 6045:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6046:   $namespace=~s/\//\_/g;
 6047:   $namespace=~s/\W//g;
 6048: 
 6049:   if (!$domain) { $domain=$env{'user.domain'}; }
 6050:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6051:   if ($domain eq 'public' && $stuname eq 'public') {
 6052:       $stuname=$ENV{'REMOTE_ADDR'};
 6053:   }
 6054:   my $path=LONCAPA::tempdir();
 6055:   my %hash;
 6056:   if (tie(%hash,'GDBM_File',
 6057: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6058: 	  &GDBM_WRCREAT(),0640)) {
 6059:     foreach my $key (keys(%hash)) {
 6060:       if ($key=~ /:$symb/) {
 6061: 	delete($hash{$key});
 6062:       }
 6063:     }
 6064:   }
 6065: }
 6066: 
 6067: sub tmpstore {
 6068:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6069: 
 6070:   if (!$symb) {
 6071:     $symb=&symbread();
 6072:     if (!$symb) { $symb= $env{'request.url'}; }
 6073:   }
 6074:   $symb=escape($symb);
 6075: 
 6076:   if (!$namespace) {
 6077:     # I don't think we would ever want to store this for a course.
 6078:     # it seems this will only be used if we don't have a course.
 6079:     #$namespace=$env{'request.course.id'};
 6080:     #if (!$namespace) {
 6081:       $namespace=$env{'request.state'};
 6082:     #}
 6083:   }
 6084:   $namespace=~s/\//\_/g;
 6085:   $namespace=~s/\W//g;
 6086:   if (!$domain) { $domain=$env{'user.domain'}; }
 6087:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6088:   if ($domain eq 'public' && $stuname eq 'public') {
 6089:       $stuname=$ENV{'REMOTE_ADDR'};
 6090:   }
 6091:   my $now=time;
 6092:   my %hash;
 6093:   my $path=LONCAPA::tempdir();
 6094:   if (tie(%hash,'GDBM_File',
 6095: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6096: 	  &GDBM_WRCREAT(),0640)) {
 6097:     $hash{"version:$symb"}++;
 6098:     my $version=$hash{"version:$symb"};
 6099:     my $allkeys=''; 
 6100:     foreach my $key (keys(%$storehash)) {
 6101:       $allkeys.=$key.':';
 6102:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6103:     }
 6104:     $hash{"$version:$symb:timestamp"}=$now;
 6105:     $allkeys.='timestamp';
 6106:     $hash{"$version:keys:$symb"}=$allkeys;
 6107:     if (untie(%hash)) {
 6108:       return 'ok';
 6109:     } else {
 6110:       return "error:$!";
 6111:     }
 6112:   } else {
 6113:     return "error:$!";
 6114:   }
 6115: }
 6116: 
 6117: # -----------------------------------------------------------------Temp Restore
 6118: 
 6119: sub tmprestore {
 6120:   my ($symb,$namespace,$domain,$stuname) = @_;
 6121: 
 6122:   if (!$symb) {
 6123:     $symb=&symbread();
 6124:     if (!$symb) { $symb= $env{'request.url'}; }
 6125:   }
 6126:   $symb=escape($symb);
 6127: 
 6128:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6129: 
 6130:   if (!$domain) { $domain=$env{'user.domain'}; }
 6131:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6132:   if ($domain eq 'public' && $stuname eq 'public') {
 6133:       $stuname=$ENV{'REMOTE_ADDR'};
 6134:   }
 6135:   my %returnhash;
 6136:   $namespace=~s/\//\_/g;
 6137:   $namespace=~s/\W//g;
 6138:   my %hash;
 6139:   my $path=LONCAPA::tempdir();
 6140:   if (tie(%hash,'GDBM_File',
 6141: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6142: 	  &GDBM_READER(),0640)) {
 6143:     my $version=$hash{"version:$symb"};
 6144:     $returnhash{'version'}=$version;
 6145:     my $scope;
 6146:     for ($scope=1;$scope<=$version;$scope++) {
 6147:       my $vkeys=$hash{"$scope:keys:$symb"};
 6148:       my @keys=split(/:/,$vkeys);
 6149:       my $key;
 6150:       $returnhash{"$scope:keys"}=$vkeys;
 6151:       foreach $key (@keys) {
 6152: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6153: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6154:       }
 6155:     }
 6156:     if (!(untie(%hash))) {
 6157:       return "error:$!";
 6158:     }
 6159:   } else {
 6160:     return "error:$!";
 6161:   }
 6162:   return %returnhash;
 6163: }
 6164: 
 6165: # ----------------------------------------------------------------------- Store
 6166: 
 6167: sub store {
 6168:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6169:     my $home='';
 6170: 
 6171:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6172: 
 6173:     $symb=&symbclean($symb);
 6174:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6175: 
 6176:     if (!$domain) { $domain=$env{'user.domain'}; }
 6177:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6178: 
 6179:     &devalidate($symb,$stuname,$domain);
 6180: 
 6181:     $symb=escape($symb);
 6182:     if (!$namespace) { 
 6183:        unless ($namespace=$env{'request.course.id'}) { 
 6184:           return ''; 
 6185:        } 
 6186:     }
 6187:     if (!$home) { $home=$env{'user.home'}; }
 6188: 
 6189:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6190:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6191: 
 6192:     my $namevalue='';
 6193:     foreach my $key (keys(%$storehash)) {
 6194:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6195:     }
 6196:     $namevalue=~s/\&$//;
 6197:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6198:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6199: }
 6200: 
 6201: # -------------------------------------------------------------- Critical Store
 6202: 
 6203: sub cstore {
 6204:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6205:     my $home='';
 6206: 
 6207:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6208: 
 6209:     $symb=&symbclean($symb);
 6210:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6211: 
 6212:     if (!$domain) { $domain=$env{'user.domain'}; }
 6213:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6214: 
 6215:     &devalidate($symb,$stuname,$domain);
 6216: 
 6217:     $symb=escape($symb);
 6218:     if (!$namespace) { 
 6219:        unless ($namespace=$env{'request.course.id'}) { 
 6220:           return ''; 
 6221:        } 
 6222:     }
 6223:     if (!$home) { $home=$env{'user.home'}; }
 6224: 
 6225:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6226:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6227: 
 6228:     my $namevalue='';
 6229:     foreach my $key (keys(%$storehash)) {
 6230:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6231:     }
 6232:     $namevalue=~s/\&$//;
 6233:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6234:     return critical
 6235:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6236: }
 6237: 
 6238: # --------------------------------------------------------------------- Restore
 6239: 
 6240: sub restore {
 6241:     my ($symb,$namespace,$domain,$stuname) = @_;
 6242:     my $home='';
 6243: 
 6244:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6245: 
 6246:     if (!$symb) {
 6247:         return if ($namespace eq 'courserequests');
 6248:         unless ($symb=escape(&symbread())) { return ''; }
 6249:     } else {
 6250:         unless ($namespace eq 'courserequests') {
 6251:             $symb=&escape(&symbclean($symb));
 6252:         }
 6253:     }
 6254:     if (!$namespace) { 
 6255:        unless ($namespace=$env{'request.course.id'}) { 
 6256:           return ''; 
 6257:        } 
 6258:     }
 6259:     if (!$domain) { $domain=$env{'user.domain'}; }
 6260:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6261:     if (!$home) { $home=$env{'user.home'}; }
 6262:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6263: 
 6264:     my %returnhash=();
 6265:     foreach my $line (split(/\&/,$answer)) {
 6266: 	my ($name,$value)=split(/\=/,$line);
 6267:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6268:     }
 6269:     my $version;
 6270:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6271:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6272:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6273:        }
 6274:     }
 6275:     return %returnhash;
 6276: }
 6277: 
 6278: # ---------------------------------------------------------- Course Description
 6279: #
 6280: #  
 6281: 
 6282: sub coursedescription {
 6283:     my ($courseid,$args)=@_;
 6284:     $courseid=~s/^\///;
 6285:     $courseid=~s/\_/\//g;
 6286:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6287:     my $chome=&homeserver($cnum,$cdomain);
 6288:     my $normalid=$cdomain.'_'.$cnum;
 6289:     # need to always cache even if we get errors otherwise we keep 
 6290:     # trying and trying and trying to get the course description.
 6291:     my %envhash=();
 6292:     my %returnhash=();
 6293:     
 6294:     my $expiretime=600;
 6295:     if ($env{'request.course.id'} eq $normalid) {
 6296: 	$expiretime=120;
 6297:     }
 6298: 
 6299:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6300:     if (!$args->{'freshen_cache'}
 6301: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6302: 	foreach my $key (keys(%env)) {
 6303: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6304: 	    my ($setting) = $1;
 6305: 	    $returnhash{$setting} = $env{$key};
 6306: 	}
 6307: 	return %returnhash;
 6308:     }
 6309: 
 6310:     # get the data again
 6311: 
 6312:     if (!$args->{'one_time'}) {
 6313: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6314:     }
 6315: 
 6316:     if ($chome ne 'no_host') {
 6317:        %returnhash=&dump('environment',$cdomain,$cnum);
 6318:        if (!exists($returnhash{'con_lost'})) {
 6319: 	   my $username = $env{'user.name'}; # Defult username
 6320: 	   if(defined $args->{'user'}) {
 6321: 	       $username = $args->{'user'};
 6322: 	   }
 6323:            $returnhash{'home'}= $chome;
 6324: 	   $returnhash{'domain'} = $cdomain;
 6325: 	   $returnhash{'num'} = $cnum;
 6326:            if (!defined($returnhash{'type'})) {
 6327:                $returnhash{'type'} = 'Course';
 6328:            }
 6329:            while (my ($name,$value) = each %returnhash) {
 6330:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6331:            }
 6332:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6333:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6334: 	       $username.'_'.$cdomain.'_'.$cnum;
 6335:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6336:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6337:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6338:        }
 6339:     }
 6340:     if (!$args->{'one_time'}) {
 6341: 	&appenv(\%envhash);
 6342:     }
 6343:     return %returnhash;
 6344: }
 6345: 
 6346: sub update_released_required {
 6347:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6348:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6349:         $cid = $env{'request.course.id'};
 6350:         $cdom = $env{'course.'.$cid.'.domain'};
 6351:         $cnum = $env{'course.'.$cid.'.num'};
 6352:         $chome = $env{'course.'.$cid.'.home'};
 6353:     }
 6354:     if ($needsrelease) {
 6355:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6356:         my $needsupdate;
 6357:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6358:             $needsupdate = 1;
 6359:         } else {
 6360:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6361:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6362:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6363:                 $needsupdate = 1;
 6364:             }
 6365:         }
 6366:         if ($needsupdate) {
 6367:             my %needshash = (
 6368:                              'internal.releaserequired' => $needsrelease,
 6369:                             );
 6370:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6371:             if ($putresult eq 'ok') {
 6372:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6373:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6374:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6375:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6376:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6377:                 }
 6378:             }
 6379:         }
 6380:     }
 6381:     return;
 6382: }
 6383: 
 6384: # -------------------------------------------------See if a user is privileged
 6385: 
 6386: sub privileged {
 6387:     my ($username,$domain,$possdomains,$possroles)=@_;
 6388:     my $now = time;
 6389:     my $roles;
 6390:     if (ref($possroles) eq 'ARRAY') {
 6391:         $roles = $possroles; 
 6392:     } else {
 6393:         $roles = ['dc','su'];
 6394:     }
 6395:     if (ref($possdomains) eq 'ARRAY') {
 6396:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6397:         foreach my $dom (@{$possdomains}) {
 6398:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6399:                 (ref($privileged{$dom}) eq 'HASH')) {
 6400:                 foreach my $role (@{$roles}) {
 6401:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6402:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6403:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6404:                             return 1 unless (($end && $end < $now) ||
 6405:                                              ($start && $start > $now));
 6406:                         }
 6407:                     }
 6408:                 }
 6409:             }
 6410:         }
 6411:     } else {
 6412:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6413:         my $now = time;
 6414: 
 6415:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6416:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6417:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6418:                 return 1 unless ($tend && $tend < $now) 
 6419:                         or ($tstart && $tstart > $now);
 6420:             }
 6421:         }
 6422:     }
 6423:     return 0;
 6424: }
 6425: 
 6426: sub privileged_by_domain {
 6427:     my ($domains,$roles) = @_;
 6428:     my %privileged = ();
 6429:     my $cachetime = 60*60*24;
 6430:     my $now = time;
 6431:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6432:         return %privileged;
 6433:     }
 6434:     foreach my $dom (@{$domains}) {
 6435:         next if (ref($privileged{$dom}) eq 'HASH');
 6436:         my $needroles;
 6437:         foreach my $role (@{$roles}) {
 6438:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6439:             if (defined($cached)) {
 6440:                 if (ref($result) eq 'HASH') {
 6441:                     $privileged{$dom}{$role} = $result;
 6442:                 }
 6443:             } else {
 6444:                 $needroles = 1;
 6445:             }
 6446:         }
 6447:         if ($needroles) {
 6448:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6449:             $privileged{$dom} = {};
 6450:             foreach my $server (keys(%dompersonnel)) {
 6451:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6452:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6453:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6454:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6455:                         next if ($end && $end < $now);
 6456:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6457:                             $dompersonnel{$server}{$item};
 6458:                     }
 6459:                 }
 6460:             }
 6461:             if (ref($privileged{$dom}) eq 'HASH') {
 6462:                 foreach my $role (@{$roles}) {
 6463:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6464:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6465:                     } else {
 6466:                         my %hash = ();
 6467:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6468:                     }
 6469:                 }
 6470:             }
 6471:         }
 6472:     }
 6473:     return %privileged;
 6474: }
 6475: 
 6476: # -------------------------------------------------------- Get user privileges
 6477: 
 6478: sub rolesinit {
 6479:     my ($domain, $username) = @_;
 6480:     my %userroles = ('user.login.time' => time);
 6481:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6482: 
 6483:     # firstaccess and timerinterval are related to timed maps/resources. 
 6484:     # also, blocking can be triggered by an activating timer
 6485:     # it's saved in the user's %env.
 6486:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6487:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6488:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6489:         %timerintchk, %timerintenv);
 6490: 
 6491:     foreach my $key (keys(%firstaccess)) {
 6492:         my ($cid, $rest) = split(/\0/, $key);
 6493:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6494:     }
 6495: 
 6496:     foreach my $key (keys(%timerinterval)) {
 6497:         my ($cid,$rest) = split(/\0/,$key);
 6498:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6499:     }
 6500: 
 6501:     my %allroles=();
 6502:     my %allgroups=();
 6503: 
 6504:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6505:         my $role = $rolesdump{$area};
 6506:         $area =~ s/\_\w\w$//;
 6507: 
 6508:         my ($trole, $tend, $tstart, $group_privs);
 6509: 
 6510:         if ($role =~ /^cr/) {
 6511:         # Custom role, defined by a user 
 6512:         # e.g., user.role.cr/msu/smith/mynewrole
 6513:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6514:                 $trole = $1;
 6515:                 ($tend, $tstart) = split('_', $2);
 6516:             } else {
 6517:                 $trole = $role;
 6518:             }
 6519:         } elsif ($role =~ m|^gr/|) {
 6520:         # Role of member in a group, defined within a course/community
 6521:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6522:             ($trole, $tend, $tstart) = split(/_/, $role);
 6523:             next if $tstart eq '-1';
 6524:             ($trole, $group_privs) = split(/\//, $trole);
 6525:             $group_privs = &unescape($group_privs);
 6526:         } else {
 6527:         # Just a normal role, defined in roles.tab
 6528:             ($trole, $tend, $tstart) = split(/_/,$role);
 6529:         }
 6530: 
 6531:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6532:                  $username);
 6533:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6534: 
 6535:         # role expired or not available yet?
 6536:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6537:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6538: 
 6539:         next if $area eq '' or $trole eq '';
 6540: 
 6541:         my $spec = "$trole.$area";
 6542:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6543: 
 6544:         if ($trole =~ /^cr\//) {
 6545:         # Custom role, defined by a user
 6546:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6547:         } elsif ($trole eq 'gr') {
 6548:         # Role of a member in a group, defined within a course/community
 6549:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6550:             next;
 6551:         } else {
 6552:         # Normal role, defined in roles.tab
 6553:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6554:         }
 6555: 
 6556:         my $cid = $tdomain.'_'.$trest;
 6557:         unless ($firstaccchk{$cid}) {
 6558:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6559:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6560:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6561:                         $coursetimerstarts{$cid}{$item}; 
 6562:                 }
 6563:             }
 6564:             $firstaccchk{$cid} = 1;
 6565:         }
 6566:         unless ($timerintchk{$cid}) {
 6567:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6568:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6569:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6570:                        $coursetimerintervals{$cid}{$item};
 6571:                 }
 6572:             }
 6573:             $timerintchk{$cid} = 1;
 6574:         }
 6575:     }
 6576: 
 6577:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6578:                                                           \%allroles, \%allgroups);
 6579:     $env{'user.adv'} = $userroles{'user.adv'};
 6580:     $env{'user.rar'} = $userroles{'user.rar'};
 6581: 
 6582:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6583: }
 6584: 
 6585: sub set_arearole {
 6586:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6587:     unless ($nolog) {
 6588: # log the associated role with the area
 6589:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6590:     }
 6591:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6592: }
 6593: 
 6594: sub custom_roleprivs {
 6595:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6596:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6597:     my $homsvr = &homeserver($rauthor,$rdomain);
 6598:     if (&hostname($homsvr) ne '') {
 6599:         my ($rdummy,$roledef)=
 6600:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6601:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6602:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6603:             if (defined($syspriv)) {
 6604:                 if ($trest =~ /^$match_community$/) {
 6605:                     $syspriv =~ s/bre\&S//; 
 6606:                 }
 6607:                 $$allroles{'cm./'}.=':'.$syspriv;
 6608:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6609:             }
 6610:             if ($tdomain ne '') {
 6611:                 if (defined($dompriv)) {
 6612:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6613:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6614:                 }
 6615:                 if (($trest ne '') && (defined($coursepriv))) {
 6616:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6617:                         my $rolename = $1;
 6618:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6619:                     }
 6620:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6621:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6622:                 }
 6623:             }
 6624:         }
 6625:     }
 6626: }
 6627: 
 6628: sub course_adhocrole_privs {
 6629:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6630:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6631:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6632:         my (%currprivs,%storeprivs);
 6633:         foreach my $item (split(/:/,$coursepriv)) {
 6634:             my ($priv,$restrict) = split(/\&/,$item);
 6635:             $currprivs{$priv} = $restrict;
 6636:         }
 6637:         my (%possadd,%possremove,%full);
 6638:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6639:             my ($priv,$restrict)=split(/\&/,$item);
 6640:             $full{$priv} = $restrict;
 6641:         }
 6642:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6643:              next if ($item eq '');
 6644:              my ($rule,$rest) = split(/=/,$item);
 6645:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6646:              foreach my $priv (split(/:/,$rest)) {
 6647:                  if ($priv ne '') {
 6648:                      if ($rule eq 'off') {
 6649:                          $possremove{$priv} = 1;
 6650:                      } else {
 6651:                          $possadd{$priv} = 1;
 6652:                      }
 6653:                  }
 6654:              }
 6655:          }
 6656:          foreach my $priv (sort(keys(%full))) {
 6657:              if (exists($currprivs{$priv})) {
 6658:                  unless (exists($possremove{$priv})) {
 6659:                      $storeprivs{$priv} = $currprivs{$priv};
 6660:                  }
 6661:              } elsif (exists($possadd{$priv})) {
 6662:                  $storeprivs{$priv} = $full{$priv};
 6663:              }
 6664:          }
 6665:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6666:      }
 6667:      return $coursepriv;
 6668: }
 6669: 
 6670: sub group_roleprivs {
 6671:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6672:     my $access = 1;
 6673:     my $now = time;
 6674:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6675:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6676:     if ($access) {
 6677:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6678:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6679:     }
 6680: }
 6681: 
 6682: sub standard_roleprivs {
 6683:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6684:     if (defined($pr{$trole.':s'})) {
 6685:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6686:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6687:     }
 6688:     if ($tdomain ne '') {
 6689:         if (defined($pr{$trole.':d'})) {
 6690:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6691:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6692:         }
 6693:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6694:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6695:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6696:         }
 6697:     }
 6698: }
 6699: 
 6700: sub set_userprivs {
 6701:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6702:     my $author=0;
 6703:     my $adv=0;
 6704:     my $rar=0;
 6705:     my %grouproles = ();
 6706:     if (keys(%{$allgroups}) > 0) {
 6707:         my @groupkeys; 
 6708:         foreach my $role (keys(%{$allroles})) {
 6709:             push(@groupkeys,$role);
 6710:         }
 6711:         if (ref($groups_roles) eq 'HASH') {
 6712:             foreach my $key (keys(%{$groups_roles})) {
 6713:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6714:                     push(@groupkeys,$key);
 6715:                 }
 6716:             }
 6717:         }
 6718:         if (@groupkeys > 0) {
 6719:             foreach my $role (@groupkeys) {
 6720:                 my ($trole,$area,$sec,$extendedarea);
 6721:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6722:                     $trole = $1;
 6723:                     $area = $2;
 6724:                     $sec = $3;
 6725:                     $extendedarea = $area.$sec;
 6726:                     if (exists($$allgroups{$area})) {
 6727:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6728:                             my $spec = $trole.'.'.$extendedarea;
 6729:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6730:                                                 $$allgroups{$area}{$group};
 6731:                         }
 6732:                     }
 6733:                 }
 6734:             }
 6735:         }
 6736:     }
 6737:     foreach my $group (keys(%grouproles)) {
 6738:         $$allroles{$group} = $grouproles{$group};
 6739:     }
 6740:     foreach my $role (keys(%{$allroles})) {
 6741:         my %thesepriv;
 6742:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6743:         foreach my $item (split(/:/,$$allroles{$role})) {
 6744:             if ($item ne '') {
 6745:                 my ($privilege,$restrictions)=split(/&/,$item);
 6746:                 if ($restrictions eq '') {
 6747:                     $thesepriv{$privilege}='F';
 6748:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6749:                     $thesepriv{$privilege}.=$restrictions;
 6750:                 }
 6751:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6752:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6753:             }
 6754:         }
 6755:         my $thesestr='';
 6756:         foreach my $priv (sort(keys(%thesepriv))) {
 6757: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6758: 	}
 6759:         $userroles->{'user.priv.'.$role} = $thesestr;
 6760:     }
 6761:     return ($author,$adv,$rar);
 6762: }
 6763: 
 6764: sub role_status {
 6765:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6766:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6767:         my ($one,$two) = split(m{\./},$rolekey,2);
 6768:         (undef,undef,$$role) = split(/\./,$one,3);
 6769:         unless (!defined($$role) || $$role eq '') {
 6770:             $$where = '/'.$two;
 6771:             $$trolecode=$$role.'.'.$$where;
 6772:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6773:             $$tstatus='is';
 6774:             if ($$tstart && $$tstart>$update) {
 6775:                 $$tstatus='future';
 6776:                 if ($$tstart<$now) {
 6777:                     if ($$tstart && $$tstart>$refresh) {
 6778:                         if (($$where ne '') && ($$role ne '')) {
 6779:                             my (%allroles,%allgroups,$group_privs,
 6780:                                 %groups_roles,@rolecodes);
 6781:                             my %userroles = (
 6782:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6783:                             );
 6784:                             @rolecodes = ('cm'); 
 6785:                             my $spec=$$role.'.'.$$where;
 6786:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6787:                             if ($$role =~ /^cr\//) {
 6788:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6789:                                 push(@rolecodes,'cr');
 6790:                             } elsif ($$role eq 'gr') {
 6791:                                 push(@rolecodes,$$role);
 6792:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6793:                                                     $env{'user.name'});
 6794:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6795:                                 (undef,my $group_privs) = split(/\//,$trole);
 6796:                                 $group_privs = &unescape($group_privs);
 6797:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6798:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6799:                                 &get_groups_roles($tdomain,$trest,
 6800:                                                   \%course_roles,\@rolecodes,
 6801:                                                   \%groups_roles);
 6802:                             } else {
 6803:                                 push(@rolecodes,$$role);
 6804:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6805:                             }
 6806:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6807:                                                                    \%groups_roles);
 6808:                             &appenv(\%userroles,\@rolecodes);
 6809:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6810:                         }
 6811:                     }
 6812:                     $$tstatus = 'is';
 6813:                 }
 6814:             }
 6815:             if ($$tend) {
 6816:                 if ($$tend<$update) {
 6817:                     $$tstatus='expired';
 6818:                 } elsif ($$tend<$now) {
 6819:                     $$tstatus='will_not';
 6820:                 }
 6821:             }
 6822:         }
 6823:     }
 6824: }
 6825: 
 6826: sub get_groups_roles {
 6827:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6828:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6829:                   (ref($rolecodes) eq 'ARRAY') && 
 6830:                   (ref($groups_roles) eq 'HASH')); 
 6831:     if (keys(%{$cdom_courseroles}) > 0) {
 6832:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6833:         if ($cdom ne '' && $cnum ne '') {
 6834:             foreach my $key (keys(%{$cdom_courseroles})) {
 6835:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6836:                     my $crsrole = $1;
 6837:                     my $crssec = $2;
 6838:                     if ($crsrole =~ /^cr/) {
 6839:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6840:                             push(@{$rolecodes},'cr');
 6841:                         }
 6842:                     } else {
 6843:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6844:                             push(@{$rolecodes},$crsrole);
 6845:                         }
 6846:                     }
 6847:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6848:                     if ($crssec ne '') {
 6849:                         $rolekey .= "/$crssec";
 6850:                     }
 6851:                     $rolekey .= './';
 6852:                     $groups_roles->{$rolekey} = $rolecodes;
 6853:                 }
 6854:             }
 6855:         }
 6856:     }
 6857:     return;
 6858: }
 6859: 
 6860: sub delete_env_groupprivs {
 6861:     my ($where,$courseroles,$possroles) = @_;
 6862:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6863:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6864:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6865:         %{$courseroles->{$udom}} =
 6866:             &get_my_roles('','','userroles',['active'],
 6867:                           $possroles,[$udom],1);
 6868:     }
 6869:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6870:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6871:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6872:             my $area = '/'.$cdom.'/'.$cnum;
 6873:             my $privkey = "user.priv.$crsrole.$area";
 6874:             if ($crssec ne '') {
 6875:                 $privkey .= '/'.$crssec;
 6876:             }
 6877:             $privkey .= ".$area/$group";
 6878:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6879:         }
 6880:     }
 6881:     return;
 6882: }
 6883: 
 6884: sub check_adhoc_privs {
 6885:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6886:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6887:     if ($sec) {
 6888:         $cckey .= '/'.$sec;
 6889:     } 
 6890:     my $setprivs;
 6891:     if ($env{$cckey}) {
 6892:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6893:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6894:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6895:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6896:             $setprivs = 1;
 6897:         }
 6898:     } else {
 6899:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6900:         $setprivs = 1;
 6901:     }
 6902:     return $setprivs;
 6903: }
 6904: 
 6905: sub set_adhoc_privileges {
 6906: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6907:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6908:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6909:     if ($sec ne '') {
 6910:         $area .= '/'.$sec;
 6911:     }
 6912:     my $spec = $role.'.'.$area;
 6913:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6914:                                   $env{'user.name'},1);
 6915:     my %rolehash = ();
 6916:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6917:         my $rolename = $1;
 6918:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6919:         my %domdef = &get_domain_defaults($dcdom);
 6920:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6921:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6922:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6923:             }
 6924:         }
 6925:     } else {
 6926:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6927:     }
 6928:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6929:     &appenv(\%userroles,[$role,'cm']);
 6930:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6931:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 6932:             ($caller eq 'tiny')) {
 6933:         &appenv( {'request.role'        => $spec,
 6934:                   'request.role.domain' => $dcdom,
 6935:                   'request.course.sec'  => $sec,
 6936:                  }
 6937:                );
 6938:         my $tadv=0;
 6939:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6940:         &appenv({'request.role.adv'    => $tadv});
 6941:     }
 6942: }
 6943: 
 6944: # --------------------------------------------------------------- get interface
 6945: 
 6946: sub get {
 6947:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6948:    my $items='';
 6949:    foreach my $item (@$storearr) {
 6950:        $items.=&escape($item).'&';
 6951:    }
 6952:    $items=~s/\&$//;
 6953:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6954:    if (!$uname) { $uname=$env{'user.name'}; }
 6955:    my $uhome=&homeserver($uname,$udomain);
 6956: 
 6957:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6958:    my @pairs=split(/\&/,$rep);
 6959:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6960:      return @pairs;
 6961:    }
 6962:    my %returnhash=();
 6963:    my $i=0;
 6964:    foreach my $item (@$storearr) {
 6965:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6966:       $i++;
 6967:    }
 6968:    return %returnhash;
 6969: }
 6970: 
 6971: # --------------------------------------------------------------- del interface
 6972: 
 6973: sub del {
 6974:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6975:    my $items='';
 6976:    foreach my $item (@$storearr) {
 6977:        $items.=&escape($item).'&';
 6978:    }
 6979: 
 6980:    $items=~s/\&$//;
 6981:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6982:    if (!$uname) { $uname=$env{'user.name'}; }
 6983:    my $uhome=&homeserver($uname,$udomain);
 6984:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6985: }
 6986: 
 6987: # -------------------------------------------------------------- dump interface
 6988: 
 6989: sub unserialize {
 6990:     my ($rep, $escapedkeys) = @_;
 6991: 
 6992:     return {} if $rep =~ /^error/;
 6993: 
 6994:     my %returnhash=();
 6995: 	foreach my $item (split(/\&/,$rep)) {
 6996: 	    my ($key, $value) = split(/=/, $item, 2);
 6997: 	    $key = unescape($key) unless $escapedkeys;
 6998: 	    next if $key =~ /^error: 2 /;
 6999: 	    $returnhash{$key} = &thaw_unescape($value);
 7000: 	}
 7001:     #return %returnhash;
 7002:     return \%returnhash;
 7003: }        
 7004: 
 7005: # see Lond::dump_with_regexp
 7006: # if $escapedkeys hash keys won't get unescaped.
 7007: sub dump {
 7008:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 7009:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7010:     if (!$uname) { $uname=$env{'user.name'}; }
 7011:     my $uhome=&homeserver($uname,$udomain);
 7012: 
 7013:     if ($regexp) {
 7014:         $regexp=&escape($regexp);
 7015:     } else {
 7016:         $regexp='.';
 7017:     }
 7018:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7019:         # user is hosted on this machine
 7020:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7021:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7022:         return %{unserialize($reply, $escapedkeys)};
 7023:     }
 7024:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7025:     my @pairs=split(/\&/,$rep);
 7026:     my %returnhash=();
 7027:     if (!($rep =~ /^error/ )) {
 7028: 	foreach my $item (@pairs) {
 7029: 	    my ($key,$value)=split(/=/,$item,2);
 7030:         $key = unescape($key) unless $escapedkeys;
 7031:         #$key = &unescape($key);
 7032: 	    next if ($key =~ /^error: 2 /);
 7033: 	    $returnhash{$key}=&thaw_unescape($value);
 7034: 	}
 7035:     }
 7036:     return %returnhash;
 7037: }
 7038: 
 7039: 
 7040: # --------------------------------------------------------- dumpstore interface
 7041: 
 7042: sub dumpstore {
 7043:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7044:    # same as dump but keys must be escaped. They may contain colon separated
 7045:    # lists of values that may themself contain colons (e.g. symbs).
 7046:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7047: }
 7048: 
 7049: # -------------------------------------------------------------- keys interface
 7050: 
 7051: sub getkeys {
 7052:    my ($namespace,$udomain,$uname)=@_;
 7053:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7054:    if (!$uname) { $uname=$env{'user.name'}; }
 7055:    my $uhome=&homeserver($uname,$udomain);
 7056:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7057:    my @keyarray=();
 7058:    foreach my $key (split(/\&/,$rep)) {
 7059:       next if ($key =~ /^error: 2 /);
 7060:       push(@keyarray,&unescape($key));
 7061:    }
 7062:    return @keyarray;
 7063: }
 7064: 
 7065: # --------------------------------------------------------------- currentdump
 7066: sub currentdump {
 7067:    my ($courseid,$sdom,$sname)=@_;
 7068:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7069:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7070:    $sname    = $env{'user.name'}         if (! defined($sname));
 7071:    my $uhome = &homeserver($sname,$sdom);
 7072:    my $rep;
 7073: 
 7074:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7075:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7076:                    $courseid)));
 7077:    } else {
 7078:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7079:    }
 7080: 
 7081:    return if ($rep =~ /^(error:|no_such_host)/);
 7082:    #
 7083:    my %returnhash=();
 7084:    #
 7085:    if ($rep eq 'unknown_cmd') {
 7086:        # an old lond will not know currentdump
 7087:        # Do a dump and make it look like a currentdump
 7088:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7089:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7090:        my %hash = @tmp;
 7091:        @tmp=();
 7092:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7093:    } else {
 7094:        my @pairs=split(/\&/,$rep);
 7095:        foreach my $pair (@pairs) {
 7096:            my ($key,$value)=split(/=/,$pair,2);
 7097:            my ($symb,$param) = split(/:/,$key);
 7098:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7099:                                                         &thaw_unescape($value);
 7100:        }
 7101:    }
 7102:    return %returnhash;
 7103: }
 7104: 
 7105: sub convert_dump_to_currentdump{
 7106:     my %hash = %{shift()};
 7107:     my %returnhash;
 7108:     # Code ripped from lond, essentially.  The only difference
 7109:     # here is the unescaping done by lonnet::dump().  Conceivably
 7110:     # we might run in to problems with parameter names =~ /^v\./
 7111:     while (my ($key,$value) = each(%hash)) {
 7112:         my ($v,$symb,$param) = split(/:/,$key);
 7113: 	$symb  = &unescape($symb);
 7114: 	$param = &unescape($param);
 7115:         next if ($v eq 'version' || $symb eq 'keys');
 7116:         next if (exists($returnhash{$symb}) &&
 7117:                  exists($returnhash{$symb}->{$param}) &&
 7118:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7119:         $returnhash{$symb}->{$param}=$value;
 7120:         $returnhash{$symb}->{'v.'.$param}=$v;
 7121:     }
 7122:     #
 7123:     # Remove all of the keys in the hashes which keep track of
 7124:     # the version of the parameter.
 7125:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7126:         # use a foreach because we are going to delete from the hash.
 7127:         foreach my $key (keys(%$param_hash)) {
 7128:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7129:         }
 7130:     }
 7131:     return \%returnhash;
 7132: }
 7133: 
 7134: # ------------------------------------------------------ critical inc interface
 7135: 
 7136: sub cinc {
 7137:     return &inc(@_,'critical');
 7138: }
 7139: 
 7140: # --------------------------------------------------------------- inc interface
 7141: 
 7142: sub inc {
 7143:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7144:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7145:     if (!$uname) { $uname=$env{'user.name'}; }
 7146:     my $uhome=&homeserver($uname,$udomain);
 7147:     my $items='';
 7148:     if (! ref($store)) {
 7149:         # got a single value, so use that instead
 7150:         $items = &escape($store).'=&';
 7151:     } elsif (ref($store) eq 'SCALAR') {
 7152:         $items = &escape($$store).'=&';        
 7153:     } elsif (ref($store) eq 'ARRAY') {
 7154:         $items = join('=&',map {&escape($_);} @{$store});
 7155:     } elsif (ref($store) eq 'HASH') {
 7156:         while (my($key,$value) = each(%{$store})) {
 7157:             $items.= &escape($key).'='.&escape($value).'&';
 7158:         }
 7159:     }
 7160:     $items=~s/\&$//;
 7161:     if ($critical) {
 7162: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7163:     } else {
 7164: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7165:     }
 7166: }
 7167: 
 7168: # --------------------------------------------------------------- put interface
 7169: 
 7170: sub put {
 7171:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7172:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7173:    if (!$uname) { $uname=$env{'user.name'}; }
 7174:    my $uhome=&homeserver($uname,$udomain);
 7175:    my $items='';
 7176:    foreach my $item (keys(%$storehash)) {
 7177:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7178:    }
 7179:    $items=~s/\&$//;
 7180:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7181: }
 7182: 
 7183: # ------------------------------------------------------------ newput interface
 7184: 
 7185: sub newput {
 7186:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7187:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7188:    if (!$uname) { $uname=$env{'user.name'}; }
 7189:    my $uhome=&homeserver($uname,$udomain);
 7190:    my $items='';
 7191:    foreach my $key (keys(%$storehash)) {
 7192:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7193:    }
 7194:    $items=~s/\&$//;
 7195:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7196: }
 7197: 
 7198: # ---------------------------------------------------------  putstore interface
 7199: 
 7200: sub putstore {
 7201:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7202:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7203:    if (!$uname) { $uname=$env{'user.name'}; }
 7204:    my $uhome=&homeserver($uname,$udomain);
 7205:    my $items='';
 7206:    foreach my $key (keys(%$storehash)) {
 7207:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7208:    }
 7209:    $items=~s/\&$//;
 7210:    my $esc_symb=&escape($symb);
 7211:    my $esc_v=&escape($version);
 7212:    my $reply =
 7213:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7214: 	      $uhome);
 7215:    if (($tolog) && ($reply eq 'ok')) {
 7216:        my $namevalue='';
 7217:        foreach my $key (keys(%{$storehash})) {
 7218:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7219:        }
 7220:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 7221:                      '&host='.&escape($perlvar{'lonHostID'}).
 7222:                      '&version='.$esc_v.
 7223:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7224:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7225:    }
 7226:    if ($reply eq 'unknown_cmd') {
 7227:        # gfall back to way things use to be done
 7228:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7229: 			    $uname);
 7230:    }
 7231:    return $reply;
 7232: }
 7233: 
 7234: sub old_putstore {
 7235:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7236:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7237:     if (!$uname) { $uname=$env{'user.name'}; }
 7238:     my $uhome=&homeserver($uname,$udomain);
 7239:     my %newstorehash;
 7240:     foreach my $item (keys(%$storehash)) {
 7241: 	my $key = $version.':'.&escape($symb).':'.$item;
 7242: 	$newstorehash{$key} = $storehash->{$item};
 7243:     }
 7244:     my $items='';
 7245:     my %allitems = ();
 7246:     foreach my $item (keys(%newstorehash)) {
 7247: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7248: 	    my $key = $1.':keys:'.$2;
 7249: 	    $allitems{$key} .= $3.':';
 7250: 	}
 7251: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7252:     }
 7253:     foreach my $item (keys(%allitems)) {
 7254: 	$allitems{$item} =~ s/\:$//;
 7255: 	$items.= $item.'='.$allitems{$item}.'&';
 7256:     }
 7257:     $items=~s/\&$//;
 7258:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7259: }
 7260: 
 7261: # ------------------------------------------------------ critical put interface
 7262: 
 7263: sub cput {
 7264:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7265:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7266:    if (!$uname) { $uname=$env{'user.name'}; }
 7267:    my $uhome=&homeserver($uname,$udomain);
 7268:    my $items='';
 7269:    foreach my $item (keys(%$storehash)) {
 7270:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7271:    }
 7272:    $items=~s/\&$//;
 7273:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7274: }
 7275: 
 7276: # -------------------------------------------------------------- eget interface
 7277: 
 7278: sub eget {
 7279:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7280:    my $items='';
 7281:    foreach my $item (@$storearr) {
 7282:        $items.=&escape($item).'&';
 7283:    }
 7284:    $items=~s/\&$//;
 7285:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7286:    if (!$uname) { $uname=$env{'user.name'}; }
 7287:    my $uhome=&homeserver($uname,$udomain);
 7288:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7289:    my @pairs=split(/\&/,$rep);
 7290:    my %returnhash=();
 7291:    my $i=0;
 7292:    foreach my $item (@$storearr) {
 7293:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7294:       $i++;
 7295:    }
 7296:    return %returnhash;
 7297: }
 7298: 
 7299: # ------------------------------------------------------------ tmpput interface
 7300: sub tmpput {
 7301:     my ($storehash,$server,$context)=@_;
 7302:     my $items='';
 7303:     foreach my $item (keys(%$storehash)) {
 7304: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7305:     }
 7306:     $items=~s/\&$//;
 7307:     if (defined($context)) {
 7308:         $items .= ':'.&escape($context);
 7309:     }
 7310:     return &reply("tmpput:$items",$server);
 7311: }
 7312: 
 7313: # ------------------------------------------------------------ tmpget interface
 7314: sub tmpget {
 7315:     my ($token,$server)=@_;
 7316:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7317:     my $rep=&reply("tmpget:$token",$server);
 7318:     my %returnhash;
 7319:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7320:         return %returnhash;
 7321:     }
 7322:     foreach my $item (split(/\&/,$rep)) {
 7323: 	my ($key,$value)=split(/=/,$item);
 7324: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7325:     }
 7326:     return %returnhash;
 7327: }
 7328: 
 7329: # ------------------------------------------------------------ tmpdel interface
 7330: sub tmpdel {
 7331:     my ($token,$server)=@_;
 7332:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7333:     return &reply("tmpdel:$token",$server);
 7334: }
 7335: 
 7336: # ------------------------------------------------------------ get_timebased_id 
 7337: 
 7338: sub get_timebased_id {
 7339:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7340:         $maxtries) = @_;
 7341:     my ($newid,$error,$dellock);
 7342:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7343:         return ('','ok','invalid call to get suffix');
 7344:     }
 7345: 
 7346: # set defaults for any optional args for which values were not supplied
 7347:     if ($who eq '') {
 7348:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7349:     }
 7350:     if (!$locktries) {
 7351:         $locktries = 3;
 7352:     }
 7353:     if (!$maxtries) {
 7354:         $maxtries = 10;
 7355:     }
 7356:     
 7357:     if (($cdom eq '') || ($cnum eq '')) {
 7358:         if ($env{'request.course.id'}) {
 7359:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7360:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7361:         }
 7362:         if (($cdom eq '') || ($cnum eq '')) {
 7363:             return ('','ok','call to get suffix not in course context');
 7364:         }
 7365:     }
 7366: 
 7367: # construct locking item
 7368:     my $lockhash = {
 7369:                       $prefix."\0".'locked_'.$keyid => $who,
 7370:                    };
 7371:     my $tries = 0;
 7372: 
 7373: # attempt to get lock on nohist_$namespace file
 7374:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7375:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7376:         $tries ++;
 7377:         sleep 1;
 7378:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7379:     }
 7380: 
 7381: # attempt to get unique identifier, based on current timestamp
 7382:     if ($gotlock eq 'ok') {
 7383:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7384:         my $id = time;
 7385:         $newid = $id;
 7386:         if ($idtype eq 'addcode') {
 7387:             $newid .= &sixnum_code();
 7388:         }
 7389:         my $idtries = 0;
 7390:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7391:             if ($idtype eq 'concat') {
 7392:                 $newid = $id.$idtries;
 7393:             } elsif ($idtype eq 'addcode') {
 7394:                 $newid = $newid.&sixnum_code();
 7395:             } else {
 7396:                 $newid ++;
 7397:             }
 7398:             $idtries ++;
 7399:         }
 7400:         if (!exists($inuse{$prefix."\0".$newid})) {
 7401:             my %new_item =  (
 7402:                               $prefix."\0".$newid => $who,
 7403:                             );
 7404:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7405:                                                  $cdom,$cnum);
 7406:             if ($putresult ne 'ok') {
 7407:                 undef($newid);
 7408:                 $error = 'error saving new item: '.$putresult;
 7409:             }
 7410:         } else {
 7411:              undef($newid);
 7412:              $error = ('error: no unique suffix available for the new item ');
 7413:         }
 7414: #  remove lock
 7415:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7416:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7417:     } else {
 7418:         $error = "error: could not obtain lockfile\n";
 7419:         $dellock = 'ok';
 7420:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7421:             $dellock = 'nolock';
 7422:         }
 7423:     }
 7424:     return ($newid,$dellock,$error);
 7425: }
 7426: 
 7427: sub sixnum_code {
 7428:     my $code;
 7429:     for (0..6) {
 7430:         $code .= int( rand(9) );
 7431:     }
 7432:     return $code;
 7433: }
 7434: 
 7435: # -------------------------------------------------- portfolio access checking
 7436: 
 7437: sub portfolio_access {
 7438:     my ($requrl,$clientip) = @_;
 7439:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7440:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7441:     if ($result) {
 7442:         my %setters;
 7443:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7444:             my ($startblock,$endblock) =
 7445:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7446:             if ($startblock && $endblock) {
 7447:                 return 'B';
 7448:             }
 7449:         } else {
 7450:             my ($startblock,$endblock) =
 7451:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7452:             if ($startblock && $endblock) {
 7453:                 return 'B';
 7454:             }
 7455:         }
 7456:     }
 7457:     if ($result eq 'ok') {
 7458:        return 'F';
 7459:     } elsif ($result =~ /^[^:]+:guest_/) {
 7460:        return 'A';
 7461:     }
 7462:     return '';
 7463: }
 7464: 
 7465: sub get_portfolio_access {
 7466:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7467: 
 7468:     if (!ref($access_hash)) {
 7469: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7470: 	my %access_controls = &get_access_controls($current_perms,$group,
 7471: 						   $file_name);
 7472: 	$access_hash = $access_controls{$file_name};
 7473:     }
 7474: 
 7475:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7476:     my $now = time;
 7477:     if (ref($access_hash) eq 'HASH') {
 7478:         foreach my $key (keys(%{$access_hash})) {
 7479:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7480:             if ($start > $now) {
 7481:                 next;
 7482:             }
 7483:             if ($end && $end<$now) {
 7484:                 next;
 7485:             }
 7486:             if ($scope eq 'public') {
 7487:                 $public = $key;
 7488:                 last;
 7489:             } elsif ($scope eq 'guest') {
 7490:                 $guest = $key;
 7491:             } elsif ($scope eq 'domains') {
 7492:                 push(@domains,$key);
 7493:             } elsif ($scope eq 'users') {
 7494:                 push(@users,$key);
 7495:             } elsif ($scope eq 'course') {
 7496:                 push(@courses,$key);
 7497:             } elsif ($scope eq 'group') {
 7498:                 push(@groups,$key);
 7499:             } elsif ($scope eq 'ip') {
 7500:                 push(@ips,$key);
 7501:             }
 7502:         }
 7503:         if ($public) {
 7504:             return 'ok';
 7505:         } elsif (@ips > 0) {
 7506:             my $allowed;
 7507:             foreach my $ipkey (@ips) {
 7508:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7509:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7510:                         $allowed = 1;
 7511:                         last; 
 7512:                     }
 7513:                 }
 7514:             }
 7515:             if ($allowed) {
 7516:                 return 'ok';
 7517:             }
 7518:         }
 7519:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7520:             if ($guest) {
 7521:                 return $guest;
 7522:             }
 7523:         } else {
 7524:             if (@domains > 0) {
 7525:                 foreach my $domkey (@domains) {
 7526:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7527:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7528:                             return 'ok';
 7529:                         }
 7530:                     }
 7531:                 }
 7532:             }
 7533:             if (@users > 0) {
 7534:                 foreach my $userkey (@users) {
 7535:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7536:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7537:                             if (ref($item) eq 'HASH') {
 7538:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7539:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7540:                                     return 'ok';
 7541:                                 }
 7542:                             }
 7543:                         }
 7544:                     } 
 7545:                 }
 7546:             }
 7547:             my %roleshash;
 7548:             my @courses_and_groups = @courses;
 7549:             push(@courses_and_groups,@groups); 
 7550:             if (@courses_and_groups > 0) {
 7551:                 my (%allgroups,%allroles); 
 7552:                 my ($start,$end,$role,$sec,$group);
 7553:                 foreach my $envkey (%env) {
 7554:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7555:                         my $cid = $2.'_'.$3; 
 7556:                         if ($1 eq 'gr') {
 7557:                             $group = $4;
 7558:                             $allgroups{$cid}{$group} = $env{$envkey};
 7559:                         } else {
 7560:                             if ($4 eq '') {
 7561:                                 $sec = 'none';
 7562:                             } else {
 7563:                                 $sec = $4;
 7564:                             }
 7565:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7566:                         }
 7567:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7568:                         my $cid = $2.'_'.$3;
 7569:                         if ($4 eq '') {
 7570:                             $sec = 'none';
 7571:                         } else {
 7572:                             $sec = $4;
 7573:                         }
 7574:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7575:                     }
 7576:                 }
 7577:                 if (keys(%allroles) == 0) {
 7578:                     return;
 7579:                 }
 7580:                 foreach my $key (@courses_and_groups) {
 7581:                     my %content = %{$$access_hash{$key}};
 7582:                     my $cnum = $content{'number'};
 7583:                     my $cdom = $content{'domain'};
 7584:                     my $cid = $cdom.'_'.$cnum;
 7585:                     if (!exists($allroles{$cid})) {
 7586:                         next;
 7587:                     }    
 7588:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7589:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7590:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7591:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7592:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7593:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7594:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7595:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7596:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7597:                                         if (grep/^all$/,@sections) {
 7598:                                             return 'ok';
 7599:                                         } else {
 7600:                                             if (grep/^$sec$/,@sections) {
 7601:                                                 return 'ok';
 7602:                                             }
 7603:                                         }
 7604:                                     }
 7605:                                 }
 7606:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7607:                                     if (grep/^none$/,@groups) {
 7608:                                         return 'ok';
 7609:                                     }
 7610:                                 } else {
 7611:                                     if (grep/^all$/,@groups) {
 7612:                                         return 'ok';
 7613:                                     } 
 7614:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7615:                                         if (grep/^$group$/,@groups) {
 7616:                                             return 'ok';
 7617:                                         }
 7618:                                     }
 7619:                                 } 
 7620:                             }
 7621:                         }
 7622:                     }
 7623:                 }
 7624:             }
 7625:             if ($guest) {
 7626:                 return $guest;
 7627:             }
 7628:         }
 7629:     }
 7630:     return;
 7631: }
 7632: 
 7633: sub course_group_datechecker {
 7634:     my ($dates,$now,$status) = @_;
 7635:     my ($start,$end) = split(/\./,$dates);
 7636:     if (!$start && !$end) {
 7637:         return 'ok';
 7638:     }
 7639:     if (grep/^active$/,@{$status}) {
 7640:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7641:             return 'ok';
 7642:         }
 7643:     }
 7644:     if (grep/^previous$/,@{$status}) {
 7645:         if ($end > $now ) {
 7646:             return 'ok';
 7647:         }
 7648:     }
 7649:     if (grep/^future$/,@{$status}) {
 7650:         if ($start > $now) {
 7651:             return 'ok';
 7652:         }
 7653:     }
 7654:     return; 
 7655: }
 7656: 
 7657: sub parse_portfolio_url {
 7658:     my ($url) = @_;
 7659: 
 7660:     my ($type,$udom,$unum,$group,$file_name);
 7661:     
 7662:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7663: 	$type = 1;
 7664:         $udom = $1;
 7665:         $unum = $2;
 7666:         $file_name = $3;
 7667:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7668: 	$type = 2;
 7669:         $udom = $1;
 7670:         $unum = $2;
 7671:         $group = $3;
 7672:         $file_name = $3.'/'.$4;
 7673:     }
 7674:     if (wantarray) {
 7675: 	return ($type,$udom,$unum,$file_name,$group);
 7676:     }
 7677:     return $type;
 7678: }
 7679: 
 7680: sub is_portfolio_url {
 7681:     my ($url) = @_;
 7682:     return scalar(&parse_portfolio_url($url));
 7683: }
 7684: 
 7685: sub is_portfolio_file {
 7686:     my ($file) = @_;
 7687:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7688:         return 1;
 7689:     }
 7690:     return;
 7691: }
 7692: 
 7693: sub usertools_access {
 7694:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7695:     my ($access,%tools);
 7696:     if ($context eq '') {
 7697:         $context = 'tools';
 7698:     }
 7699:     if ($context eq 'requestcourses') {
 7700:         %tools = (
 7701:                       official   => 1,
 7702:                       unofficial => 1,
 7703:                       community  => 1,
 7704:                       textbook   => 1,
 7705:                       placement  => 1,
 7706:                       lti        => 1,
 7707:                  );
 7708:     } elsif ($context eq 'requestauthor') {
 7709:         %tools = (
 7710:                       requestauthor => 1,
 7711:                  );
 7712:     } else {
 7713:         %tools = (
 7714:                       aboutme   => 1,
 7715:                       blog      => 1,
 7716:                       webdav    => 1,
 7717:                       portfolio => 1,
 7718:                  );
 7719:     }
 7720:     return if (!defined($tools{$tool}));
 7721: 
 7722:     if (($udom eq '') || ($uname eq '')) {
 7723:         $udom = $env{'user.domain'};
 7724:         $uname = $env{'user.name'};
 7725:     }
 7726: 
 7727:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7728:         if ($action ne 'reload') {
 7729:             if ($context eq 'requestcourses') {
 7730:                 return $env{'environment.canrequest.'.$tool};
 7731:             } elsif ($context eq 'requestauthor') {
 7732:                 return $env{'environment.canrequest.author'};
 7733:             } else {
 7734:                 return $env{'environment.availabletools.'.$tool};
 7735:             }
 7736:         }
 7737:     }
 7738: 
 7739:     my ($toolstatus,$inststatus,$envkey);
 7740:     if ($context eq 'requestauthor') {
 7741:         $envkey = $context; 
 7742:     } else {
 7743:         $envkey = $context.'.'.$tool;
 7744:     }
 7745: 
 7746:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7747:          ($action ne 'reload')) {
 7748:         $toolstatus = $env{'environment.'.$envkey};
 7749:         $inststatus = $env{'environment.inststatus'};
 7750:     } else {
 7751:         if (ref($userenvref) eq 'HASH') {
 7752:             $toolstatus = $userenvref->{$envkey};
 7753:             $inststatus = $userenvref->{'inststatus'};
 7754:         } else {
 7755:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7756:             $toolstatus = $userenv{$envkey};
 7757:             $inststatus = $userenv{'inststatus'};
 7758:         }
 7759:     }
 7760: 
 7761:     if ($toolstatus ne '') {
 7762:         if ($toolstatus) {
 7763:             $access = 1;
 7764:         } else {
 7765:             $access = 0;
 7766:         }
 7767:         return $access;
 7768:     }
 7769: 
 7770:     my ($is_adv,%domdef);
 7771:     if (ref($is_advref) eq 'HASH') {
 7772:         $is_adv = $is_advref->{'is_adv'};
 7773:     } else {
 7774:         $is_adv = &is_advanced_user($udom,$uname);
 7775:     }
 7776:     if (ref($domdefref) eq 'HASH') {
 7777:         %domdef = %{$domdefref};
 7778:     } else {
 7779:         %domdef = &get_domain_defaults($udom);
 7780:     }
 7781:     if (ref($domdef{$tool}) eq 'HASH') {
 7782:         if ($is_adv) {
 7783:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7784:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7785:                     $access = 1;
 7786:                 } else {
 7787:                     $access = 0;
 7788:                 }
 7789:                 return $access;
 7790:             }
 7791:         }
 7792:         if ($inststatus ne '') {
 7793:             my ($hasaccess,$hasnoaccess);
 7794:             foreach my $affiliation (split(/:/,$inststatus)) {
 7795:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7796:                     if ($domdef{$tool}{$affiliation}) {
 7797:                         $hasaccess = 1;
 7798:                     } else {
 7799:                         $hasnoaccess = 1;
 7800:                     }
 7801:                 }
 7802:             }
 7803:             if ($hasaccess || $hasnoaccess) {
 7804:                 if ($hasaccess) {
 7805:                     $access = 1;
 7806:                 } elsif ($hasnoaccess) {
 7807:                     $access = 0; 
 7808:                 }
 7809:                 return $access;
 7810:             }
 7811:         } else {
 7812:             if ($domdef{$tool}{'default'} ne '') {
 7813:                 if ($domdef{$tool}{'default'}) {
 7814:                     $access = 1;
 7815:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7816:                     $access = 0;
 7817:                 }
 7818:                 return $access;
 7819:             }
 7820:         }
 7821:     } else {
 7822:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7823:             $access = 1;
 7824:         } else {
 7825:             $access = 0;
 7826:         }
 7827:         return $access;
 7828:     }
 7829: }
 7830: 
 7831: sub is_course_owner {
 7832:     my ($cdom,$cnum,$udom,$uname) = @_;
 7833:     if (($udom eq '') || ($uname eq '')) {
 7834:         $udom = $env{'user.domain'};
 7835:         $uname = $env{'user.name'};
 7836:     }
 7837:     unless (($udom eq '') || ($uname eq '')) {
 7838:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7839:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7840:                 return 1;
 7841:             } else {
 7842:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7843:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7844:                     return 1;
 7845:                 }
 7846:             }
 7847:         }
 7848:     }
 7849:     return;
 7850: }
 7851: 
 7852: sub is_advanced_user {
 7853:     my ($udom,$uname) = @_;
 7854:     if ($udom ne '' && $uname ne '') {
 7855:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7856:             if (wantarray) {
 7857:                 return ($env{'user.adv'},$env{'user.author'});
 7858:             } else {
 7859:                 return $env{'user.adv'};
 7860:             }
 7861:         }
 7862:     }
 7863:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7864:     my %allroles;
 7865:     my ($is_adv,$is_author);
 7866:     foreach my $role (keys(%roleshash)) {
 7867:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7868:         my $area = '/'.$tdomain.'/'.$trest;
 7869:         if ($sec ne '') {
 7870:             $area .= '/'.$sec;
 7871:         }
 7872:         if (($area ne '') && ($trole ne '')) {
 7873:             my $spec=$trole.'.'.$area;
 7874:             if ($trole =~ /^cr\//) {
 7875:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7876:             } elsif ($trole ne 'gr') {
 7877:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7878:             }
 7879:             if ($trole eq 'au') {
 7880:                 $is_author = 1;
 7881:             }
 7882:         }
 7883:     }
 7884:     foreach my $role (keys(%allroles)) {
 7885:         last if ($is_adv);
 7886:         foreach my $item (split(/:/,$allroles{$role})) {
 7887:             if ($item ne '') {
 7888:                 my ($privilege,$restrictions)=split(/&/,$item);
 7889:                 if ($privilege eq 'adv') {
 7890:                     $is_adv = 1;
 7891:                     last;
 7892:                 }
 7893:             }
 7894:         }
 7895:     }
 7896:     if (wantarray) {
 7897:         return ($is_adv,$is_author);
 7898:     }
 7899:     return $is_adv;
 7900: }
 7901: 
 7902: sub check_can_request {
 7903:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7904:     my $canreq = 0;
 7905:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7906:         $uname = $env{'user.name'};
 7907:         $udom = $env{'user.domain'};
 7908:     }
 7909:     my ($types,$typename) = &Apache::loncommon::course_types();
 7910:     my @options = ('approval','validate','autolimit');
 7911:     my $optregex = join('|',@options);
 7912:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7913:         foreach my $type (@{$types}) {
 7914:             if (&usertools_access($uname,$udom,$type,undef,
 7915:                                   'requestcourses')) {
 7916:                 $canreq ++;
 7917:                 if (ref($request_domains) eq 'HASH') {
 7918:                     push(@{$request_domains->{$type}},$udom);
 7919:                 }
 7920:                 if ($dom eq $udom) {
 7921:                     $can_request->{$type} = 1;
 7922:                 }
 7923:             }
 7924:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7925:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7926:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7927:                 if (@curr > 0) {
 7928:                     foreach my $item (@curr) {
 7929:                         if (ref($request_domains) eq 'HASH') {
 7930:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7931:                             if ($otherdom ne '') {
 7932:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7933:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7934:                                         push(@{$request_domains->{$type}},$otherdom);
 7935:                                     }
 7936:                                 } else {
 7937:                                     push(@{$request_domains->{$type}},$otherdom);
 7938:                                 }
 7939:                             }
 7940:                         }
 7941:                     }
 7942:                     unless ($dom eq $env{'user.domain'}) {
 7943:                         $canreq ++;
 7944:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7945:                             $can_request->{$type} = 1;
 7946:                         }
 7947:                     }
 7948:                 }
 7949:             }
 7950:         }
 7951:     }
 7952:     return $canreq;
 7953: }
 7954: 
 7955: # ---------------------------------------------- Custom access rule evaluation
 7956: 
 7957: sub customaccess {
 7958:     my ($priv,$uri)=@_;
 7959:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7960:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7961:     $udom = &LONCAPA::clean_domain($udom);
 7962:     $ucrs = &LONCAPA::clean_username($ucrs);
 7963:     my $access=0;
 7964:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7965: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7966: 	if ($type eq 'user') {
 7967: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7968: 		my ($tdom,$tuname)=split(m{/},$scope);
 7969: 		if ($tdom) {
 7970: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7971: 		}
 7972: 		if ($tuname) {
 7973: 		    if ($tuname ne $env{'user.name'}) { next; }
 7974: 		}
 7975: 		$access=($effect eq 'allow');
 7976: 		last;
 7977: 	    }
 7978: 	} else {
 7979: 	    if ($role) {
 7980: 		if ($role ne $urole) { next; }
 7981: 	    }
 7982: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7983: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7984: 		if ($tdom) {
 7985: 		    if ($tdom ne $udom) { next; }
 7986: 		}
 7987: 		if ($tcrs) {
 7988: 		    if ($tcrs ne $ucrs) { next; }
 7989: 		}
 7990: 		if ($tsec) {
 7991: 		    if ($tsec ne $usec) { next; }
 7992: 		}
 7993: 		$access=($effect eq 'allow');
 7994: 		last;
 7995: 	    }
 7996: 	    if ($realm eq '' && $role eq '') {
 7997: 		$access=($effect eq 'allow');
 7998: 	    }
 7999: 	}
 8000:     }
 8001:     return $access;
 8002: }
 8003: 
 8004: # ------------------------------------------------- Check for a user privilege
 8005: 
 8006: sub allowed {
 8007:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 8008:     my $ver_orguri=$uri;
 8009:     $uri=&deversion($uri);
 8010:     my $orguri=$uri;
 8011:     $uri=&declutter($uri);
 8012: 
 8013:     if ($priv eq 'evb') {
 8014: # Evade communication block restrictions for specified role in a course
 8015:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8016:             return $1;
 8017:         } else {
 8018:             return;
 8019:         }
 8020:     }
 8021: 
 8022:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8023: # Free bre access to adm and meta resources
 8024:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 8025: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8026: 	&& ($priv eq 'bre')) {
 8027: 	return 'F';
 8028:     }
 8029: 
 8030: # Free bre access to user's own portfolio contents
 8031:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8032:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8033: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8034:         my %setters;
 8035:         my ($startblock,$endblock) = 
 8036:             &Apache::loncommon::blockcheck(\%setters,'port');
 8037:         if ($startblock && $endblock) {
 8038:             return 'B';
 8039:         } else {
 8040:             return 'F';
 8041:         }
 8042:     }
 8043: 
 8044: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8045:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8046:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8047:         if (exists($env{'request.course.id'})) {
 8048:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8049:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8050:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8051:                 my $courseprivid=$env{'request.course.id'};
 8052:                 $courseprivid=~s/\_/\//;
 8053:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8054:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8055:                     return $1; 
 8056:                 } else {
 8057:                     if ($env{'request.course.sec'}) {
 8058:                         $courseprivid.='/'.$env{'request.course.sec'};
 8059:                     }
 8060:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8061:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8062:                         return $2;
 8063:                     }
 8064:                 }
 8065:             }
 8066:         }
 8067:     }
 8068: 
 8069: # Free bre to public access
 8070: 
 8071:     if ($priv eq 'bre') {
 8072:         my $copyright;
 8073:         unless ($uri =~ /ext\.tool/) {
 8074:             $copyright=&metadata($uri,'copyright');
 8075:         }
 8076: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8077:            return 'F'; 
 8078:         }
 8079:         if ($copyright eq 'priv') {
 8080:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8081: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8082: 		return '';
 8083:             }
 8084:         }
 8085:         if ($copyright eq 'domain') {
 8086:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8087: 	    unless (($env{'user.domain'} eq $1) ||
 8088:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8089: 		return '';
 8090:             }
 8091:         }
 8092:         if ($env{'request.role'}=~ /li\.\//) {
 8093:             # Library role, so allow browsing of resources in this domain.
 8094:             return 'F';
 8095:         }
 8096:         if ($copyright eq 'custom') {
 8097: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8098:         }
 8099:     }
 8100:     # Domain coordinator is trying to create a course
 8101:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8102:         # uri is the requested domain in this case.
 8103:         # comparison to 'request.role.domain' shows if the user has selected
 8104:         # a role of dc for the domain in question.
 8105:         return 'F' if ($uri eq $env{'request.role.domain'});
 8106:     }
 8107: 
 8108:     my $thisallowed='';
 8109:     my $statecond=0;
 8110:     my $courseprivid='';
 8111: 
 8112:     my $ownaccess;
 8113:     # Community Coordinator or Assistant Co-author browsing resource space.
 8114:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8115:         if ($uri eq '') {
 8116:             $ownaccess = 1;
 8117:         } else {
 8118:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8119:                 my $udom = $env{'user.domain'};
 8120:                 my $uname = $env{'user.name'};
 8121:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8122:                     $ownaccess = 1;
 8123:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8124:                     unless ($uri =~ m{\.\./}) {
 8125:                         $ownaccess = 1;
 8126:                     }
 8127:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8128:                     my $now = time;
 8129:                     if ($uri =~ m{^([^/]+)/?$}) {
 8130:                         my $adom = $1;
 8131:                         foreach my $key (keys(%env)) {
 8132:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8133:                                 my ($start,$end) = split('.',$env{$key});
 8134:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8135:                                     $ownaccess = 1;
 8136:                                     last;
 8137:                                 }
 8138:                             }
 8139:                         }
 8140:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8141:                         my $adom = $1;
 8142:                         my $aname = $2;
 8143:                         foreach my $role ('ca','aa') { 
 8144:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8145:                                 my ($start,$end) =
 8146:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8147:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8148:                                     $ownaccess = 1;
 8149:                                     last;
 8150:                                 }
 8151:                             }
 8152:                         }
 8153:                     }
 8154:                 }
 8155:             }
 8156:         }
 8157:     }
 8158: 
 8159: # Course
 8160: 
 8161:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8162:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8163:             $thisallowed.=$1;
 8164:         }
 8165:     }
 8166: 
 8167: # Domain
 8168: 
 8169:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8170:        =~/\Q$priv\E\&([^\:]*)/) {
 8171:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8172:             $thisallowed.=$1;
 8173:         }
 8174:     }
 8175: 
 8176: # User who is not author or co-author might still be able to edit
 8177: # resource of an author in the domain (e.g., if Domain Coordinator).
 8178:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8179:         (&allowed('mdc',$env{'request.course.id'}))) {
 8180:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8181:             $thisallowed.=$1;
 8182:         }
 8183:     }
 8184: 
 8185: # Course: uri itself is a course
 8186:     my $courseuri=$uri;
 8187:     $courseuri=~s/\_(\d)/\/$1/;
 8188:     $courseuri=~s/^([^\/])/\/$1/;
 8189: 
 8190:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8191:        =~/\Q$priv\E\&([^\:]*)/) {
 8192:         if ($priv eq 'mip') {
 8193:             my $rem = $1;
 8194:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8195:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8196:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8197:                 if ($cdom ne '') {
 8198:                     my %passwdconf = &get_passwdconf($cdom);
 8199:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8200:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8201:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8202:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8203:                                 unless (@inststatuses) {
 8204:                                     @inststatuses = ('default');
 8205:                                 }
 8206:                                 foreach my $status (@inststatuses) {
 8207:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8208:                                         $thisallowed.=$rem;
 8209:                                     }
 8210:                                 }
 8211:                             }
 8212:                         }
 8213:                     }
 8214:                 }
 8215:             }
 8216:         } else {
 8217:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8218:                 $thisallowed.=$1;
 8219:             }
 8220:         }
 8221:     }
 8222: 
 8223: # URI is an uploaded document for this course, default permissions don't matter
 8224: # not allowing 'edit' access (editupload) to uploaded course docs
 8225:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8226: 	$thisallowed='';
 8227:         my ($match)=&is_on_map($uri);
 8228:         if ($match) {
 8229:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8230:                   =~/\Q$priv\E\&([^\:]*)/) {
 8231:                 my $value = $1;
 8232:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8233:                 if ($deeplinkblock) {
 8234:                     $thisallowed='D';
 8235:                 } elsif ($noblockcheck) {
 8236:                     $thisallowed.=$value;
 8237:                 } else {
 8238:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8239:                     if (@blockers > 0) {
 8240:                         $thisallowed = 'B';
 8241:                     } else {
 8242:                         $thisallowed.=$value;
 8243:                     }
 8244:                 }
 8245:             }
 8246:         } else {
 8247:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8248:             if ($refuri) {
 8249:                 if ($refuri =~ m|^/adm/|) {
 8250:                     $thisallowed='F';
 8251:                 } else {
 8252:                     $refuri=&declutter($refuri);
 8253:                     my ($match) = &is_on_map($refuri);
 8254:                     if ($match) {
 8255:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8256:                         if ($deeplinkblock) {
 8257:                             $thisallowed='D';
 8258:                         } elsif ($noblockcheck) {
 8259:                             $thisallowed='F';
 8260:                         } else {
 8261:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8262:                             if (@blockers > 0) {
 8263:                                 $thisallowed = 'B';
 8264:                             } else {
 8265:                                 $thisallowed='F';
 8266:                             }
 8267:                         }
 8268:                     }
 8269:                 }
 8270:             }
 8271:         }
 8272:     }
 8273: 
 8274:     if ($priv eq 'bre'
 8275: 	&& $thisallowed ne 'F' 
 8276: 	&& $thisallowed ne '2'
 8277: 	&& &is_portfolio_url($uri)) {
 8278: 	$thisallowed = &portfolio_access($uri,$clientip);
 8279:     }
 8280: 
 8281: # Full access at system, domain or course-wide level? Exit.
 8282:     if ($thisallowed=~/F/) {
 8283: 	return 'F';
 8284:     }
 8285: 
 8286: # If this is generating or modifying users, exit with special codes
 8287: 
 8288:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8289: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8290: 	    my ($audom,$auname)=split('/',$uri);
 8291: # no author name given, so this just checks on the general right to make a co-author in this domain
 8292: 	    unless ($auname) { return $thisallowed; }
 8293: # an author name is given, so we are about to actually make a co-author for a certain account
 8294: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8295: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8296: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8297: 	}
 8298: 	return $thisallowed;
 8299:     }
 8300: #
 8301: # Gathered so far: system, domain and course wide privileges
 8302: #
 8303: # Course: See if uri or referer is an individual resource that is part of 
 8304: # the course
 8305: 
 8306:     if ($env{'request.course.id'}) {
 8307: 
 8308: # If this is modifying password (internal auth) domains must match for user and user's role.
 8309: 
 8310:         if ($priv eq 'mip') {
 8311:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8312:                 return $thisallowed;
 8313:             } else {
 8314:                 return '';
 8315:             }
 8316:         }
 8317: 
 8318:        $courseprivid=$env{'request.course.id'};
 8319:        if ($env{'request.course.sec'}) {
 8320:           $courseprivid.='/'.$env{'request.course.sec'};
 8321:        }
 8322:        $courseprivid=~s/\_/\//;
 8323:        my $checkreferer=1;
 8324:        my ($match,$cond)=&is_on_map($uri);
 8325:        if ($match) {
 8326:            $statecond=$cond;
 8327:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8328:                =~/\Q$priv\E\&([^\:]*)/) {
 8329:                my $value = $1;
 8330:                if ($priv eq 'bre') {
 8331:                    if ($noblockcheck) {
 8332:                        $thisallowed.=$value;
 8333:                    } else {
 8334:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8335:                        if (@blockers > 0) {
 8336:                            $thisallowed = 'B';
 8337:                        } else {
 8338:                            $thisallowed.=$value;
 8339:                        }
 8340:                    }
 8341:                } else {
 8342:                    $thisallowed.=$value;
 8343:                }
 8344:                $checkreferer=0;
 8345:            }
 8346:        }
 8347:        
 8348:        if ($checkreferer) {
 8349: 	  my $refuri=$env{'httpref.'.$orguri};
 8350:             unless ($refuri) {
 8351:                 foreach my $key (keys(%env)) {
 8352: 		    if ($key=~/^httpref\..*\*/) {
 8353: 			my $pattern=$key;
 8354:                         $pattern=~s/^httpref\.\/res\///;
 8355:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8356:                         $pattern=~s/\//\\\//g;
 8357:                         if ($orguri=~/$pattern/) {
 8358: 			    $refuri=$env{$key};
 8359:                         }
 8360:                     }
 8361:                 }
 8362:             }
 8363: 
 8364:          if ($refuri) { 
 8365: 	  $refuri=&declutter($refuri);
 8366:           my ($match,$cond)=&is_on_map($refuri);
 8367:             if ($match) {
 8368:               my $refstatecond=$cond;
 8369:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8370:                   =~/\Q$priv\E\&([^\:]*)/) {
 8371:                   my $value = $1;
 8372:                   if ($priv eq 'bre') {
 8373:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8374:                       if ($deeplinkblock) {
 8375:                           $thisallowed = 'D';
 8376:                       } elsif ($noblockcheck) {
 8377:                           $thisallowed.=$value;
 8378:                       } else {
 8379:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8380:                           if (@blockers > 0) {
 8381:                               $thisallowed = 'B';
 8382:                           } else {
 8383:                               $thisallowed.=$value;
 8384:                           }
 8385:                       }
 8386:                   } else {
 8387:                       $thisallowed.=$value;
 8388:                   }
 8389:                   $uri=$refuri;
 8390:                   $statecond=$refstatecond;
 8391:               }
 8392:           }
 8393:         }
 8394:        }
 8395:    }
 8396: 
 8397: #
 8398: # Gathered now: all privileges that could apply, and condition number
 8399: # 
 8400: #
 8401: # Full or no access?
 8402: #
 8403: 
 8404:     if ($thisallowed=~/F/) {
 8405: 	return 'F';
 8406:     }
 8407: 
 8408:     unless ($thisallowed) {
 8409:         return '';
 8410:     }
 8411: 
 8412: # Restrictions exist, deal with them
 8413: #
 8414: #   C:according to course preferences
 8415: #   R:according to resource settings
 8416: #   L:unless locked
 8417: #   X:according to user session state
 8418: #
 8419: 
 8420: # Possibly locked functionality, check all courses
 8421: # Locks might take effect only after 10 minutes cache expiration for other
 8422: # courses, and 2 minutes for current course
 8423: 
 8424:     my $envkey;
 8425:     if ($thisallowed=~/L/) {
 8426:         foreach $envkey (keys(%env)) {
 8427:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8428:                my $courseid=$2;
 8429:                my $roleid=$1.'.'.$2;
 8430:                $courseid=~s/^\///;
 8431:                my $expiretime=600;
 8432:                if ($env{'request.role'} eq $roleid) {
 8433: 		  $expiretime=120;
 8434:                }
 8435: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8436:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8437:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8438: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8439:                }
 8440:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8441:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8442: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8443:                        &log($env{'user.domain'},$env{'user.name'},
 8444:                             $env{'user.home'},
 8445:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8446:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8447:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8448: 		       return '';
 8449:                    }
 8450:                }
 8451:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8452:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8453: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8454:                        &log($env{'user.domain'},$env{'user.name'},
 8455:                             $env{'user.home'},
 8456:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8457:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8458:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8459: 		       return '';
 8460:                    }
 8461:                }
 8462: 	   }
 8463:        }
 8464:     }
 8465:    
 8466: #
 8467: # Rest of the restrictions depend on selected course
 8468: #
 8469: 
 8470:     unless ($env{'request.course.id'}) {
 8471: 	if ($thisallowed eq 'A') {
 8472: 	    return 'A';
 8473:         } elsif ($thisallowed eq 'B') {
 8474:             return 'B';
 8475: 	} else {
 8476: 	    return '1';
 8477: 	}
 8478:     }
 8479: 
 8480: #
 8481: # Now user is definitely in a course
 8482: #
 8483: 
 8484: 
 8485: # Course preferences
 8486: 
 8487:    if ($thisallowed=~/C/) {
 8488:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8489:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8490:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8491: 	   =~/\Q$rolecode\E/) {
 8492: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8493: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8494: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8495: 			$env{'request.course.id'});
 8496: 	   }
 8497:            return '';
 8498:        }
 8499: 
 8500:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8501: 	   =~/\Q$unamedom\E/) {
 8502: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8503: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8504: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8505: 			$env{'request.course.id'});
 8506: 	   }
 8507:            return '';
 8508:        }
 8509:    }
 8510: 
 8511: # Resource preferences
 8512: 
 8513:    if ($thisallowed=~/R/) {
 8514:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8515:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8516: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8517: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8518: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8519: 	   }
 8520: 	   return '';
 8521:        }
 8522:    }
 8523: 
 8524: # Restricted by state or randomout?
 8525: 
 8526:    if ($thisallowed=~/X/) {
 8527:       if ($env{'acc.randomout'}) {
 8528: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8529:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8530:             return ''; 
 8531:          }
 8532:       }
 8533:       if (&condval($statecond)) {
 8534: 	 return '2';
 8535:       } else {
 8536:          return '';
 8537:       }
 8538:    }
 8539: 
 8540:     if ($thisallowed eq 'A') {
 8541: 	return 'A';
 8542:     } elsif ($thisallowed eq 'B') {
 8543:         return 'B';
 8544:     } elsif ($thisallowed eq 'D') {
 8545:         return 'D';
 8546:     }
 8547:    return 'F';
 8548: }
 8549: 
 8550: # ------------------------------------------- Check construction space access
 8551: 
 8552: sub constructaccess {
 8553:     my ($url,$setpriv)=@_;
 8554: 
 8555: # We do not allow editing of previous versions of files
 8556:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8557: 
 8558: # Get username and domain from URL
 8559:     my ($ownername,$ownerdomain,$ownerhome);
 8560: 
 8561:     ($ownerdomain,$ownername) =
 8562:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8563: 
 8564: # The URL does not really point to any authorspace, forget it
 8565:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8566: 
 8567: # Now we need to see if the user has access to the authorspace of
 8568: # $ownername at $ownerdomain
 8569: 
 8570:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8571: # Real author for this?
 8572:        $ownerhome = $env{'user.home'};
 8573:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8574:           return ($ownername,$ownerdomain,$ownerhome);
 8575:        }
 8576:     } else {
 8577: # Co-author for this?
 8578:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8579:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8580:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8581:             return ($ownername,$ownerdomain,$ownerhome);
 8582:         }
 8583:         if ($env{'request.course.id'}) {
 8584:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8585:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8586:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8587:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8588:                     return ($ownername,$ownerdomain,$ownerhome);
 8589:                 }
 8590:             }
 8591:         }
 8592:     }
 8593: 
 8594: # We don't have any access right now. If we are not possibly going to do anything about this,
 8595: # we might as well leave
 8596:    unless ($setpriv) { return ''; }
 8597: 
 8598: # Backdoor access?
 8599:     my $allowed=&allowed('eco',$ownerdomain);
 8600: # Nope
 8601:     unless ($allowed) { return ''; }
 8602: # Looks like we may have access, but could be locked by the owner of the construction space
 8603:     if ($allowed eq 'U') {
 8604:         my %blocked=&get('environment',['domcoord.author'],
 8605:                          $ownerdomain,$ownername);
 8606: # Is blocked by owner
 8607:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8608:     }
 8609:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8610: # Grant temporary access
 8611:         my $then=$env{'user.login.time'};
 8612:         my $update=$env{'user.update.time'};
 8613:         if (!$update) { $update = $then; }
 8614:         my $refresh=$env{'user.refresh.time'};
 8615:         if (!$refresh) { $refresh = $update; }
 8616:         my $now = time;
 8617:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8618:                            $now,'ca','constructaccess');
 8619:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8620:         return($ownername,$ownerdomain,$ownerhome);
 8621:     }
 8622: # No business here
 8623:     return '';
 8624: }
 8625: 
 8626: # ----------------------------------------------------------- Content Blocking
 8627: 
 8628: {
 8629: # Caches for faster Course Contents display where content blocking
 8630: # is in operation (i.e., interval param set) for timed quiz.
 8631: #
 8632: # User for whom data are being temporarily cached.
 8633: my $cacheduser='';
 8634: # Cached blockers for this user (a hash of blocking items). 
 8635: my %cachedblockers=();
 8636: # When the data were last cached.
 8637: my $cachedlast='';
 8638: 
 8639: sub load_all_blockers {
 8640:     my ($uname,$udom,$blocks)=@_;
 8641:     if (($uname ne '') && ($udom ne '')) { 
 8642:         if (($cacheduser eq $uname.':'.$udom) &&
 8643:             (abs($cachedlast-time)<5)) {
 8644:             return;
 8645:         }
 8646:     }
 8647:     $cachedlast=time;
 8648:     $cacheduser=$uname.':'.$udom;
 8649:     %cachedblockers = &get_commblock_resources($blocks);
 8650: }
 8651: 
 8652: sub get_comm_blocks {
 8653:     my ($cdom,$cnum) = @_;
 8654:     if ($cdom eq '' || $cnum eq '') {
 8655:         return unless ($env{'request.course.id'});
 8656:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8657:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8658:     }
 8659:     my %commblocks;
 8660:     my $hashid=$cdom.'_'.$cnum;
 8661:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8662:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8663:         %commblocks = %{$blocksref};
 8664:     } else {
 8665:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8666:         my $cachetime = 600;
 8667:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8668:     }
 8669:     return %commblocks;
 8670: }
 8671: 
 8672: sub get_commblock_resources {
 8673:     my ($blocks) = @_;
 8674:     my %blockers = ();
 8675:     return %blockers unless ($env{'request.course.id'});
 8676:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8677:     my %commblocks;
 8678:     if (ref($blocks) eq 'HASH') {
 8679:         %commblocks = %{$blocks};
 8680:     } else {
 8681:         %commblocks = &get_comm_blocks();
 8682:     }
 8683:     return %blockers unless (keys(%commblocks) > 0); 
 8684:     my $navmap = Apache::lonnavmaps::navmap->new();
 8685:     return %blockers unless (ref($navmap));
 8686:     my $now = time;
 8687:     foreach my $block (keys(%commblocks)) {
 8688:         if ($block =~ /^(\d+)____(\d+)$/) {
 8689:             my ($start,$end) = ($1,$2);
 8690:             if ($start <= $now && $end >= $now) {
 8691:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8692:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8693:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8694:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8695:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8696:                             }
 8697:                         }
 8698:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8699:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8700:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8701:                             }
 8702:                         }
 8703:                     }
 8704:                 }
 8705:             }
 8706:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8707:             my $item = $1;
 8708:             my @to_test;
 8709:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8710:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8711:                     my @interval;
 8712:                     my $type = 'map';
 8713:                     if ($item eq 'course') {
 8714:                         $type = 'course';
 8715:                         @interval=&EXT("resource.0.interval");
 8716:                     } else {
 8717:                         if ($item =~ /___\d+___/) {
 8718:                             $type = 'resource';
 8719:                             @interval=&EXT("resource.0.interval",$item);
 8720:                             if (ref($navmap)) {                        
 8721:                                 my $res = $navmap->getBySymb($item); 
 8722:                                 push(@to_test,$res);
 8723:                             }
 8724:                         } else {
 8725:                             my $mapsymb = &symbread($item,1);
 8726:                             if ($mapsymb) {
 8727:                                 if (ref($navmap)) {
 8728:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8729:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8730:                                     foreach my $res (@to_test) {
 8731:                                         my $symb = $res->symb();
 8732:                                         next if ($symb eq $mapsymb);
 8733:                                         if ($symb ne '') {
 8734:                                             @interval=&EXT("resource.0.interval",$symb);
 8735:                                             if ($interval[1] eq 'map') {
 8736:                                                 last;
 8737:                                             }
 8738:                                         }
 8739:                                     }
 8740:                                 }
 8741:                             }
 8742:                         }
 8743:                     }
 8744:                     if ($interval[0] =~ /^(\d+)/) {
 8745:                         my $timelimit = $1; 
 8746:                         my $first_access;
 8747:                         if ($type eq 'resource') {
 8748:                             $first_access=&get_first_access($interval[1],$item);
 8749:                         } elsif ($type eq 'map') {
 8750:                             $first_access=&get_first_access($interval[1],undef,$item);
 8751:                         } else {
 8752:                             $first_access=&get_first_access($interval[1]);
 8753:                         }
 8754:                         if ($first_access) {
 8755:                             my $timesup = $first_access+$timelimit;
 8756:                             if ($timesup > $now) {
 8757:                                 my $activeblock;
 8758:                                 foreach my $res (@to_test) {
 8759:                                     if ($res->answerable()) {
 8760:                                         $activeblock = 1;
 8761:                                         last;
 8762:                                     }
 8763:                                 }
 8764:                                 if ($activeblock) {
 8765:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8766:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8767:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8768:                                          }
 8769:                                     }
 8770:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8771:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8772:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8773:                                         }
 8774:                                     }
 8775:                                 }
 8776:                             }
 8777:                         }
 8778:                     }
 8779:                 }
 8780:             }
 8781:         }
 8782:     }
 8783:     return %blockers;
 8784: }
 8785: 
 8786: sub has_comm_blocking {
 8787:     my ($priv,$symb,$uri,$blocks) = @_;
 8788:     my @blockers;
 8789:     return unless ($env{'request.course.id'});
 8790:     return unless ($priv eq 'bre');
 8791:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8792:     return if ($env{'request.state'} eq 'construct');
 8793:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8794:     return unless (keys(%cachedblockers) > 0);
 8795:     my (%possibles,@symbs);
 8796:     if (!$symb) {
 8797:         $symb = &symbread($uri,1,1,1,\%possibles);
 8798:     }
 8799:     if ($symb) {
 8800:         @symbs = ($symb);
 8801:     } elsif (keys(%possibles)) { 
 8802:         @symbs = keys(%possibles);
 8803:     }
 8804:     my $noblock;
 8805:     foreach my $symb (@symbs) {
 8806:         last if ($noblock);
 8807:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8808:         foreach my $block (keys(%cachedblockers)) {
 8809:             if ($block =~ /^firstaccess____(.+)$/) {
 8810:                 my $item = $1;
 8811:                 if (($item eq $map) || ($item eq $symb)) {
 8812:                     $noblock = 1;
 8813:                     last;
 8814:                 }
 8815:             }
 8816:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8817:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8818:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8819:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8820:                             push(@blockers,$block);
 8821:                         }
 8822:                     }
 8823:                 }
 8824:             }
 8825:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8826:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8827:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8828:                         push(@blockers,$block);
 8829:                     }
 8830:                 }
 8831:             }
 8832:         }
 8833:     }
 8834:     return if ($noblock);
 8835:     return @blockers;
 8836: }
 8837: }
 8838: 
 8839: sub deeplink_check {
 8840:     my ($priv,$symb,$uri) = @_;
 8841:     return unless ($env{'request.course.id'});
 8842:     return unless ($priv eq 'bre');
 8843:     return if ($env{'request.state'} eq 'construct');
 8844:     return if ($env{'request.role.adv'});
 8845:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8846:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8847:     my (%possibles,@symbs);
 8848:     if (!$symb) {
 8849:         $symb = &symbread($uri,1,1,1,\%possibles);
 8850:     }
 8851:     if ($symb) {
 8852:         @symbs = ($symb);
 8853:     } elsif (keys(%possibles)) {
 8854:         @symbs = keys(%possibles);
 8855:     }
 8856: 
 8857:     my ($login,$switchrole,$allow);
 8858:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8859:         my $key = $1;
 8860:         my $tinyurl;
 8861:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8862:         if (defined($cached)) {
 8863:              $tinyurl = $result;
 8864:         } else {
 8865:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8866:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8867:              if ($currtiny{$key} ne '') {
 8868:                  $tinyurl = $currtiny{$key};
 8869:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8870:              }
 8871:         }
 8872:         if ($tinyurl ne '') {
 8873:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 8874:             if ($cnumreq eq $cnum) {
 8875:                 $login = $posslogin;
 8876:             } else {
 8877:                 $switchrole = 1;
 8878:             }
 8879:         }
 8880:     }
 8881:     foreach my $symb (@symbs) {
 8882:         last if ($allow);
 8883:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8884:         if ($deeplink eq '') {
 8885:             $allow = 1;
 8886:         } else {
 8887:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 8888:             if ($access eq 'any') {
 8889:                 $allow = 1;
 8890:             } elsif ($login) {
 8891:                 if ($access eq 'only') {
 8892:                     if ($scope eq 'res') {
 8893:                         if ($symb eq $login) {
 8894:                             $allow = 1;
 8895:                         }
 8896:                     } elsif ($scope eq 'map') {
 8897: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 8898:                     } elsif ($scope eq 'rec') {
 8899: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 8900:                     }
 8901:                 } else {
 8902:                     my ($acctype,$item) = split(/:/,$access);
 8903:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 8904:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 8905:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8906:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 8907:                                 $allow = 1;
 8908:                             }
 8909:                         }
 8910:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 8911:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 8912:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8913:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 8914:                                 $allow = 1;
 8915:                             }
 8916:                         }
 8917:                     }
 8918:                 }
 8919:             }
 8920:         }
 8921:     }
 8922:     return if ($allow);
 8923:     return 1;
 8924: }
 8925: 
 8926: # -------------------------------- Deversion and split uri into path an filename   
 8927: 
 8928: #
 8929: #   Removes the version from a URI and
 8930: #   splits it in to its filename and path to the filename.
 8931: #   Seems like File::Basename could have done this more clearly.
 8932: #   Parameters:
 8933: #      $uri   - input URI
 8934: #   Returns:
 8935: #     Two element list consisting of 
 8936: #     $pathname  - the URI up to and excluding the trailing /
 8937: #     $filename  - The part of the URI following the last /
 8938: #  NOTE:
 8939: #    Another realization of this is simply:
 8940: #    use File::Basename;
 8941: #    ...
 8942: #    $uri = shift;
 8943: #    $filename = basename($uri);
 8944: #    $path     = dirname($uri);
 8945: #    return ($filename, $path);
 8946: #
 8947: #     The implementation below is probably faster however.
 8948: #
 8949: sub split_uri_for_cond {
 8950:     my $uri=&deversion(&declutter(shift));
 8951:     my @uriparts=split(/\//,$uri);
 8952:     my $filename=pop(@uriparts);
 8953:     my $pathname=join('/',@uriparts);
 8954:     return ($pathname,$filename);
 8955: }
 8956: # --------------------------------------------------- Is a resource on the map?
 8957: 
 8958: sub is_on_map {
 8959:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8960:     #Trying to find the conditional for the file
 8961:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8962: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8963:     if ($match) {
 8964: 	return (1,$1);
 8965:     } else {
 8966: 	return (0,0);
 8967:     }
 8968: }
 8969: 
 8970: # --------------------------------------------------------- Get symb from alias
 8971: 
 8972: sub get_symb_from_alias {
 8973:     my $symb=shift;
 8974:     my ($map,$resid,$url)=&decode_symb($symb);
 8975: # Already is a symb
 8976:     if ($url) { return $symb; }
 8977: # Must be an alias
 8978:     my $aliassymb='';
 8979:     my %bighash;
 8980:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8981:                             &GDBM_READER(),0640)) {
 8982:         my $rid=$bighash{'mapalias_'.$symb};
 8983: 	if ($rid) {
 8984: 	    my ($mapid,$resid)=split(/\./,$rid);
 8985: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8986: 				    $resid,$bighash{'src_'.$rid});
 8987: 	}
 8988:         untie %bighash;
 8989:     }
 8990:     return $aliassymb;
 8991: }
 8992: 
 8993: # ----------------------------------------------------------------- Define Role
 8994: 
 8995: sub definerole {
 8996:   if (allowed('mcr','/')) {
 8997:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8998:     foreach my $role (split(':',$sysrole)) {
 8999: 	my ($crole,$cqual)=split(/\&/,$role);
 9000:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9001:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9002: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9003:                return "refused:s:$crole&$cqual"; 
 9004:             }
 9005:         }
 9006:     }
 9007:     foreach my $role (split(':',$domrole)) {
 9008: 	my ($crole,$cqual)=split(/\&/,$role);
 9009:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9010:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9011: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9012:                return "refused:d:$crole&$cqual"; 
 9013:             }
 9014:         }
 9015:     }
 9016:     foreach my $role (split(':',$courole)) {
 9017: 	my ($crole,$cqual)=split(/\&/,$role);
 9018:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9019:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9020: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9021:                return "refused:c:$crole&$cqual"; 
 9022:             }
 9023:         }
 9024:     }
 9025:     my $uhome;
 9026:     if (($uname ne '') && ($udom ne '')) {
 9027:         $uhome = &homeserver($uname,$udom);
 9028:         return $uhome if ($uhome eq 'no_host');
 9029:     } else {
 9030:         $uname = $env{'user.name'};
 9031:         $udom = $env{'user.domain'};
 9032:         $uhome = $env{'user.home'};
 9033:     }
 9034:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9035:                 "$udom:$uname:rolesdef_$rolename=".
 9036:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9037:     return reply($command,$uhome);
 9038:   } else {
 9039:     return 'refused';
 9040:   }
 9041: }
 9042: 
 9043: # ---------------- Make a metadata query against the network of library servers
 9044: 
 9045: sub metadata_query {
 9046:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9047:     my %rhash;
 9048:     my %libserv = &all_library();
 9049:     my @server_list = (defined($server_array) ? @$server_array
 9050:                                               : keys(%libserv) );
 9051:     for my $server (@server_list) {
 9052:         my $domains = ''; 
 9053:         if (ref($domains_hash) eq 'HASH') {
 9054:             $domains = $domains_hash->{$server}; 
 9055:         }
 9056: 	unless ($custom or $customshow) {
 9057: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9058: 	    $rhash{$server}=$reply;
 9059: 	}
 9060: 	else {
 9061: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9062: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9063: 			     $server);
 9064: 	    $rhash{$server}=$reply;
 9065: 	}
 9066:     }
 9067:     return \%rhash;
 9068: }
 9069: 
 9070: # ----------------------------------------- Send log queries and wait for reply
 9071: 
 9072: sub log_query {
 9073:     my ($uname,$udom,$query,%filters)=@_;
 9074:     my $uhome=&homeserver($uname,$udom);
 9075:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9076:     my $uhost=&hostname($uhome);
 9077:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9078:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9079:                        $uhome);
 9080:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9081:     return get_query_reply($queryid);
 9082: }
 9083: 
 9084: # -------------------------- Update MySQL table for portfolio file
 9085: 
 9086: sub update_portfolio_table {
 9087:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9088:     if ($group ne '') {
 9089:         $file_name =~s /^\Q$group\E//;
 9090:     }
 9091:     my $homeserver = &homeserver($uname,$udom);
 9092:     my $queryid=
 9093:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9094:                ':'.&escape($file_name).':'.$action,$homeserver);
 9095:     my $reply = &get_query_reply($queryid);
 9096:     return $reply;
 9097: }
 9098: 
 9099: # -------------------------- Update MySQL allusers table
 9100: 
 9101: sub update_allusers_table {
 9102:     my ($uname,$udom,$names) = @_;
 9103:     my $homeserver = &homeserver($uname,$udom);
 9104:     my $queryid=
 9105:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9106:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9107:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9108:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9109:                'generation='.&escape($names->{'generation'}).'%%'.
 9110:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9111:                'id='.&escape($names->{'id'}),$homeserver);
 9112:     return;
 9113: }
 9114: 
 9115: # ------- Request retrieval of institutional classlists for course(s)
 9116: 
 9117: sub fetch_enrollment_query {
 9118:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9119:     my ($homeserver,$sleep,$loopmax);
 9120:     my $maxtries = 1;
 9121:     if ($context eq 'automated') {
 9122:         $homeserver = $perlvar{'lonHostID'};
 9123:         $sleep = 2;
 9124:         $loopmax = 100;
 9125:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9126:     } else {
 9127:         $homeserver = &homeserver($cnum,$dom);
 9128:     }
 9129:     my $host=&hostname($homeserver);
 9130:     my $cmd = '';
 9131:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9132:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9133:     }
 9134:     $cmd =~ s/%%$//;
 9135:     $cmd = &escape($cmd);
 9136:     my $query = 'fetchenrollment';
 9137:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9138:     unless ($queryid=~/^\Q$host\E\_/) { 
 9139:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9140:         return 'error: '.$queryid;
 9141:     }
 9142:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9143:     my $tries = 1;
 9144:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9145:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9146:         $tries ++;
 9147:     }
 9148:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9149:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9150:     } else {
 9151:         my @responses = split(/:/,$reply);
 9152:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9153:             foreach my $line (@responses) {
 9154:                 my ($key,$value) = split(/=/,$line,2);
 9155:                 $$replyref{$key} = $value;
 9156:             }
 9157:         } else {
 9158:             my $pathname = LONCAPA::tempdir();
 9159:             foreach my $line (@responses) {
 9160:                 my ($key,$value) = split(/=/,$line);
 9161:                 $$replyref{$key} = $value;
 9162:                 if ($value > 0) {
 9163:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9164:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9165:                         my $destname = $pathname.'/'.$filename;
 9166:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9167:                         if ($xml_classlist =~ /^error/) {
 9168:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9169:                         } else {
 9170:                             if ( open(FILE,">",$destname) ) {
 9171:                                 print FILE &unescape($xml_classlist);
 9172:                                 close(FILE);
 9173:                             } else {
 9174:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9175:                             }
 9176:                         }
 9177:                     }
 9178:                 }
 9179:             }
 9180:         }
 9181:         return 'ok';
 9182:     }
 9183:     return 'error';
 9184: }
 9185: 
 9186: sub get_query_reply {
 9187:     my ($queryid,$sleep,$loopmax) = @_;;
 9188:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9189:         $sleep = 0.2;
 9190:     }
 9191:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9192:         $loopmax = 100;
 9193:     }
 9194:     my $replyfile=LONCAPA::tempdir().$queryid;
 9195:     my $reply='';
 9196:     for (1..$loopmax) {
 9197: 	sleep($sleep);
 9198:         if (-e $replyfile.'.end') {
 9199: 	    if (open(my $fh,"<",$replyfile)) {
 9200: 		$reply = join('',<$fh>);
 9201: 		close($fh);
 9202: 	   } else { return 'error: reply_file_error'; }
 9203:            return &unescape($reply);
 9204: 	}
 9205:     }
 9206:     return 'timeout:'.$queryid;
 9207: }
 9208: 
 9209: sub courselog_query {
 9210: #
 9211: # possible filters:
 9212: # url: url or symb
 9213: # username
 9214: # domain
 9215: # action: view, submit, grade
 9216: # start: timestamp
 9217: # end: timestamp
 9218: #
 9219:     my (%filters)=@_;
 9220:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9221:     if ($filters{'url'}) {
 9222: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9223:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9224:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9225:     }
 9226:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9227:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9228:     return &log_query($cname,$cdom,'courselog',%filters);
 9229: }
 9230: 
 9231: sub userlog_query {
 9232: #
 9233: # possible filters:
 9234: # action: log check role
 9235: # start: timestamp
 9236: # end: timestamp
 9237: #
 9238:     my ($uname,$udom,%filters)=@_;
 9239:     return &log_query($uname,$udom,'userlog',%filters);
 9240: }
 9241: 
 9242: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9243: 
 9244: sub auto_run {
 9245:     my ($cnum,$cdom) = @_;
 9246:     my $response = 0;
 9247:     my $settings;
 9248:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9249:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9250:         $settings = $domconfig{'autoenroll'};
 9251:         if ($settings->{'run'} eq '1') {
 9252:             $response = 1;
 9253:         }
 9254:     } else {
 9255:         my $homeserver;
 9256:         if (&is_course($cdom,$cnum)) {
 9257:             $homeserver = &homeserver($cnum,$cdom);
 9258:         } else {
 9259:             $homeserver = &domain($cdom,'primary');
 9260:         }
 9261:         if ($homeserver ne 'no_host') {
 9262:             $response = &reply('autorun:'.$cdom,$homeserver);
 9263:         }
 9264:     }
 9265:     return $response;
 9266: }
 9267: 
 9268: sub auto_get_sections {
 9269:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9270:     my $homeserver;
 9271:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9272:         $homeserver = &homeserver($cnum,$cdom);
 9273:     }
 9274:     if (!defined($homeserver)) { 
 9275:         if ($cdom =~ /^$match_domain$/) {
 9276:             $homeserver = &domain($cdom,'primary');
 9277:         }
 9278:     }
 9279:     my @secs;
 9280:     if (defined($homeserver)) {
 9281:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9282:         unless ($response eq 'refused') {
 9283:             @secs = split(/:/,$response);
 9284:         }
 9285:     }
 9286:     return @secs;
 9287: }
 9288: 
 9289: sub auto_new_course {
 9290:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9291:     my $homeserver = &homeserver($cnum,$cdom);
 9292:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9293:     return $response;
 9294: }
 9295: 
 9296: sub auto_validate_courseID {
 9297:     my ($cnum,$cdom,$inst_course_id) = @_;
 9298:     my $homeserver = &homeserver($cnum,$cdom);
 9299:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9300:     return $response;
 9301: }
 9302: 
 9303: sub auto_validate_instcode {
 9304:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9305:     my ($homeserver,$response);
 9306:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9307:         $homeserver = &homeserver($cnum,$cdom);
 9308:     }
 9309:     if (!defined($homeserver)) {
 9310:         if ($cdom =~ /^$match_domain$/) {
 9311:             $homeserver = &domain($cdom,'primary');
 9312:         }
 9313:     }
 9314:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9315:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9316:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9317:     return ($outcome,$description,$defaultcredits);
 9318: }
 9319: 
 9320: sub auto_create_password {
 9321:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9322:     my ($homeserver,$response);
 9323:     my $create_passwd = 0;
 9324:     my $authchk = '';
 9325:     if ($udom =~ /^$match_domain$/) {
 9326:         $homeserver = &domain($udom,'primary');
 9327:     }
 9328:     if ($homeserver eq '') {
 9329:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9330:             $homeserver = &homeserver($cnum,$cdom);
 9331:         }
 9332:     }
 9333:     if ($homeserver eq '') {
 9334:         $authchk = 'nodomain';
 9335:     } else {
 9336:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9337:         if ($response eq 'refused') {
 9338:             $authchk = 'refused';
 9339:         } else {
 9340:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9341:         }
 9342:     }
 9343:     return ($authparam,$create_passwd,$authchk);
 9344: }
 9345: 
 9346: sub auto_photo_permission {
 9347:     my ($cnum,$cdom,$students) = @_;
 9348:     my $homeserver = &homeserver($cnum,$cdom);
 9349:     my ($outcome,$perm_reqd,$conditions) = 
 9350: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9351:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9352: 	return (undef,undef);
 9353:     }
 9354:     return ($outcome,$perm_reqd,$conditions);
 9355: }
 9356: 
 9357: sub auto_checkphotos {
 9358:     my ($uname,$udom,$pid) = @_;
 9359:     my $homeserver = &homeserver($uname,$udom);
 9360:     my ($result,$resulttype);
 9361:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9362: 				   &escape($uname).':'.&escape($pid),
 9363: 				   $homeserver));
 9364:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9365: 	return (undef,undef);
 9366:     }
 9367:     if ($outcome) {
 9368:         ($result,$resulttype) = split(/:/,$outcome);
 9369:     } 
 9370:     return ($result,$resulttype);
 9371: }
 9372: 
 9373: sub auto_photochoice {
 9374:     my ($cnum,$cdom) = @_;
 9375:     my $homeserver = &homeserver($cnum,$cdom);
 9376:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9377: 						       &escape($cdom),
 9378: 						       $homeserver)));
 9379:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9380: 	return (undef,undef);
 9381:     }
 9382:     return ($update,$comment);
 9383: }
 9384: 
 9385: sub auto_photoupdate {
 9386:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9387:     my $homeserver = &homeserver($cnum,$dom);
 9388:     my $host=&hostname($homeserver);
 9389:     my $cmd = '';
 9390:     my $maxtries = 1;
 9391:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9392:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9393:     }
 9394:     $cmd =~ s/%%$//;
 9395:     $cmd = &escape($cmd);
 9396:     my $query = 'institutionalphotos';
 9397:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9398:     unless ($queryid=~/^\Q$host\E\_/) {
 9399:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9400:         return 'error: '.$queryid;
 9401:     }
 9402:     my $reply = &get_query_reply($queryid);
 9403:     my $tries = 1;
 9404:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9405:         $reply = &get_query_reply($queryid);
 9406:         $tries ++;
 9407:     }
 9408:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9409:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9410:     } else {
 9411:         my @responses = split(/:/,$reply);
 9412:         my $outcome = shift(@responses); 
 9413:         foreach my $item (@responses) {
 9414:             my ($key,$value) = split(/=/,$item);
 9415:             $$photo{$key} = $value;
 9416:         }
 9417:         return $outcome;
 9418:     }
 9419:     return 'error';
 9420: }
 9421: 
 9422: sub auto_instcode_format {
 9423:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9424: 	$cat_order) = @_;
 9425:     my $courses = '';
 9426:     my @homeservers;
 9427:     if ($caller eq 'global') {
 9428: 	my %servers = &get_servers($codedom,'library');
 9429: 	foreach my $tryserver (keys(%servers)) {
 9430: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9431: 		push(@homeservers,$tryserver);
 9432: 	    }
 9433:         }
 9434:     } elsif ($caller eq 'requests') {
 9435:         if ($codedom =~ /^$match_domain$/) {
 9436:             my $chome = &domain($codedom,'primary');
 9437:             unless ($chome eq 'no_host') {
 9438:                 push(@homeservers,$chome);
 9439:             }
 9440:         }
 9441:     } else {
 9442:         push(@homeservers,&homeserver($caller,$codedom));
 9443:     }
 9444:     foreach my $code (keys(%{$instcodes})) {
 9445:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9446:     }
 9447:     chop($courses);
 9448:     my $ok_response = 0;
 9449:     my $response;
 9450:     while (@homeservers > 0 && $ok_response == 0) {
 9451:         my $server = shift(@homeservers); 
 9452:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9453:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9454:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9455: 		split(/:/,$response);
 9456:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9457:             push(@{$codetitles},&str2array($codetitles_str));
 9458:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9459:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9460:             $ok_response = 1;
 9461:         }
 9462:     }
 9463:     if ($ok_response) {
 9464:         return 'ok';
 9465:     } else {
 9466:         return $response;
 9467:     }
 9468: }
 9469: 
 9470: sub auto_instcode_defaults {
 9471:     my ($domain,$returnhash,$code_order) = @_;
 9472:     my @homeservers;
 9473: 
 9474:     my %servers = &get_servers($domain,'library');
 9475:     foreach my $tryserver (keys(%servers)) {
 9476: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9477: 	    push(@homeservers,$tryserver);
 9478: 	}
 9479:     }
 9480: 
 9481:     my $response;
 9482:     foreach my $server (@homeservers) {
 9483:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9484:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9485: 	
 9486: 	foreach my $pair (split(/\&/,$response)) {
 9487: 	    my ($name,$value)=split(/\=/,$pair);
 9488: 	    if ($name eq 'code_order') {
 9489: 		@{$code_order} = split(/\&/,&unescape($value));
 9490: 	    } else {
 9491: 		$returnhash->{&unescape($name)}=&unescape($value);
 9492: 	    }
 9493: 	}
 9494: 	return 'ok';
 9495:     }
 9496: 
 9497:     return $response;
 9498: }
 9499: 
 9500: sub auto_possible_instcodes {
 9501:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9502:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9503:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9504:         return;
 9505:     }
 9506:     my (@homeservers,$uhome);
 9507:     if (defined(&domain($domain,'primary'))) {
 9508:         $uhome=&domain($domain,'primary');
 9509:         push(@homeservers,&domain($domain,'primary'));
 9510:     } else {
 9511:         my %servers = &get_servers($domain,'library');
 9512:         foreach my $tryserver (keys(%servers)) {
 9513:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9514:                 push(@homeservers,$tryserver);
 9515:             }
 9516:         }
 9517:     }
 9518:     my $response;
 9519:     foreach my $server (@homeservers) {
 9520:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9521:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9522:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9523:             split(':',$response);
 9524:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9525:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9526:         foreach my $item (split('&',$cat_title)) {   
 9527:             my ($name,$value)=split('=',$item);
 9528:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9529:         }
 9530:         foreach my $item (split('&',$cat_order)) {
 9531:             my ($name,$value)=split('=',$item);
 9532:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9533:         }
 9534:         return 'ok';
 9535:     }
 9536:     return $response;
 9537: }
 9538: 
 9539: sub auto_courserequest_checks {
 9540:     my ($dom) = @_;
 9541:     my ($homeserver,%validations);
 9542:     if ($dom =~ /^$match_domain$/) {
 9543:         $homeserver = &domain($dom,'primary');
 9544:     }
 9545:     unless ($homeserver eq 'no_host') {
 9546:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9547:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9548:             my @items = split(/&/,$response);
 9549:             foreach my $item (@items) {
 9550:                 my ($key,$value) = split('=',$item);
 9551:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9552:             }
 9553:         }
 9554:     }
 9555:     return %validations; 
 9556: }
 9557: 
 9558: sub auto_courserequest_validation {
 9559:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9560:     my ($homeserver,$response);
 9561:     if ($dom =~ /^$match_domain$/) {
 9562:         $homeserver = &domain($dom,'primary');
 9563:     }
 9564:     unless ($homeserver eq 'no_host') {
 9565:         my $customdata;
 9566:         if (ref($custominfo) eq 'HASH') {
 9567:             $customdata = &freeze_escape($custominfo);
 9568:         }
 9569:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9570:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9571:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9572:                                     $customdata,$homeserver));
 9573:     }
 9574:     return $response;
 9575: }
 9576: 
 9577: sub auto_validate_class_sec {
 9578:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9579:     my $homeserver = &homeserver($cnum,$cdom);
 9580:     my $ownerlist;
 9581:     if (ref($owners) eq 'ARRAY') {
 9582:         $ownerlist = join(',',@{$owners});
 9583:     } else {
 9584:         $ownerlist = $owners;
 9585:     }
 9586:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9587:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9588:     return $response;
 9589: }
 9590: 
 9591: sub auto_validate_instclasses {
 9592:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9593:     my ($homeserver,%validations);
 9594:     $homeserver = &homeserver($cnum,$cdom);
 9595:     unless ($homeserver eq 'no_host') {
 9596:         my $ownerlist;
 9597:         if (ref($owners) eq 'ARRAY') {
 9598:             $ownerlist = join(',',@{$owners});
 9599:         } else {
 9600:             $ownerlist = $owners;
 9601:         }
 9602:         if (ref($classesref) eq 'HASH') {
 9603:             my $classes = &freeze_escape($classesref);
 9604:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9605:                                 ':'.$cdom.':'.$classes,$homeserver);
 9606:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9607:                 my @items = split(/&/,$response);
 9608:                 foreach my $item (@items) {
 9609:                     my ($key,$value) = split('=',$item);
 9610:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9611:                 }
 9612:             }
 9613:         }
 9614:     }
 9615:     return %validations;
 9616: }
 9617: 
 9618: sub auto_crsreq_update {
 9619:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9620:         $code,$accessstart,$accessend,$inbound) = @_;
 9621:     my ($homeserver,%crsreqresponse);
 9622:     if ($cdom =~ /^$match_domain$/) {
 9623:         $homeserver = &domain($cdom,'primary');
 9624:     }
 9625:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9626:         my $info;
 9627:         if (ref($inbound) eq 'HASH') {
 9628:             $info = &freeze_escape($inbound);
 9629:         }
 9630:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9631:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9632:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9633:                             &escape($title).':'.&escape($code).':'.
 9634:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9635:                             $homeserver);
 9636:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9637:             my @items = split(/&/,$response);
 9638:             foreach my $item (@items) {
 9639:                 my ($key,$value) = split('=',$item);
 9640:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9641:             }
 9642:         }
 9643:     }
 9644:     return \%crsreqresponse;
 9645: }
 9646: 
 9647: sub auto_export_grades {
 9648:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9649:     my ($homeserver,%exportresponse);
 9650:     if ($cdom =~ /^$match_domain$/) {
 9651:         $homeserver = &domain($cdom,'primary');
 9652:     }
 9653:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9654:         my $info;
 9655:         if (ref($inforef) eq 'HASH') {
 9656:             $info = &freeze_escape($inforef);
 9657:         }
 9658:         if (ref($gradesref) eq 'HASH') {
 9659:             my $grades = &freeze_escape($gradesref);
 9660:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9661:                                 $info.':'.$grades,$homeserver);
 9662:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9663:                 my @items = split(/&/,$response);
 9664:                 foreach my $item (@items) {
 9665:                     my ($key,$value) = split('=',$item);
 9666:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9667:                 }
 9668:             }
 9669:         }
 9670:     }
 9671:     return \%exportresponse;
 9672: }
 9673: 
 9674: sub check_instcode_cloning {
 9675:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9676:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9677:         return;
 9678:     }
 9679:     my $canclone;
 9680:     if (@{$code_order} > 0) {
 9681:         my $instcoderegexp ='^';
 9682:         my @clonecodes = split(/\&/,$cloner);
 9683:         foreach my $item (@{$code_order}) {
 9684:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9685:                 foreach my $pair (@clonecodes) {
 9686:                     my ($key,$val) = split(/\=/,$pair,2);
 9687:                     $val = &unescape($val);
 9688:                     if ($key eq $item) {
 9689:                         $instcoderegexp .= '('.$val.')';
 9690:                         last;
 9691:                     }
 9692:                 }
 9693:             } else {
 9694:                 $instcoderegexp .= $codedefaults->{$item};
 9695:             }
 9696:         }
 9697:         $instcoderegexp .= '$';
 9698:         my (@from,@to);
 9699:         eval {
 9700:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9701:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9702:         };
 9703:         if ((@from > 0) && (@to > 0)) {
 9704:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9705:             if (!@diffs) {
 9706:                 $canclone = 1;
 9707:             }
 9708:         }
 9709:     }
 9710:     return $canclone;
 9711: }
 9712: 
 9713: sub default_instcode_cloning {
 9714:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9715:     my (%codedefaults,@code_order,$canclone);
 9716:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9717:         %codedefaults = %{$codedefaultsref};
 9718:         @code_order = @{$codeorderref};
 9719:     } elsif ($clonedom) {
 9720:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9721:     }
 9722:     if (($domdefclone) && (@code_order)) {
 9723:         my @clonecodes = split(/\+/,$domdefclone);
 9724:         my $instcoderegexp ='^';
 9725:         foreach my $item (@code_order) {
 9726:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9727:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9728:             } else {
 9729:                 $instcoderegexp .= $codedefaults{$item};
 9730:             }
 9731:         }
 9732:         $instcoderegexp .= '$';
 9733:         my (@from,@to);
 9734:         eval {
 9735:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9736:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9737:         };
 9738:         if ((@from > 0) && (@to > 0)) {
 9739:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9740:             if (!@diffs) {
 9741:                 $canclone = 1;
 9742:             }
 9743:         }
 9744:     }
 9745:     return $canclone;
 9746: }
 9747: 
 9748: # ------------------------------------------------------- Course Group routines
 9749: 
 9750: sub get_coursegroups {
 9751:     my ($cdom,$cnum,$group,$namespace) = @_;
 9752:     return(&dump($namespace,$cdom,$cnum,$group));
 9753: }
 9754: 
 9755: sub modify_coursegroup {
 9756:     my ($cdom,$cnum,$groupsettings) = @_;
 9757:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9758: }
 9759: 
 9760: sub toggle_coursegroup_status {
 9761:     my ($cdom,$cnum,$group,$action) = @_;
 9762:     my ($from_namespace,$to_namespace);
 9763:     if ($action eq 'delete') {
 9764:         $from_namespace = 'coursegroups';
 9765:         $to_namespace = 'deleted_groups';
 9766:     } else {
 9767:         $from_namespace = 'deleted_groups';
 9768:         $to_namespace = 'coursegroups';
 9769:     }
 9770:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9771:     if (my $tmp = &error(%curr_group)) {
 9772:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9773:         return ('read error',$tmp);
 9774:     } else {
 9775:         my %savedsettings = %curr_group; 
 9776:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9777:         my $deloutcome;
 9778:         if ($result eq 'ok') {
 9779:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9780:         } else {
 9781:             return ('write error',$result);
 9782:         }
 9783:         if ($deloutcome eq 'ok') {
 9784:             return 'ok';
 9785:         } else {
 9786:             return ('delete error',$deloutcome);
 9787:         }
 9788:     }
 9789: }
 9790: 
 9791: sub modify_group_roles {
 9792:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9793:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9794:     my $role = 'gr/'.&escape($userprivs);
 9795:     my ($uname,$udom) = split(/:/,$user);
 9796:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9797:     if ($result eq 'ok') {
 9798:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9799:     }
 9800:     return $result;
 9801: }
 9802: 
 9803: sub modify_coursegroup_membership {
 9804:     my ($cdom,$cnum,$membership) = @_;
 9805:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9806:     return $result;
 9807: }
 9808: 
 9809: sub get_active_groups {
 9810:     my ($udom,$uname,$cdom,$cnum) = @_;
 9811:     my $now = time;
 9812:     my %groups = ();
 9813:     foreach my $key (keys(%env)) {
 9814:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9815:             my ($start,$end) = split(/\./,$env{$key});
 9816:             if (($end!=0) && ($end<$now)) { next; }
 9817:             if (($start!=0) && ($start>$now)) { next; }
 9818:             if ($1 eq $cdom && $2 eq $cnum) {
 9819:                 $groups{$3} = $env{$key} ;
 9820:             }
 9821:         }
 9822:     }
 9823:     return %groups;
 9824: }
 9825: 
 9826: sub get_group_membership {
 9827:     my ($cdom,$cnum,$group) = @_;
 9828:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9829: }
 9830: 
 9831: sub get_users_groups {
 9832:     my ($udom,$uname,$courseid) = @_;
 9833:     my @usersgroups;
 9834:     my $cachetime=1800;
 9835: 
 9836:     my $hashid="$udom:$uname:$courseid";
 9837:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9838:     if (defined($cached)) {
 9839:         @usersgroups = split(/:/,$grouplist);
 9840:     } else {  
 9841:         $grouplist = '';
 9842:         my $courseurl = &courseid_to_courseurl($courseid);
 9843:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9844:         my $access_end = $env{'course.'.$courseid.
 9845:                               '.default_enrollment_end_date'};
 9846:         my $now = time;
 9847:         foreach my $key (keys(%roleshash)) {
 9848:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9849:                 my $group = $1;
 9850:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9851:                     my $start = $2;
 9852:                     my $end = $1;
 9853:                     if ($start == -1) { next; } # deleted from group
 9854:                     if (($start!=0) && ($start>$now)) { next; }
 9855:                     if (($end!=0) && ($end<$now)) {
 9856:                         if ($access_end && $access_end < $now) {
 9857:                             if ($access_end - $end < 86400) {
 9858:                                 push(@usersgroups,$group);
 9859:                             }
 9860:                         }
 9861:                         next;
 9862:                     }
 9863:                     push(@usersgroups,$group);
 9864:                 }
 9865:             }
 9866:         }
 9867:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9868:         $grouplist = join(':',@usersgroups);
 9869:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9870:     }
 9871:     return @usersgroups;
 9872: }
 9873: 
 9874: sub devalidate_getgroups_cache {
 9875:     my ($udom,$uname,$cdom,$cnum)=@_;
 9876:     my $courseid = $cdom.'_'.$cnum;
 9877: 
 9878:     my $hashid="$udom:$uname:$courseid";
 9879:     &devalidate_cache_new('getgroups',$hashid);
 9880: }
 9881: 
 9882: # ------------------------------------------------------------------ Plain Text
 9883: 
 9884: sub plaintext {
 9885:     my ($short,$type,$cid,$forcedefault) = @_;
 9886:     if ($short =~ m{^cr/}) {
 9887: 	return (split('/',$short))[-1];
 9888:     }
 9889:     if (!defined($cid)) {
 9890:         $cid = $env{'request.course.id'};
 9891:     }
 9892:     my %rolenames = (
 9893:                       Course    => 'std',
 9894:                       Community => 'alt1',
 9895:                       Placement => 'std',
 9896:                     );
 9897:     if ($cid ne '') {
 9898:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9899:             unless ($forcedefault) {
 9900:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9901:                 &Apache::lonlocal::mt_escape(\$roletext);
 9902:                 return &Apache::lonlocal::mt($roletext);
 9903:             }
 9904:         }
 9905:     }
 9906:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9907:         (defined($rolenames{$type})) && 
 9908:         (defined($prp{$short}{$rolenames{$type}}))) {
 9909:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9910:     } elsif ($cid ne '') {
 9911:         my $crstype = $env{'course.'.$cid.'.type'};
 9912:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9913:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9914:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9915:         }
 9916:     }
 9917:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9918: }
 9919: 
 9920: # ----------------------------------------------------------------- Assign Role
 9921: 
 9922: sub assignrole {
 9923:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9924:         $context)=@_;
 9925:     my $mrole;
 9926:     if ($role =~ /^cr\//) {
 9927:         my $cwosec=$url;
 9928:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9929: 	unless (&allowed('ccr',$cwosec)) {
 9930:            my $refused = 1;
 9931:            if ($context eq 'requestcourses') {
 9932:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9933:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9934:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9935:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9936:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9937:                            if ($crsenv{'internal.courseowner'} eq
 9938:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9939:                                $refused = '';
 9940:                            }
 9941:                        }
 9942:                    }
 9943:                }
 9944:            }
 9945:            if ($refused) {
 9946:                &logthis('Refused custom assignrole: '.
 9947:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9948:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9949:                return 'refused';
 9950:            }
 9951:         }
 9952:         $mrole='cr';
 9953:     } elsif ($role =~ /^gr\//) {
 9954:         my $cwogrp=$url;
 9955:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9956:         unless (&allowed('mdg',$cwogrp)) {
 9957:             &logthis('Refused group assignrole: '.
 9958:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9959:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9960:             return 'refused';
 9961:         }
 9962:         $mrole='gr';
 9963:     } else {
 9964:         my $cwosec=$url;
 9965:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9966:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9967:             my $refused;
 9968:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9969:                 if (!(&allowed('c'.$role,$url))) {
 9970:                     $refused = 1;
 9971:                 }
 9972:             } else {
 9973:                 $refused = 1;
 9974:             }
 9975:             if ($refused) {
 9976:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9977:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9978:                     my %crsenv;
 9979:                     if ($role eq 'cc' || $role eq 'co') {
 9980:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9981:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9982:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9983:                                 if ($crsenv{'internal.courseowner'} eq 
 9984:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9985:                                     $refused = '';
 9986:                                 }
 9987:                             }
 9988:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9989:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9990:                                 if ($crsenv{'internal.courseowner'} eq 
 9991:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9992:                                     $refused = '';
 9993:                                 }
 9994:                             }
 9995:                         }
 9996:                     }
 9997:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9998:                     if ($role eq 'st') {
 9999:                         $refused = '';
10000:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10001:                         $refused = '';
10002:                     }
10003:                 } elsif ($context eq 'requestcourses') {
10004:                     my @possroles = ('st','ta','ep','in','cc','co');
10005:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10006:                         my $wrongcc;
10007:                         if ($cnum =~ /^$match_community$/) {
10008:                             $wrongcc = 1 if ($role eq 'cc');
10009:                         } else {
10010:                             $wrongcc = 1 if ($role eq 'co');
10011:                         }
10012:                         unless ($wrongcc) {
10013:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10014:                             if ($crsenv{'internal.courseowner'} eq 
10015:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10016:                                 $refused = '';
10017:                             }
10018:                         }
10019:                     }
10020:                 } elsif ($context eq 'requestauthor') {
10021:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10022:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10023:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10024:                             $refused = '';
10025:                         } else {
10026:                             my %domdefaults = &get_domain_defaults($udom);
10027:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10028:                                 my $checkbystatus;
10029:                                 if ($env{'user.adv'}) { 
10030:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10031:                                     if ($disposition eq 'automatic') {
10032:                                         $refused = '';
10033:                                     } elsif ($disposition eq '') {
10034:                                         $checkbystatus = 1;
10035:                                     } 
10036:                                 } else {
10037:                                     $checkbystatus = 1;
10038:                                 }
10039:                                 if ($checkbystatus) {
10040:                                     if ($env{'environment.inststatus'}) {
10041:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10042:                                         foreach my $type (@inststatuses) {
10043:                                             if (($type ne '') &&
10044:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10045:                                                 $refused = '';
10046:                                             }
10047:                                         }
10048:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10049:                                         $refused = '';
10050:                                     }
10051:                                 }
10052:                             }
10053:                         }
10054:                     }
10055:                 }
10056:                 if ($refused) {
10057:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10058:                              ' '.$role.' '.$end.' '.$start.' by '.
10059: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10060:                     return 'refused';
10061:                 }
10062:             }
10063:         } elsif ($role eq 'au') {
10064:             if ($url ne '/'.$udom.'/') {
10065:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10066:                          ' to assign author role for '.$uname.':'.$udom.
10067:                          ' in domain: '.$url.' refused (wrong domain).');
10068:                 return 'refused';
10069:             }
10070:         }
10071:         $mrole=$role;
10072:     }
10073:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10074:                 "$udom:$uname:$url".'_'."$mrole=$role";
10075:     if ($end) { $command.='_'.$end; }
10076:     if ($start) {
10077: 	if ($end) { 
10078:            $command.='_'.$start; 
10079:         } else {
10080:            $command.='_0_'.$start;
10081:         }
10082:     }
10083:     my $origstart = $start;
10084:     my $origend = $end;
10085:     my $delflag;
10086: # actually delete
10087:     if ($deleteflag) {
10088: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10089: # modify command to delete the role
10090:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10091:                 "$udom:$uname:$url".'_'."$mrole";
10092: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10093: # set start and finish to negative values for userrolelog
10094:            $start=-1;
10095:            $end=-1;
10096:            $delflag = 1;
10097:         }
10098:     }
10099: # send command
10100:     my $answer=&reply($command,&homeserver($uname,$udom));
10101: # log new user role if status is ok
10102:     if ($answer eq 'ok') {
10103: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10104:         if (($role eq 'cc') || ($role eq 'in') ||
10105:             ($role eq 'ep') || ($role eq 'ad') ||
10106:             ($role eq 'ta') || ($role eq 'st') ||
10107:             ($role=~/^cr/) || ($role eq 'gr') ||
10108:             ($role eq 'co')) {
10109: # for course roles, perform group memberships changes triggered by role change.
10110:             unless ($role =~ /^gr/) {
10111:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10112:                                                  $origstart,$selfenroll,$context);
10113:             }
10114:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10115:                            $selfenroll,$context);
10116:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10117:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10118:                  ($role eq 'da')) {
10119:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10120:                            $context);
10121:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10122:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10123:                              $context); 
10124:         }
10125:         if ($role eq 'cc') {
10126:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10127:         }
10128:     }
10129:     return $answer;
10130: }
10131: 
10132: sub autoupdate_coowners {
10133:     my ($url,$end,$start,$uname,$udom) = @_;
10134:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10135:     if (($cdom ne '') && ($cnum ne '')) {
10136:         my $now = time;
10137:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10138:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10139:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10140:             my $instcode = $coursehash{'internal.coursecode'};
10141:             if ($instcode ne '') {
10142:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10143:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10144:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10145:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10146:                         if ($result eq 'valid') {
10147:                             if ($coursehash{'internal.co-owners'}) {
10148:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10149:                                     push(@newcoowners,$coowner);
10150:                                 }
10151:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10152:                                     push(@newcoowners,$uname.':'.$udom);
10153:                                 }
10154:                                 @newcoowners = sort(@newcoowners);
10155:                             } else {
10156:                                 push(@newcoowners,$uname.':'.$udom);
10157:                             }
10158:                         } else {
10159:                             if ($coursehash{'internal.co-owners'}) {
10160:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10161:                                     unless ($coowner eq $uname.':'.$udom) {
10162:                                         push(@newcoowners,$coowner);
10163:                                     }
10164:                                 }
10165:                                 unless (@newcoowners > 0) {
10166:                                     $delcoowners = 1;
10167:                                     $coowners = '';
10168:                                 }
10169:                             }
10170:                         }
10171:                         if (@newcoowners || $delcoowners) {
10172:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10173:                                             $delcoowners,@newcoowners);
10174:                         }
10175:                     }
10176:                 }
10177:             }
10178:         }
10179:     }
10180: }
10181: 
10182: sub store_coowners {
10183:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10184:     my $cid = $cdom.'_'.$cnum;
10185:     my ($coowners,$delresult,$putresult);
10186:     if (@newcoowners) {
10187:         $coowners = join(',',@newcoowners);
10188:         my %coownershash = (
10189:                             'internal.co-owners' => $coowners,
10190:                            );
10191:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10192:         if ($putresult eq 'ok') {
10193:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10194:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10195:             }
10196:         }
10197:     }
10198:     if ($delcoowners) {
10199:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10200:         if ($delresult eq 'ok') {
10201:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10202:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10203:             }
10204:         }
10205:     }
10206:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10207:         my %crsinfo =
10208:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10209:         if (ref($crsinfo{$cid}) eq 'HASH') {
10210:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10211:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10212:         }
10213:     }
10214: }
10215: 
10216: # -------------------------------------------------- Modify user authentication
10217: # Overrides without validation
10218: 
10219: sub modifyuserauth {
10220:     my ($udom,$uname,$umode,$upass)=@_;
10221:     my $uhome=&homeserver($uname,$udom);
10222:     my $allowed;
10223:     if (&allowed('mau',$udom)) {
10224:         $allowed = 1;
10225:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10226:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10227:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10228:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10229:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10230:         if (($cdom ne '') && ($cnum ne '')) {
10231:             my $is_owner = &is_course_owner($cdom,$cnum);
10232:             if ($is_owner) {
10233:                 $allowed = 1;
10234:             }
10235:         }
10236:     }
10237:     unless ($allowed) { return 'refused'; }
10238:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10239:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10240:              ' in domain '.$env{'request.role.domain'});  
10241:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10242: 		     &escape($upass),$uhome);
10243:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10244:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10245:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10246:     &log($udom,,$uname,$uhome,
10247:         'Authentication changed by '.$env{'user.domain'}.', '.
10248:                                      $env{'user.name'}.', '.$umode.
10249:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10250:     unless ($reply eq 'ok') {
10251:         &logthis('Authentication mode error: '.$reply);
10252: 	return 'error: '.$reply;
10253:     }   
10254:     return 'ok';
10255: }
10256: 
10257: # --------------------------------------------------------------- Modify a user
10258: 
10259: sub modifyuser {
10260:     my ($udom,    $uname, $uid,
10261:         $umode,   $upass, $first,
10262:         $middle,  $last,  $gene,
10263:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10264:     $udom= &LONCAPA::clean_domain($udom);
10265:     $uname=&LONCAPA::clean_username($uname);
10266:     my $showcandelete = 'none';
10267:     if (ref($candelete) eq 'ARRAY') {
10268:         if (@{$candelete} > 0) {
10269:             $showcandelete = join(', ',@{$candelete});
10270:         }
10271:     }
10272:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10273:              $umode.', '.$first.', '.$middle.', '.
10274: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10275:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10276:                                      ' desiredhome not specified'). 
10277:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10278:              ' in domain '.$env{'request.role.domain'});
10279:     my $uhome=&homeserver($uname,$udom,'true');
10280:     my $newuser;
10281:     if ($uhome eq 'no_host') {
10282:         $newuser = 1;
10283:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10284:                 ($umode eq 'lti')) {
10285:             return 'error: more information needed to create new user';
10286:         }
10287:     }
10288: # ----------------------------------------------------------------- Create User
10289:     if (($uhome eq 'no_host') && 
10290: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10291:         my $unhome='';
10292:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10293:             $unhome = $desiredhome;
10294: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10295: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10296:         } else { # load balancing routine for determining $unhome
10297:             my $loadm=10000000;
10298: 	    my %servers = &get_servers($udom,'library');
10299: 	    foreach my $tryserver (keys(%servers)) {
10300: 		my $answer=reply('load',$tryserver);
10301: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10302: 		    $loadm=$answer;
10303: 		    $unhome=$tryserver;
10304: 		}
10305: 	    }
10306:         }
10307:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10308: 	    return 'error: unable to find a home server for '.$uname.
10309:                    ' in domain '.$udom;
10310:         }
10311:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10312:                          &escape($upass),$unhome);
10313: 	unless ($reply eq 'ok') {
10314:             return 'error: '.$reply;
10315:         }   
10316:         $uhome=&homeserver($uname,$udom,'true');
10317:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10318: 	    return 'error: unable verify users home machine.';
10319:         }
10320:     }   # End of creation of new user
10321: # ---------------------------------------------------------------------- Add ID
10322:     if ($uid) {
10323:        $uid=~tr/A-Z/a-z/;
10324:        my %uidhash=&idrget($udom,$uname);
10325:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10326:          && (!$forceid)) {
10327: 	  unless ($uid eq $uidhash{$uname}) {
10328: 	      return 'error: user id "'.$uid.'" does not match '.
10329:                   'current user id "'.$uidhash{$uname}.'".';
10330:           }
10331:        } else {
10332: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10333:        }
10334:     }
10335: # -------------------------------------------------------------- Add names, etc
10336:     my @tmp=&get('environment',
10337: 		   ['firstname','middlename','lastname','generation','id',
10338:                     'permanentemail','inststatus'],
10339: 		   $udom,$uname);
10340:     my (%names,%oldnames);
10341:     if ($tmp[0] =~ m/^error:.*/) { 
10342:         %names=(); 
10343:     } else {
10344:         %names = @tmp;
10345:         %oldnames = %names;
10346:     }
10347: #
10348: # If name, email and/or uid are blank (e.g., because an uploaded file
10349: # of users did not contain them), do not overwrite existing values
10350: # unless field is in $candelete array ref.  
10351: #
10352: 
10353:     my @fields = ('firstname','middlename','lastname','generation',
10354:                   'permanentemail','id');
10355:     my %newvalues;
10356:     if (ref($candelete) eq 'ARRAY') {
10357:         foreach my $field (@fields) {
10358:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10359:                 if ($field eq 'firstname') {
10360:                     $names{$field} = $first;
10361:                 } elsif ($field eq 'middlename') {
10362:                     $names{$field} = $middle;
10363:                 } elsif ($field eq 'lastname') {
10364:                     $names{$field} = $last;
10365:                 } elsif ($field eq 'generation') { 
10366:                     $names{$field} = $gene;
10367:                 } elsif ($field eq 'permanentemail') {
10368:                     $names{$field} = $email;
10369:                 } elsif ($field eq 'id') {
10370:                     $names{$field}  = $uid;
10371:                 }
10372:             }
10373:         }
10374:     }
10375:     if ($first)  { $names{'firstname'}  = $first; }
10376:     if (defined($middle)) { $names{'middlename'} = $middle; }
10377:     if ($last)   { $names{'lastname'}   = $last; }
10378:     if (defined($gene))   { $names{'generation'} = $gene; }
10379:     if ($email) {
10380:        $email=~s/[^\w\@\.\-\,]//gs;
10381:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10382:     }
10383:     if ($uid) { $names{'id'}  = $uid; }
10384:     if (defined($inststatus)) {
10385:         $names{'inststatus'} = '';
10386:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10387:         if (ref($usertypes) eq 'HASH') {
10388:             my @okstatuses; 
10389:             foreach my $item (split(/:/,$inststatus)) {
10390:                 if (defined($usertypes->{$item})) {
10391:                     push(@okstatuses,$item);  
10392:                 }
10393:             }
10394:             if (@okstatuses) {
10395:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10396:             }
10397:         }
10398:     }
10399:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10400:                  $umode.', '.$first.', '.$middle.', '.
10401:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10402:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10403:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10404:     } else {
10405:         $logmsg .= ' during self creation';
10406:     }
10407:     my $changed;
10408:     if ($newuser) {
10409:         $changed = 1;
10410:     } else {
10411:         foreach my $field (@fields) {
10412:             if ($names{$field} ne $oldnames{$field}) {
10413:                 $changed = 1;
10414:                 last;
10415:             }
10416:         }
10417:     }
10418:     unless ($changed) {
10419:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10420:         &logthis($logmsg);
10421:         return 'ok';
10422:     }
10423:     my $reply = &put('environment', \%names, $udom,$uname);
10424:     if ($reply ne 'ok') { 
10425:         return 'error: '.$reply;
10426:     }
10427:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10428:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10429:     }
10430:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10431:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10432:     $logmsg = 'Success modifying user '.$logmsg;
10433:     &logthis($logmsg);
10434:     return 'ok';
10435: }
10436: 
10437: # -------------------------------------------------------------- Modify student
10438: 
10439: sub modifystudent {
10440:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10441:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10442:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10443:     if (!$cid) {
10444: 	unless ($cid=$env{'request.course.id'}) {
10445: 	    return 'not_in_class';
10446: 	}
10447:     }
10448: # --------------------------------------------------------------- Make the user
10449:     my $reply=&modifyuser
10450: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10451:          $desiredhome,$email,$inststatus);
10452:     unless ($reply eq 'ok') { return $reply; }
10453:     # This will cause &modify_student_enrollment to get the uid from the
10454:     # student's environment
10455:     $uid = undef if (!$forceid);
10456:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10457:                                         $gene,$usec,$end,$start,$type,$locktype,
10458:                                         $cid,$selfenroll,$context,$credits,$instsec);
10459:     return $reply;
10460: }
10461: 
10462: sub modify_student_enrollment {
10463:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10464:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10465:     my ($cdom,$cnum,$chome);
10466:     if (!$cid) {
10467: 	unless ($cid=$env{'request.course.id'}) {
10468: 	    return 'not_in_class';
10469: 	}
10470: 	$cdom=$env{'course.'.$cid.'.domain'};
10471: 	$cnum=$env{'course.'.$cid.'.num'};
10472:     } else {
10473: 	($cdom,$cnum)=split(/_/,$cid);
10474:     }
10475:     $chome=$env{'course.'.$cid.'.home'};
10476:     if (!$chome) {
10477: 	$chome=&homeserver($cnum,$cdom);
10478:     }
10479:     if (!$chome) { return 'unknown_course'; }
10480:     # Make sure the user exists
10481:     my $uhome=&homeserver($uname,$udom);
10482:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10483: 	return 'error: no such user';
10484:     }
10485:     # Get student data if we were not given enough information
10486:     if (!defined($first)  || $first  eq '' || 
10487:         !defined($last)   || $last   eq '' || 
10488:         !defined($uid)    || $uid    eq '' || 
10489:         !defined($middle) || $middle eq '' || 
10490:         !defined($gene)   || $gene   eq '') {
10491:         # They did not supply us with enough data to enroll the student, so
10492:         # we need to pick up more information.
10493:         my %tmp = &get('environment',
10494:                        ['firstname','middlename','lastname', 'generation','id']
10495:                        ,$udom,$uname);
10496: 
10497:         #foreach my $key (keys(%tmp)) {
10498:         #    &logthis("key $key = ".$tmp{$key});
10499:         #}
10500:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10501:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10502:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10503:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10504:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10505:     }
10506:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10507:     my $user = "$uname:$udom";
10508:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10509:     my $reply=cput('classlist',
10510: 		   {$user => 
10511: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10512: 		   $cdom,$cnum);
10513:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10514:         &devalidate_getsection_cache($udom,$uname,$cid);
10515:     } else { 
10516: 	return 'error: '.$reply;
10517:     }
10518:     # Add student role to user
10519:     my $uurl='/'.$cid;
10520:     $uurl=~s/\_/\//g;
10521:     if ($usec) {
10522: 	$uurl.='/'.$usec;
10523:     }
10524:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10525:                              $selfenroll,$context);
10526:     if ($result ne 'ok') {
10527:         if ($old_entry{$user} ne '') {
10528:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10529:         } else {
10530:             $reply = &del('classlist',[$user],$cdom,$cnum);
10531:         }
10532:     }
10533:     return $result; 
10534: }
10535: 
10536: sub format_name {
10537:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10538:     my $name;
10539:     if ($first ne 'lastname') {
10540: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10541:     } else {
10542: 	if ($lastname=~/\S/) {
10543: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10544: 	    $name=~s/\s+,/,/;
10545: 	} else {
10546: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10547: 	}
10548:     }
10549:     $name=~s/^\s+//;
10550:     $name=~s/\s+$//;
10551:     $name=~s/\s+/ /g;
10552:     return $name;
10553: }
10554: 
10555: # ------------------------------------------------- Write to course preferences
10556: 
10557: sub writecoursepref {
10558:     my ($courseid,%prefs)=@_;
10559:     $courseid=~s/^\///;
10560:     $courseid=~s/\_/\//g;
10561:     my ($cdomain,$cnum)=split(/\//,$courseid);
10562:     my $chome=homeserver($cnum,$cdomain);
10563:     if (($chome eq '') || ($chome eq 'no_host')) { 
10564: 	return 'error: no such course';
10565:     }
10566:     my $cstring='';
10567:     foreach my $pref (keys(%prefs)) {
10568: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10569:     }
10570:     $cstring=~s/\&$//;
10571:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10572: }
10573: 
10574: # ---------------------------------------------------------- Make/modify course
10575: 
10576: sub createcourse {
10577:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10578:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10579:     $url=&declutter($url);
10580:     my $cid='';
10581:     if ($context eq 'requestcourses') {
10582:         my $can_create = 0;
10583:         my ($ownername,$ownerdom) = split(':',$course_owner);
10584:         if ($udom eq $ownerdom) {
10585:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10586:                                   $context)) {
10587:                 $can_create = 1;
10588:             }
10589:         } else {
10590:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10591:                                            $category);
10592:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10593:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10594:                 if (@curr > 0) {
10595:                     my @options = qw(approval validate autolimit);
10596:                     my $optregex = join('|',@options);
10597:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10598:                         $can_create = 1;
10599:                     }
10600:                 }
10601:             }
10602:         }
10603:         if ($can_create) {
10604:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10605:                 unless (&allowed('ccc',$udom)) {
10606:                     return 'refused'; 
10607:                 }
10608:             }
10609:         } else {
10610:             return 'refused';
10611:         }
10612:     } elsif (!&allowed('ccc',$udom)) {
10613:         return 'refused';
10614:     }
10615: # --------------------------------------------------------------- Get Unique ID
10616:     my $uname;
10617:     if ($cnum =~ /^$match_courseid$/) {
10618:         my $chome=&homeserver($cnum,$udom,'true');
10619:         if (($chome eq '') || ($chome eq 'no_host')) {
10620:             $uname = $cnum;
10621:         } else {
10622:             $uname = &generate_coursenum($udom,$crstype);
10623:         }
10624:     } else {
10625:         $uname = &generate_coursenum($udom,$crstype);
10626:     }
10627:     return $uname if ($uname =~ /^error/);
10628: # -------------------------------------------------- Check supplied server name
10629:     if (!defined($course_server)) {
10630:         if (defined(&domain($udom,'primary'))) {
10631:             $course_server = &domain($udom,'primary');
10632:         } else {
10633:             $course_server = $env{'user.home'}; 
10634:         }
10635:     }
10636:     my %host_servers =
10637:         &Apache::lonnet::get_servers($udom,'library');
10638:     unless ($host_servers{$course_server}) {
10639:         return 'error: invalid home server for course: '.$course_server;
10640:     }
10641: # ------------------------------------------------------------- Make the course
10642:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10643:                       $course_server);
10644:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10645:     my $uhome=&homeserver($uname,$udom,'true');
10646:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10647: 	return 'error: no such course';
10648:     }
10649: # ----------------------------------------------------------------- Course made
10650: # log existence
10651:     my $now = time;
10652:     my $newcourse = {
10653:                     $udom.'_'.$uname => {
10654:                                      description => $description,
10655:                                      inst_code   => $inst_code,
10656:                                      owner       => $course_owner,
10657:                                      type        => $crstype,
10658:                                      creator     => $env{'user.name'}.':'.
10659:                                                     $env{'user.domain'},
10660:                                      created     => $now,
10661:                                      context     => $context,
10662:                                                 },
10663:                     };
10664:     &courseidput($udom,$newcourse,$uhome,'notime');
10665: # set toplevel url
10666:     my $topurl=$url;
10667:     unless ($nonstandard) {
10668: # ------------------------------------------ For standard courses, make top url
10669:         my $mapurl=&clutter($url);
10670:         if ($mapurl eq '/res/') { $mapurl=''; }
10671:         $env{'form.initmap'}=(<<ENDINITMAP);
10672: <map>
10673: <resource id="1" type="start"></resource>
10674: <resource id="2" src="$mapurl"></resource>
10675: <resource id="3" type="finish"></resource>
10676: <link index="1" from="1" to="2"></link>
10677: <link index="2" from="2" to="3"></link>
10678: </map>
10679: ENDINITMAP
10680:         $topurl=&declutter(
10681:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10682:                           );
10683:     }
10684: # ----------------------------------------------------------- Write preferences
10685:     &writecoursepref($udom.'_'.$uname,
10686:                      ('description'              => $description,
10687:                       'url'                      => $topurl,
10688:                       'internal.creator'         => $env{'user.name'}.':'.
10689:                                                     $env{'user.domain'},
10690:                       'internal.created'         => $now,
10691:                       'internal.creationcontext' => $context)
10692:                     );
10693:     return '/'.$udom.'/'.$uname;
10694: }
10695: 
10696: # ------------------------------------------------------------------- Create ID
10697: sub generate_coursenum {
10698:     my ($udom,$crstype) = @_;
10699:     my $domdesc = &domain($udom);
10700:     return 'error: invalid domain' if ($domdesc eq '');
10701:     my $first;
10702:     if ($crstype eq 'Community') {
10703:         $first = '0';
10704:     } else {
10705:         $first = int(1+rand(9)); 
10706:     } 
10707:     my $uname=$first.
10708:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10709:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10710:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10711: # ----------------------------------------------- Make sure that does not exist
10712:     my $uhome=&homeserver($uname,$udom,'true');
10713:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10714:         if ($crstype eq 'Community') {
10715:             $first = '0';
10716:         } else {
10717:             $first = int(1+rand(9));
10718:         }
10719:         $uname=$first.
10720:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10721:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10722:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10723:         $uhome=&homeserver($uname,$udom,'true');
10724:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10725:             return 'error: unable to generate unique course-ID';
10726:         }
10727:     }
10728:     return $uname;
10729: }
10730: 
10731: sub is_course {
10732:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10733:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10734: 
10735:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10736:     my $uhome=&homeserver($cnum,$cdom);
10737:     my $iscourse;
10738:     if (grep { $_ eq $uhome } current_machine_ids()) {
10739:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10740:     } else {
10741:         my $hashid = $cdom.':'.$cnum;
10742:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10743:         unless (defined($cached)) {
10744:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10745:                                         $cnum,undef,undef,'.');
10746:             $iscourse = 0;
10747:             if (exists($courses{$cdom.'_'.$cnum})) {
10748:                 $iscourse = 1;
10749:             }
10750:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10751:         }
10752:     }
10753:     return unless ($iscourse);
10754:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10755: }
10756: 
10757: sub store_userdata {
10758:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10759:     my $result;
10760:     if ($datakey ne '') {
10761:         if (ref($storehash) eq 'HASH') {
10762:             if ($udom eq '' || $uname eq '') {
10763:                 $udom = $env{'user.domain'};
10764:                 $uname = $env{'user.name'};
10765:             }
10766:             my $uhome=&homeserver($uname,$udom);
10767:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10768:                 $result = 'error: no_host';
10769:             } else {
10770:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10771:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10772: 
10773:                 my $namevalue='';
10774:                 foreach my $key (keys(%{$storehash})) {
10775:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10776:                 }
10777:                 $namevalue=~s/\&$//;
10778:                 unless ($namespace eq 'courserequests') {
10779:                     $datakey = &escape($datakey);
10780:                 }
10781:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10782:                                   $namevalue,$uhome);
10783:             }
10784:         } else {
10785:             $result = 'error: data to store was not a hash reference'; 
10786:         }
10787:     } else {
10788:         $result= 'error: invalid requestkey'; 
10789:     }
10790:     return $result;
10791: }
10792: 
10793: # ---------------------------------------------------------- Assign Custom Role
10794: 
10795: sub assigncustomrole {
10796:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10797:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10798:                        $end,$start,$deleteflag,$selfenroll,$context);
10799: }
10800: 
10801: # ----------------------------------------------------------------- Revoke Role
10802: 
10803: sub revokerole {
10804:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10805:     my $now=time;
10806:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10807: }
10808: 
10809: # ---------------------------------------------------------- Revoke Custom Role
10810: 
10811: sub revokecustomrole {
10812:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10813:     my $now=time;
10814:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10815:            $deleteflag,$selfenroll,$context);
10816: }
10817: 
10818: # ------------------------------------------------------------ Disk usage
10819: sub diskusage {
10820:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10821:     $directorypath =~ s/\/$//;
10822:     my $listing=&reply('du2:'.&escape($directorypath).':'
10823:                        .&escape($getpropath).':'.&escape($uname).':'
10824:                        .&escape($udom),homeserver($uname,$udom));
10825:     if ($listing eq 'unknown_cmd') {
10826:         if ($getpropath) {
10827:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10828:         }
10829:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10830:     }
10831:     return $listing;
10832: }
10833: 
10834: sub is_locked {
10835:     my ($file_name, $domain, $user, $which) = @_;
10836:     my @check;
10837:     my $is_locked;
10838:     push (@check,$file_name);
10839:     my %locked = &get('file_permissions',\@check,
10840: 		      $env{'user.domain'},$env{'user.name'});
10841:     my ($tmp)=keys(%locked);
10842:     if ($tmp=~/^error:/) { undef(%locked); }
10843:     
10844:     if (ref($locked{$file_name}) eq 'ARRAY') {
10845:         $is_locked = 'false';
10846:         foreach my $entry (@{$locked{$file_name}}) {
10847:            if (ref($entry) eq 'ARRAY') {
10848:                $is_locked = 'true';
10849:                if (ref($which) eq 'ARRAY') {
10850:                    push(@{$which},$entry);
10851:                } else {
10852:                    last;
10853:                }
10854:            }
10855:        }
10856:     } else {
10857:         $is_locked = 'false';
10858:     }
10859:     return $is_locked;
10860: }
10861: 
10862: sub declutter_portfile {
10863:     my ($file) = @_;
10864:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10865:     return $file;
10866: }
10867: 
10868: # ------------------------------------------------------------- Mark as Read Only
10869: 
10870: sub mark_as_readonly {
10871:     my ($domain,$user,$files,$what) = @_;
10872:     my %current_permissions = &dump('file_permissions',$domain,$user);
10873:     my ($tmp)=keys(%current_permissions);
10874:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10875:     foreach my $file (@{$files}) {
10876: 	$file = &declutter_portfile($file);
10877:         push(@{$current_permissions{$file}},$what);
10878:     }
10879:     &put('file_permissions',\%current_permissions,$domain,$user);
10880:     return;
10881: }
10882: 
10883: # ------------------------------------------------------------Save Selected Files
10884: 
10885: sub save_selected_files {
10886:     my ($user, $path, @files) = @_;
10887:     my $filename = $user."savedfiles";
10888:     my @other_files = &files_not_in_path($user, $path);
10889:     open (OUT,'>',LONCAPA::tempdir().$filename);
10890:     foreach my $file (@files) {
10891:         print (OUT $env{'form.currentpath'}.$file."\n");
10892:     }
10893:     foreach my $file (@other_files) {
10894:         print (OUT $file."\n");
10895:     }
10896:     close (OUT);
10897:     return 'ok';
10898: }
10899: 
10900: sub clear_selected_files {
10901:     my ($user) = @_;
10902:     my $filename = $user."savedfiles";
10903:     open (OUT,'>',LONCAPA::tempdir().$filename);
10904:     print (OUT undef);
10905:     close (OUT);
10906:     return ("ok");    
10907: }
10908: 
10909: sub files_in_path {
10910:     my ($user, $path) = @_;
10911:     my $filename = $user."savedfiles";
10912:     my %return_files;
10913:     open (IN,'<',LONCAPA::tempdir().$filename);
10914:     while (my $line_in = <IN>) {
10915:         chomp ($line_in);
10916:         my @paths_and_file = split (m!/!, $line_in);
10917:         my $file_part = pop (@paths_and_file);
10918:         my $path_part = join ('/', @paths_and_file);
10919:         $path_part.='/';
10920:         my $path_and_file = $path_part.$file_part;
10921:         if ($path_part eq $path) {
10922:             $return_files{$file_part}= 'selected';
10923:         }
10924:     }
10925:     close (IN);
10926:     return (\%return_files);
10927: }
10928: 
10929: # called in portfolio select mode, to show files selected NOT in current directory
10930: sub files_not_in_path {
10931:     my ($user, $path) = @_;
10932:     my $filename = $user."savedfiles";
10933:     my @return_files;
10934:     my $path_part;
10935:     open(IN, '<',LONCAPA::tempdir().$filename);
10936:     while (my $line = <IN>) {
10937:         #ok, I know it's clunky, but I want it to work
10938:         my @paths_and_file = split(m|/|, $line);
10939:         my $file_part = pop(@paths_and_file);
10940:         chomp($file_part);
10941:         my $path_part = join('/', @paths_and_file);
10942:         $path_part .= '/';
10943:         my $path_and_file = $path_part.$file_part;
10944:         if ($path_part ne $path) {
10945:             push(@return_files, ($path_and_file));
10946:         }
10947:     }
10948:     close(OUT);
10949:     return (@return_files);
10950: }
10951: 
10952: #------------------------------Submitted/Handedback Portfolio Files Versioning
10953:  
10954: sub portfiles_versioning {
10955:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10956:     my $portfolio_root = '/userfiles/portfolio';
10957:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10958:     foreach my $file (@{$portfiles}) {
10959:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10960:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10961:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10962:         my $getpropath = 1;
10963:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10964:                                              $stu_name,$getpropath);
10965:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10966:         my $new_answer = 
10967:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10968:         if ($new_answer ne 'problem getting file') {
10969:             push(@{$versioned_portfiles}, $directory.$new_answer);
10970:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10971:                               [$symb,$env{'request.course.id'},'graded']);
10972:         }
10973:     }
10974: }
10975: 
10976: sub get_next_version {
10977:     my ($answer_name, $answer_ext, $dir_list) = @_;
10978:     my $version;
10979:     if (ref($dir_list) eq 'ARRAY') {
10980:         foreach my $row (@{$dir_list}) {
10981:             my ($file) = split(/\&/,$row,2);
10982:             my ($file_name,$file_version,$file_ext) =
10983:                 &file_name_version_ext($file);
10984:             if (($file_name eq $answer_name) &&
10985:                 ($file_ext eq $answer_ext)) {
10986:                      # gets here if filename and extension match,
10987:                      # regardless of version
10988:                 if ($file_version ne '') {
10989:                     # a versioned file is found  so save it for later
10990:                     if ($file_version > $version) {
10991:                         $version = $file_version;
10992:                     }
10993:                 }
10994:             }
10995:         }
10996:     }
10997:     $version ++;
10998:     return($version);
10999: }
11000: 
11001: sub version_selected_portfile {
11002:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11003:     my ($answer_name,$answer_ver,$answer_ext) =
11004:         &file_name_version_ext($file_name);
11005:     my $new_answer;
11006:     $env{'form.copy'} =
11007:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11008:     if($env{'form.copy'} eq '-1') {
11009:         $new_answer = 'problem getting file';
11010:     } else {
11011:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11012:         my $copy_result = 
11013:             &finishuserfileupload($stu_name,$domain,'copy',
11014:                                   '/portfolio'.$directory.$new_answer);
11015:     }
11016:     undef($env{'form.copy'});
11017:     return ($new_answer);
11018: }
11019: 
11020: sub file_name_version_ext {
11021:     my ($file)=@_;
11022:     my @file_parts = split(/\./, $file);
11023:     my ($name,$version,$ext);
11024:     if (@file_parts > 1) {
11025:         $ext=pop(@file_parts);
11026:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11027:             $version=pop(@file_parts);
11028:         }
11029:         $name=join('.',@file_parts);
11030:     } else {
11031:         $name=join('.',@file_parts);
11032:     }
11033:     return($name,$version,$ext);
11034: }
11035: 
11036: #----------------------------------------------Get portfolio file permissions
11037: 
11038: sub get_portfile_permissions {
11039:     my ($domain,$user) = @_;
11040:     my %current_permissions = &dump('file_permissions',$domain,$user);
11041:     my ($tmp)=keys(%current_permissions);
11042:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11043:     return \%current_permissions;
11044: }
11045: 
11046: #---------------------------------------------Get portfolio file access controls
11047: 
11048: sub get_access_controls {
11049:     my ($current_permissions,$group,$file) = @_;
11050:     my %access;
11051:     my $real_file = $file;
11052:     $file =~ s/\.meta$//;
11053:     if (defined($file)) {
11054:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11055:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11056:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11057:             }
11058:         }
11059:     } else {
11060:         foreach my $key (keys(%{$current_permissions})) {
11061:             if ($key =~ /\0accesscontrol$/) {
11062:                 if (defined($group)) {
11063:                     if ($key !~ m-^\Q$group\E/-) {
11064:                         next;
11065:                     }
11066:                 }
11067:                 my ($fullpath) = split(/\0/,$key);
11068:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11069:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11070:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11071:                     }
11072:                 }
11073:             }
11074:         }
11075:     }
11076:     return %access;
11077: }
11078: 
11079: sub modify_access_controls {
11080:     my ($file_name,$changes,$domain,$user)=@_;
11081:     my ($outcome,$deloutcome);
11082:     my %store_permissions;
11083:     my %new_values;
11084:     my %new_control;
11085:     my %translation;
11086:     my @deletions = ();
11087:     my $now = time;
11088:     if (exists($$changes{'activate'})) {
11089:         if (ref($$changes{'activate'}) eq 'HASH') {
11090:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11091:             my $numnew = scalar(@newitems);
11092:             for (my $i=0; $i<$numnew; $i++) {
11093:                 my $newkey = $newitems[$i];
11094:                 my $newid = &Apache::loncommon::get_cgi_id();
11095:                 if ($newkey =~ /^\d+:/) { 
11096:                     $newkey =~ s/^(\d+)/$newid/;
11097:                     $translation{$1} = $newid;
11098:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11099:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11100:                     $translation{$1} = $newid;
11101:                 }
11102:                 $new_values{$file_name."\0".$newkey} = 
11103:                                           $$changes{'activate'}{$newitems[$i]};
11104:                 $new_control{$newkey} = $now;
11105:             }
11106:         }
11107:     }
11108:     my %todelete;
11109:     my %changed_items;
11110:     foreach my $action ('delete','update') {
11111:         if (exists($$changes{$action})) {
11112:             if (ref($$changes{$action}) eq 'HASH') {
11113:                 foreach my $key (keys(%{$$changes{$action}})) {
11114:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11115:                     if ($action eq 'delete') { 
11116:                         $todelete{$itemnum} = 1;
11117:                     } else {
11118:                         $changed_items{$itemnum} = $key;
11119:                     }
11120:                 }
11121:             }
11122:         }
11123:     }
11124:     # get lock on access controls for file.
11125:     my $lockhash = {
11126:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11127:                                                        ':'.$env{'user.domain'},
11128:                    }; 
11129:     my $tries = 0;
11130:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11131:    
11132:     while (($gotlock ne 'ok') && $tries < 10) {
11133:         $tries ++;
11134:         sleep(0.1);
11135:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11136:     }
11137:     if ($gotlock eq 'ok') {
11138:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11139:         my ($tmp)=keys(%curr_permissions);
11140:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11141:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11142:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11143:             if (ref($curr_controls) eq 'HASH') {
11144:                 foreach my $control_item (keys(%{$curr_controls})) {
11145:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11146:                     if (defined($todelete{$itemnum})) {
11147:                         push(@deletions,$file_name."\0".$control_item);
11148:                     } else {
11149:                         if (defined($changed_items{$itemnum})) {
11150:                             $new_control{$changed_items{$itemnum}} = $now;
11151:                             push(@deletions,$file_name."\0".$control_item);
11152:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11153:                         } else {
11154:                             $new_control{$control_item} = $$curr_controls{$control_item};
11155:                         }
11156:                     }
11157:                 }
11158:             }
11159:         }
11160:         my ($group);
11161:         if (&is_course($domain,$user)) {
11162:             ($group,my $file) = split(/\//,$file_name,2);
11163:         }
11164:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11165:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11166:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11167:         #  remove lock
11168:         my @del_lock = ($file_name."\0".'locked_access_records');
11169:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11170:         my $sqlresult =
11171:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11172:                                     $group);
11173:     } else {
11174:         $outcome = "error: could not obtain lockfile\n";  
11175:     }
11176:     return ($outcome,$deloutcome,\%new_values,\%translation);
11177: }
11178: 
11179: sub make_public_indefinitely {
11180:     my (@requrl) = @_;
11181:     return &automated_portfile_access('public',\@requrl);
11182: }
11183: 
11184: sub automated_portfile_access {
11185:     my ($accesstype,$addsref,$delsref,$info) = @_;
11186:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11187:         return 'invalid';
11188:     }
11189:     my %urls;
11190:     if (ref($addsref) eq 'ARRAY') {
11191:         foreach my $requrl (@{$addsref}) {
11192:             if (&is_portfolio_url($requrl)) {
11193:                 unless (exists($urls{$requrl})) {
11194:                     $urls{$requrl} = 'add';
11195:                 }
11196:             }
11197:         }
11198:     }
11199:     if (ref($delsref) eq 'ARRAY') {
11200:         foreach my $requrl (@{$delsref}) { 
11201:             if (&is_portfolio_url($requrl)) {
11202:                 unless (exists($urls{$requrl})) {
11203:                     $urls{$requrl} = 'delete'; 
11204:                 }
11205:             }
11206:         }
11207:     }
11208:     unless (keys(%urls)) {
11209:         return 'invalid';
11210:     }
11211:     my $ip;
11212:     if ($accesstype eq 'ip') {
11213:         if (ref($info) eq 'HASH') {
11214:             if ($info->{'ip'} ne '') {
11215:                 $ip = $info->{'ip'};
11216:             }
11217:         }
11218:         if ($ip eq '') {
11219:             return 'invalid';
11220:         }
11221:     }
11222:     my $errors;
11223:     my $now = time;
11224:     my %current_perms;
11225:     foreach my $requrl (sort(keys(%urls))) {
11226:         my $action;
11227:         if ($urls{$requrl} eq 'add') {
11228:             $action = 'activate';
11229:         } else {
11230:             $action = 'none';
11231:         }
11232:         my $aclnum = 0;
11233:         my (undef,$udom,$unum,$file_name,$group) =
11234:             &parse_portfolio_url($requrl);
11235:         unless (exists($current_perms{$unum.':'.$udom})) {
11236:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11237:         }
11238:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11239:                                                    $group,$file_name);
11240:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11241:             my ($num,$scope,$end,$start) = 
11242:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11243:             if ($scope eq $accesstype) {
11244:                 if (($start <= $now) && ($end == 0)) {
11245:                     if ($accesstype eq 'ip') {
11246:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11247:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11248:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11249:                                     if ($urls{$requrl} eq 'add') {
11250:                                         $action = 'none';
11251:                                         last;
11252:                                     } else {
11253:                                         $action = 'delete';
11254:                                         $aclnum = $num;
11255:                                         last;
11256:                                     }
11257:                                 }
11258:                             }
11259:                         }
11260:                     } elsif ($accesstype eq 'public') {
11261:                         if ($urls{$requrl} eq 'add') {
11262:                             $action = 'none';
11263:                             last;
11264:                         } else {
11265:                             $action = 'delete';
11266:                             $aclnum = $num;
11267:                             last;
11268:                         }
11269:                     }
11270:                 } elsif ($accesstype eq 'public') {
11271:                     $action = 'update';
11272:                     $aclnum = $num;
11273:                     last;
11274:                 }
11275:             }
11276:         }
11277:         if ($action eq 'none') {
11278:             next;
11279:         } else {
11280:             my %changes;
11281:             my $newend = 0;
11282:             my $newstart = $now;
11283:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11284:             $changes{$action}{$newkey} = {
11285:                 type => $accesstype,
11286:                 time => {
11287:                     start => $newstart,
11288:                     end   => $newend,
11289:                 },
11290:             };
11291:             if ($accesstype eq 'ip') {
11292:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11293:             }
11294:             my ($outcome,$deloutcome,$new_values,$translation) =
11295:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11296:             unless ($outcome eq 'ok') {
11297:                 $errors .= $outcome.' ';
11298:             }
11299:         }
11300:     }
11301:     if ($errors) {
11302:         $errors =~ s/\s$//;
11303:         return $errors;
11304:     } else {
11305:         return 'ok';
11306:     }
11307: }
11308: 
11309: #------------------------------------------------------Get Marked as Read Only
11310: 
11311: sub get_marked_as_readonly {
11312:     my ($domain,$user,$what,$group) = @_;
11313:     my $current_permissions = &get_portfile_permissions($domain,$user);
11314:     my @readonly_files;
11315:     my $cmp1=$what;
11316:     if (ref($what)) { $cmp1=join('',@{$what}) };
11317:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11318:         if (defined($group)) {
11319:             if ($file_name !~ m-^\Q$group\E/-) {
11320:                 next;
11321:             }
11322:         }
11323:         if (ref($value) eq "ARRAY"){
11324:             foreach my $stored_what (@{$value}) {
11325:                 my $cmp2=$stored_what;
11326:                 if (ref($stored_what) eq 'ARRAY') {
11327:                     $cmp2=join('',@{$stored_what});
11328:                 }
11329:                 if ($cmp1 eq $cmp2) {
11330:                     push(@readonly_files, $file_name);
11331:                     last;
11332:                 } elsif (!defined($what)) {
11333:                     push(@readonly_files, $file_name);
11334:                     last;
11335:                 }
11336:             }
11337:         }
11338:     }
11339:     return @readonly_files;
11340: }
11341: #-----------------------------------------------------------Get Marked as Read Only Hash
11342: 
11343: sub get_marked_as_readonly_hash {
11344:     my ($current_permissions,$group,$what) = @_;
11345:     my %readonly_files;
11346:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11347:         if (defined($group)) {
11348:             if ($file_name !~ m-^\Q$group\E/-) {
11349:                 next;
11350:             }
11351:         }
11352:         if (ref($value) eq "ARRAY"){
11353:             foreach my $stored_what (@{$value}) {
11354:                 if (ref($stored_what) eq 'ARRAY') {
11355:                     foreach my $lock_descriptor(@{$stored_what}) {
11356:                         if ($lock_descriptor eq 'graded') {
11357:                             $readonly_files{$file_name} = 'graded';
11358:                         } elsif ($lock_descriptor eq 'handback') {
11359:                             $readonly_files{$file_name} = 'handback';
11360:                         } else {
11361:                             if (!exists($readonly_files{$file_name})) {
11362:                                 $readonly_files{$file_name} = 'locked';
11363:                             }
11364:                         }
11365:                     }
11366:                 } 
11367:             }
11368:         } 
11369:     }
11370:     return %readonly_files;
11371: }
11372: # ------------------------------------------------------------ Unmark as Read Only
11373: 
11374: sub unmark_as_readonly {
11375:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11376:     # for portfolio submissions, $what contains [$symb,$crsid] 
11377:     my ($domain,$user,$what,$file_name,$group) = @_;
11378:     $file_name = &declutter_portfile($file_name);
11379:     my $symb_crs = $what;
11380:     if (ref($what)) { $symb_crs=join('',@$what); }
11381:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11382:     my ($tmp)=keys(%current_permissions);
11383:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11384:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11385:     foreach my $file (@readonly_files) {
11386: 	my $clean_file = &declutter_portfile($file);
11387: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11388: 	my $current_locks = $current_permissions{$file};
11389:         my @new_locks;
11390:         my @del_keys;
11391:         if (ref($current_locks) eq "ARRAY"){
11392:             foreach my $locker (@{$current_locks}) {
11393:                 my $compare=$locker;
11394:                 if (ref($locker) eq 'ARRAY') {
11395:                     $compare=join('',@{$locker});
11396:                     if ($compare ne $symb_crs) {
11397:                         push(@new_locks, $locker);
11398:                     }
11399:                 }
11400:             }
11401:             if (scalar(@new_locks) > 0) {
11402:                 $current_permissions{$file} = \@new_locks;
11403:             } else {
11404:                 push(@del_keys, $file);
11405:                 &del('file_permissions',\@del_keys, $domain, $user);
11406:                 delete($current_permissions{$file});
11407:             }
11408:         }
11409:     }
11410:     &put('file_permissions',\%current_permissions,$domain,$user);
11411:     return;
11412: }
11413: 
11414: # ------------------------------------------------------------ Directory lister
11415: 
11416: sub dirlist {
11417:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11418:     $uri=~s/^\///;
11419:     $uri=~s/\/$//;
11420:     my ($udom, $uname);
11421:     if ($getuserdir) {
11422:         $udom = $userdomain;
11423:         $uname = $username;
11424:     } else {
11425:         (undef,$udom,$uname)=split(/\//,$uri);
11426:         if(defined($userdomain)) {
11427:             $udom = $userdomain;
11428:         }
11429:         if(defined($username)) {
11430:             $uname = $username;
11431:         }
11432:     }
11433:     my ($dirRoot,$listing,@listing_results);
11434: 
11435:     $dirRoot = $perlvar{'lonDocRoot'};
11436:     if (defined($getpropath)) {
11437:         $dirRoot = &propath($udom,$uname);
11438:         $dirRoot =~ s/\/$//;
11439:     } elsif (defined($getuserdir)) {
11440:         my $subdir=$uname.'__';
11441:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11442:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11443:                    ."/$udom/$subdir/$uname";
11444:     } elsif (defined($alternateRoot)) {
11445:         $dirRoot = $alternateRoot;
11446:     }
11447: 
11448:     if($udom) {
11449:         if($uname) {
11450:             my $uhome = &homeserver($uname,$udom);
11451:             if ($uhome eq 'no_host') {
11452:                 return ([],'no_host');
11453:             }
11454:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11455:                               .$getuserdir.':'.&escape($dirRoot)
11456:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11457:             if ($listing eq 'unknown_cmd') {
11458:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11459:             } else {
11460:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11461:             }
11462:             if ($listing eq 'unknown_cmd') {
11463:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11464:                 @listing_results = split(/:/,$listing);
11465:             } else {
11466:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11467:             }
11468:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11469:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11470:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11471:                 return ([],$listing);
11472:             } else {
11473:                 return (\@listing_results);
11474:             }
11475:         } elsif(!$alternateRoot) {
11476:             my (%allusers,%listerror);
11477: 	    my %servers = &get_servers($udom,'library');
11478:  	    foreach my $tryserver (keys(%servers)) {
11479:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11480:                                   &escape($udom),$tryserver);
11481:                 if ($listing eq 'unknown_cmd') {
11482: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11483: 				      $udom, $tryserver);
11484:                 } else {
11485:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11486:                 }
11487: 		if ($listing eq 'unknown_cmd') {
11488: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11489: 				      $udom, $tryserver);
11490: 		    @listing_results = split(/:/,$listing);
11491: 		} else {
11492: 		    @listing_results =
11493: 			map { &unescape($_); } split(/:/,$listing);
11494: 		}
11495:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11496:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11497:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11498:                     $listerror{$tryserver} = $listing;
11499:                 } else {
11500: 		    foreach my $line (@listing_results) {
11501: 			my ($entry) = split(/&/,$line,2);
11502: 			$allusers{$entry} = 1;
11503: 		    }
11504: 		}
11505:             }
11506:             my @alluserslist=();
11507:             foreach my $user (sort(keys(%allusers))) {
11508:                 push(@alluserslist,$user.'&user');
11509:             }
11510: 
11511:             if (!%listerror) {
11512:                 # no errors
11513:                 return (\@alluserslist);
11514:             } elsif (scalar(keys(%servers)) == 1) {
11515:                 # one library server, one error 
11516:                 my ($key) = keys(%listerror);
11517:                 return (\@alluserslist, $listerror{$key});
11518:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11519:                 # con_lost indicates that we might miss data from at least one
11520:                 # library server
11521:                 return (\@alluserslist, 'con_lost');
11522:             } else {
11523:                 # multiple library servers and no con_lost -> data should be
11524:                 # complete. 
11525:                 return (\@alluserslist);
11526:             }
11527: 
11528:         } else {
11529:             return ([],'missing username');
11530:         }
11531:     } elsif(!defined($getpropath)) {
11532:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11533:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11534:         return (\@all_domains);
11535:     } else {
11536:         return ([],'missing domain');
11537:     }
11538: }
11539: 
11540: # --------------------------------------------- GetFileTimestamp
11541: # This function utilizes dirlist and returns the date stamp for
11542: # when it was last modified.  It will also return an error of -1
11543: # if an error occurs
11544: 
11545: sub GetFileTimestamp {
11546:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11547:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11548:     $studentName   = &LONCAPA::clean_username($studentName);
11549:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11550:                                     undef,$getuserdir);
11551:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11552:         return -1;
11553:     }
11554:     if (ref($fileref) eq 'ARRAY') {
11555:         my @stats = split('&',$fileref->[0]);
11556:         # @stats contains first the filename, then the stat output
11557:         return $stats[10]; # so this is 10 instead of 9.
11558:     } else {
11559:         return -1;
11560:     }
11561: }
11562: 
11563: sub stat_file {
11564:     my ($uri) = @_;
11565:     $uri = &clutter_with_no_wrapper($uri);
11566: 
11567:     my ($udom,$uname,$file);
11568:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11569: 	($udom,$uname,$file) =
11570: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11571: 	$file = 'userfiles/'.$file;
11572:     }
11573:     if ($uri =~ m-^/res/-) {
11574: 	($udom,$uname) = 
11575: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11576: 	$file = $uri;
11577:     }
11578: 
11579:     if (!$udom || !$uname || !$file) {
11580: 	# unable to handle the uri
11581: 	return ();
11582:     }
11583:     my $getpropath;
11584:     if ($file =~ /^userfiles\//) {
11585:         $getpropath = 1;
11586:     }
11587:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11588:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11589:         return ();
11590:     } else {
11591:         if (ref($listref) eq 'ARRAY') {
11592:             my @stats = split('&',$listref->[0]);
11593: 	    shift(@stats); #filename is first
11594: 	    return @stats;
11595:         }
11596:     }
11597:     return ();
11598: }
11599: 
11600: # --------------------------------------------------------- recursedirs
11601: # Recursive function to traverse either a specific user's Authoring Space
11602: # or corresponding Published Resource Space, and populate the hash ref:
11603: # $dirhashref with URLs of all directories, and if $filehashref hash
11604: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11605: # or .rights files in resource space, and .meta, .save, .log, and .bak
11606: # files in Authoring Space.
11607: #
11608: # Inputs:
11609: #
11610: # $is_home - true if current server is home server for user's space
11611: # $context - either: priv, or res respectively for Authoring or Resource Space.
11612: # $docroot - Document root (i.e., /home/httpd/html
11613: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11614: # $relpath - Current path (relative to top level).
11615: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11616: # $filehashref - reference to hash to populate with URLs of files (Optional)
11617: #
11618: # Returns: nothing
11619: #
11620: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11621: #
11622: # Currently used by interface/londocs.pm to create linked select boxes for
11623: # directory and filename to import a Course "Author" resource into a course, and
11624: # also to create linked select boxes for Authoring Space and Directory to choose
11625: # save location for creation of a new "standard" problem from the Course Editor.
11626: #
11627: 
11628: sub recursedirs {
11629:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11630:     return unless (ref($dirhashref) eq 'HASH');
11631:     my $currpath = $docroot.$toppath;
11632:     if ($relpath) {
11633:         $currpath .= "/$relpath";
11634:     }
11635:     my $savefile;
11636:     if (ref($filehashref)) {
11637:         $savefile = 1;
11638:     }
11639:     if ($is_home) {
11640:         if (opendir(my $dirh,$currpath)) {
11641:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11642:                 next if ($item eq '');
11643:                 if (-d "$currpath/$item") {
11644:                     my $newpath;
11645:                     if ($relpath) {
11646:                         $newpath = "$relpath/$item";
11647:                     } else {
11648:                         $newpath = $item;
11649:                     }
11650:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11651:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11652:                 } elsif ($savefile) {
11653:                     if ($context eq 'priv') {
11654:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11655:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11656:                         }
11657:                     } else {
11658:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11659:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11660:                         }
11661:                     }
11662:                 }
11663:             }
11664:             closedir($dirh);
11665:         }
11666:     } else {
11667:         my ($dirlistref,$listerror) =
11668:             &dirlist($toppath.$relpath);
11669:         my @dir_lines;
11670:         my $dirptr=16384;
11671:         if (ref($dirlistref) eq 'ARRAY') {
11672:             foreach my $dir_line (sort
11673:                               {
11674:                                   my ($afile)=split('&',$a,2);
11675:                                   my ($bfile)=split('&',$b,2);
11676:                                   return (lc($afile) cmp lc($bfile));
11677:                               } (@{$dirlistref})) {
11678:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11679:                     split(/\&/,$dir_line,16);
11680:                 $item =~ s/\s+$//;
11681:                 next if (($item =~ /^\.\.?$/) || ($obs));
11682:                 if ($dirptr&$testdir) {
11683:                     my $newpath;
11684:                     if ($relpath) {
11685:                         $newpath = "$relpath/$item";
11686:                     } else {
11687:                         $relpath = '/';
11688:                         $newpath = $item;
11689:                     }
11690:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11691:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11692:                 } elsif ($savefile) {
11693:                     if ($context eq 'priv') {
11694:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11695:                             $filehashref->{$relpath}{$item} = 1;
11696:                         }
11697:                     } else {
11698:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11699:                             $filehashref->{$relpath}{$item} = 1;
11700:                         }
11701:                     }
11702:                 }
11703:             }
11704:         }
11705:     }
11706:     return;
11707: }
11708: 
11709: # -------------------------------------------------------- Value of a Condition
11710: 
11711: # gets the value of a specific preevaluated condition
11712: #    stored in the string  $env{user.state.<cid>}
11713: # or looks up a condition reference in the bighash and if if hasn't
11714: # already been evaluated recurses into docondval to get the value of
11715: # the condition, then memoizing it to 
11716: #   $env{user.state.<cid>.<condition>}
11717: sub directcondval {
11718:     my $number=shift;
11719:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11720: 	&Apache::lonuserstate::evalstate();
11721:     }
11722:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11723: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11724:     } elsif ($number =~ /^_/) {
11725: 	my $sub_condition;
11726: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11727: 		&GDBM_READER(),0640)) {
11728: 	    $sub_condition=$bighash{'conditions'.$number};
11729: 	    untie(%bighash);
11730: 	}
11731: 	my $value = &docondval($sub_condition);
11732: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11733: 	return $value;
11734:     }
11735:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11736:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11737:     } else {
11738:        return 2;
11739:     }
11740: }
11741: 
11742: # get the collection of conditions for this resource
11743: sub condval {
11744:     my $condidx=shift;
11745:     my $allpathcond='';
11746:     foreach my $cond (split(/\|/,$condidx)) {
11747: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11748: 	    $allpathcond.=
11749: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11750: 	}
11751:     }
11752:     $allpathcond=~s/\|$//;
11753:     return &docondval($allpathcond);
11754: }
11755: 
11756: #evaluates an expression of conditions
11757: sub docondval {
11758:     my ($allpathcond) = @_;
11759:     my $result=0;
11760:     if ($env{'request.course.id'}
11761: 	&& defined($allpathcond)) {
11762: 	my $operand='|';
11763: 	my @stack;
11764: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11765: 	    if ($chunk eq '(') {
11766: 		push @stack,($operand,$result);
11767: 	    } elsif ($chunk eq ')') {
11768: 		my $before=pop @stack;
11769: 		if (pop @stack eq '&') {
11770: 		    $result=$result>$before?$before:$result;
11771: 		} else {
11772: 		    $result=$result>$before?$result:$before;
11773: 		}
11774: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11775: 		$operand=$chunk;
11776: 	    } else {
11777: 		my $new=directcondval($chunk);
11778: 		if ($operand eq '&') {
11779: 		    $result=$result>$new?$new:$result;
11780: 		} else {
11781: 		    $result=$result>$new?$result:$new;
11782: 		}
11783: 	    }
11784: 	}
11785:     }
11786:     return $result;
11787: }
11788: 
11789: # ---------------------------------------------------- Devalidate courseresdata
11790: 
11791: sub devalidatecourseresdata {
11792:     my ($coursenum,$coursedomain)=@_;
11793:     my $hashid=$coursenum.':'.$coursedomain;
11794:     &devalidate_cache_new('courseres',$hashid);
11795: }
11796: 
11797: 
11798: # --------------------------------------------------- Course Resourcedata Query
11799: #
11800: #  Parameters:
11801: #      $coursenum    - Number of the course.
11802: #      $coursedomain - Domain at which the course was created.
11803: #  Returns:
11804: #     A hash of the course parameters along (I think) with timestamps
11805: #     and version info.
11806: 
11807: sub get_courseresdata {
11808:     my ($coursenum,$coursedomain)=@_;
11809:     my $coursehom=&homeserver($coursenum,$coursedomain);
11810:     my $hashid=$coursenum.':'.$coursedomain;
11811:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11812:     my %dumpreply;
11813:     unless (defined($cached)) {
11814: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11815: 	$result=\%dumpreply;
11816: 	my ($tmp) = keys(%dumpreply);
11817: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11818: 	    &do_cache_new('courseres',$hashid,$result,600);
11819: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11820: 	    return $tmp;
11821: 	} elsif ($tmp =~ /^(error)/) {
11822: 	    $result=undef;
11823: 	    &do_cache_new('courseres',$hashid,$result,600);
11824: 	}
11825:     }
11826:     return $result;
11827: }
11828: 
11829: sub devalidateuserresdata {
11830:     my ($uname,$udom)=@_;
11831:     my $hashid="$udom:$uname";
11832:     &devalidate_cache_new('userres',$hashid);
11833: }
11834: 
11835: sub get_userresdata {
11836:     my ($uname,$udom)=@_;
11837:     #most student don\'t have any data set, check if there is some data
11838:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11839: 
11840:     my $hashid="$udom:$uname";
11841:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11842:     if (!defined($cached)) {
11843: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11844: 	$result=\%resourcedata;
11845: 	&do_cache_new('userres',$hashid,$result,600);
11846:     }
11847:     my ($tmp)=keys(%$result);
11848:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11849: 	return $result;
11850:     }
11851:     #error 2 occurs when the .db doesn't exist
11852:     if ($tmp!~/error: 2 /) {
11853:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11854: 	    &logthis("<font color=\"blue\">WARNING:".
11855: 		     " Trying to get resource data for ".
11856: 		     $uname." at ".$udom.": ".
11857: 		     $tmp."</font>");
11858:         }
11859:     } elsif ($tmp=~/error: 2 /) {
11860: 	#&EXT_cache_set($udom,$uname);
11861: 	&do_cache_new('userres',$hashid,undef,600);
11862: 	undef($tmp); # not really an error so don't send it back
11863:     }
11864:     return $tmp;
11865: }
11866: #----------------------------------------------- resdata - return resource data
11867: #  Purpose:
11868: #    Return resource data for either users or for a course.
11869: #  Parameters:
11870: #     $name      - Course/user name.
11871: #     $domain    - Name of the domain the user/course is registered on.
11872: #     $type      - Type of thing $name is (must be 'course' or 'user')
11873: #     $mapp      - decluttered URL of enclosing map  
11874: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11875: #     $recurseup - Ref to array of map URLs, starting with map containing
11876: #                  $mapp up through hierarchy of nested maps to top level map.  
11877: #     $courseid  - CourseID (first part of param identifier).
11878: #     $modifier  - Middle part of param identifier.
11879: #     $what      - Last part of param identifier.
11880: #     @which     - Array of names of resources desired.
11881: #  Returns:
11882: #     The value of the first reasource in @which that is found in the
11883: #     resource hash.
11884: #  Exceptional Conditions:
11885: #     If the $type passed in is not valid (not the string 'course' or 
11886: #     'user', an undefined  reference is returned.
11887: #     If none of the resources are found, an undef is returned
11888: sub resdata {
11889:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11890:         $modifier,$what,@which)=@_;
11891:     my $result;
11892:     if ($type eq 'course') {
11893: 	$result=&get_courseresdata($name,$domain);
11894:     } elsif ($type eq 'user') {
11895: 	$result=&get_userresdata($name,$domain);
11896:     }
11897:     if (!ref($result)) { return $result; }    
11898:     foreach my $item (@which) {
11899:         if ($item->[1] eq 'course') {
11900:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11901:                 unless ($$recursed) {
11902:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11903:                     $$recursed = 1;
11904:                 }
11905:                 foreach my $item (@${recurseup}) {
11906:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11907:                     last if (defined($result->{$norecursechk}));
11908:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11909:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11910:                 }
11911:             }
11912:         }
11913:         if (defined($result->{$item->[0]})) {
11914: 	    return [$result->{$item->[0]},$item->[1]];
11915: 	}
11916:     }
11917:     return undef;
11918: }
11919: 
11920: sub get_domain_lti {
11921:     my ($cdom,$context) = @_;
11922:     my ($name,%lti);
11923:     if ($context eq 'consumer') {
11924:         $name = 'ltitools';
11925:     } elsif ($context eq 'provider') {
11926:         $name = 'lti';
11927:     } else {
11928:         return %lti;
11929:     }
11930:     my ($result,$cached)=&is_cached_new($name,$cdom);
11931:     if (defined($cached)) {
11932:         if (ref($result) eq 'HASH') {
11933:             %lti = %{$result};
11934:         }
11935:     } else {
11936:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11937:         if (ref($domconfig{$name}) eq 'HASH') {
11938:             %lti = %{$domconfig{$name}};
11939:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11940:             if (ref($encdomconfig{$name}) eq 'HASH') {
11941:                 foreach my $id (keys(%lti)) {
11942:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11943:                         foreach my $item ('key','secret') {
11944:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11945:                         }
11946:                     }
11947:                 }
11948:             }
11949:         }
11950:         my $cachetime = 24*60*60;
11951:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11952:     }
11953:     return %lti;
11954: }
11955: 
11956: sub get_numsuppfiles {
11957:     my ($cnum,$cdom,$ignorecache)=@_;
11958:     my $hashid=$cnum.':'.$cdom;
11959:     my ($suppcount,$cached);
11960:     unless ($ignorecache) {
11961:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11962:     }
11963:     unless (defined($cached)) {
11964:         my $chome=&homeserver($cnum,$cdom);
11965:         unless ($chome eq 'no_host') {
11966:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11967:             my $suppmap = 'supplemental.sequence';
11968:             ($suppcount,$supptools,$errors) =
11969:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11970:                                                          $supptools,$errors);
11971:         }
11972:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11973:     }
11974:     return $suppcount;
11975: }
11976: 
11977: #
11978: # EXT resource caching routines
11979: #
11980: 
11981: {
11982: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11983: #
11984: # The course for which we cache
11985: my $cachedmapkey='';
11986: # The cached recursive maps for this course
11987: my %cachedmaps=();
11988: # When this was last done
11989: my $cachedmaptime='';
11990: 
11991: sub clear_EXT_cache_status {
11992:     &delenv('cache.EXT.');
11993: }
11994: 
11995: sub EXT_cache_status {
11996:     my ($target_domain,$target_user) = @_;
11997:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11998:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11999:         # We know already the user has no data
12000:         return 1;
12001:     } else {
12002:         return 0;
12003:     }
12004: }
12005: 
12006: sub EXT_cache_set {
12007:     my ($target_domain,$target_user) = @_;
12008:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12009:     #&appenv({$cachename => time});
12010: }
12011: 
12012: # --------------------------------------------------------- Value of a Variable
12013: sub EXT {
12014: 
12015:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
12016:     unless ($varname) { return ''; }
12017:     #get real user name/domain, courseid and symb
12018:     my $courseid;
12019:     my $publicuser;
12020:     if ($symbparm) {
12021: 	$symbparm=&get_symb_from_alias($symbparm);
12022:     }
12023:     if (!($uname && $udom)) {
12024:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12025:       if (!$symbparm) {	$symbparm=$cursymb; }
12026:     } else {
12027: 	$courseid=$env{'request.course.id'};
12028:     }
12029:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12030:     my $rest;
12031:     if (defined($therest[0])) {
12032:        $rest=join('.',@therest);
12033:     } else {
12034:        $rest='';
12035:     }
12036: 
12037:     my $qualifierrest=$qualifier;
12038:     if ($rest) { $qualifierrest.='.'.$rest; }
12039:     my $spacequalifierrest=$space;
12040:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12041:     if ($realm eq 'user') {
12042: # --------------------------------------------------------------- user.resource
12043: 	if ($space eq 'resource') {
12044: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12045: 		  || defined($Apache::lonhomework::parsing_a_task))
12046: 		 &&
12047: 		 ($symbparm eq &symbread()) ) {	
12048: 		# if we are in the middle of processing the resource the
12049: 		# get the value we are planning on committing
12050:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12051:                     return $Apache::lonhomework::results{$qualifierrest};
12052:                 } else {
12053:                     return $Apache::lonhomework::history{$qualifierrest};
12054:                 }
12055: 	    } else {
12056: 		my %restored;
12057: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12058: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12059: 		} else {
12060: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12061: 		}
12062: 		return $restored{$qualifierrest};
12063: 	    }
12064: # ----------------------------------------------------------------- user.access
12065:         } elsif ($space eq 'access') {
12066: 	    # FIXME - not supporting calls for a specific user
12067:             return &allowed($qualifier,$rest);
12068: # ------------------------------------------ user.preferences, user.environment
12069:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12070: 	    if (($uname eq $env{'user.name'}) &&
12071: 		($udom eq $env{'user.domain'})) {
12072: 		return $env{join('.',('environment',$qualifierrest))};
12073: 	    } else {
12074: 		my %returnhash;
12075: 		if (!$publicuser) {
12076: 		    %returnhash=&userenvironment($udom,$uname,
12077: 						 $qualifierrest);
12078: 		}
12079: 		return $returnhash{$qualifierrest};
12080: 	    }
12081: # ----------------------------------------------------------------- user.course
12082:         } elsif ($space eq 'course') {
12083: 	    # FIXME - not supporting calls for a specific user
12084:             return $env{join('.',('request.course',$qualifier))};
12085: # ------------------------------------------------------------------- user.role
12086:         } elsif ($space eq 'role') {
12087: 	    # FIXME - not supporting calls for a specific user
12088:             my ($role,$where)=split(/\./,$env{'request.role'});
12089:             if ($qualifier eq 'value') {
12090: 		return $role;
12091:             } elsif ($qualifier eq 'extent') {
12092:                 return $where;
12093:             }
12094: # ----------------------------------------------------------------- user.domain
12095:         } elsif ($space eq 'domain') {
12096:             return $udom;
12097: # ------------------------------------------------------------------- user.name
12098:         } elsif ($space eq 'name') {
12099:             return $uname;
12100: # ---------------------------------------------------- Any other user namespace
12101:         } else {
12102: 	    my %reply;
12103: 	    if (!$publicuser) {
12104: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12105: 	    }
12106: 	    return $reply{$qualifierrest};
12107:         }
12108:     } elsif ($realm eq 'query') {
12109: # ---------------------------------------------- pull stuff out of query string
12110:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12111: 						[$spacequalifierrest]);
12112: 	return $env{'form.'.$spacequalifierrest}; 
12113:    } elsif ($realm eq 'request') {
12114: # ------------------------------------------------------------- request.browser
12115:         if ($space eq 'browser') {
12116:             return $env{'browser.'.$qualifier};
12117: # ------------------------------------------------------------ request.filename
12118:         } else {
12119:             return $env{'request.'.$spacequalifierrest};
12120:         }
12121:     } elsif ($realm eq 'course') {
12122: # ---------------------------------------------------------- course.description
12123:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12124:     } elsif ($realm eq 'resource') {
12125: 
12126: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12127: 	    if (!$symbparm) { $symbparm=&symbread(); }
12128: 	}
12129: 
12130:         if ($qualifier eq '') {
12131: 	    if ($space eq 'title') {
12132: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12133: 	        return &gettitle($symbparm);
12134: 	    }
12135: 	
12136: 	    if ($space eq 'map') {
12137: 	        my ($map) = &decode_symb($symbparm);
12138: 	        return &symbread($map);
12139: 	    }
12140:             if ($space eq 'maptitle') {
12141:                 my ($map) = &decode_symb($symbparm);
12142:                 return &gettitle($map);
12143:             }
12144: 	    if ($space eq 'filename') {
12145: 	        if ($symbparm) {
12146: 		    return &clutter((&decode_symb($symbparm))[2]);
12147: 	        }
12148: 	        return &hreflocation('',$env{'request.filename'});
12149: 	    }
12150: 
12151:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12152:                 if ($space eq 'visibleparts') {
12153:                     my $navmap = Apache::lonnavmaps::navmap->new();
12154:                     my $item;
12155:                     if (ref($navmap)) {
12156:                         my $res = $navmap->getBySymb($symbparm);
12157:                         my $parts = $res->parts();
12158:                         if (ref($parts) eq 'ARRAY') {
12159:                             $item = join(',',@{$parts});
12160:                         }
12161:                         undef($navmap);
12162:                     }
12163:                     return $item;
12164:                 }
12165:             }
12166:         }
12167: 
12168: 	my ($section, $group, @groups, @recurseup, $recursed);
12169: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12170:         if (($courseid eq '') && ($cid)) {
12171:             $courseid = $cid;
12172:         }
12173: 	if (($symbparm && $courseid) && 
12174: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12175: 
12176: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12177: 
12178: # ----------------------------------------------------- Cascading lookup scheme
12179: 	    my $symbp=$symbparm;
12180: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12181: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12182:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12183: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12184: 	    if (($env{'user.name'} eq $uname) &&
12185: 		($env{'user.domain'} eq $udom)) {
12186: 		$section=$env{'request.course.sec'};
12187:                 @groups = split(/:/,$env{'request.course.groups'});  
12188:                 @groups=&sort_course_groups($courseid,@groups); 
12189: 	    } else {
12190: 		if (! defined($usection)) {
12191: 		    $section=&getsection($udom,$uname,$courseid);
12192: 		} else {
12193: 		    $section = $usection;
12194: 		}
12195:                 @groups = &get_users_groups($udom,$uname,$courseid);
12196: 	    }
12197: 
12198: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12199: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12200:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12201: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12202: 
12203: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12204: 	    my $courselevelr=$courseid.'.'.$symbparm;
12205:             $courseleveli=$courseid.'.'.$recurseparm;
12206: 	    $courselevelm=$courseid.'.'.$mapparm;
12207: 
12208: # ----------------------------------------------------------- first, check user
12209: 
12210: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12211:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12212: 				       ([$courselevelr,'resource'],
12213: 					[$courselevelm,'map'     ],
12214:                                         [$courseleveli,'map'     ],
12215: 					[$courselevel, 'course'  ]));
12216: 	    if (defined($userreply)) { return &get_reply($userreply); }
12217: 
12218: # ------------------------------------------------ second, check some of course
12219:             my $coursereply;
12220:             if (@groups > 0) {
12221:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12222:                                        $recurseparm,$mapparm,$spacequalifierrest,
12223:                                        $mapp,\$recursed,\@recurseup);
12224:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12225:             }
12226: 
12227: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12228: 				  $env{'course.'.$courseid.'.domain'},
12229: 				  'course',$mapp,\$recursed,\@recurseup,
12230:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12231: 				  ([$seclevelr,   'resource'],
12232: 				   [$seclevelm,   'map'     ],
12233:                                    [$secleveli,   'map'     ],
12234: 				   [$seclevel,    'course'  ],
12235: 				   [$courselevelr,'resource']));
12236: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12237: 
12238: # ------------------------------------------------------ third, check map parms
12239: 	    my %parmhash=();
12240: 	    my $thisparm='';
12241: 	    if (tie(%parmhash,'GDBM_File',
12242: 		    $env{'request.course.fn'}.'_parms.db',
12243: 		    &GDBM_READER(),0640)) {
12244: 		$thisparm=$parmhash{$symbparm};
12245: 		untie(%parmhash);
12246: 	    }
12247: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12248: 	}
12249: # ------------------------------------------ fourth, look in resource metadata
12250:  
12251:         my $what = $spacequalifierrest;
12252: 	$what=~s/\./\_/;
12253: 	my $filename;
12254: 	if (!$symbparm) { $symbparm=&symbread(); }
12255: 	if ($symbparm) {
12256: 	    $filename=(&decode_symb($symbparm))[2];
12257: 	} else {
12258: 	    $filename=$env{'request.filename'};
12259: 	}
12260:         my $toolsymb;
12261:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12262:             $toolsymb = $symbparm;
12263:         }
12264: 	my $metadata=&metadata($filename,$what,$toolsymb);
12265: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12266: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12267: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12268: 
12269: # ----------------------------------------------- fifth, look in rest of course
12270: 	if ($symbparm && defined($courseid) && 
12271: 	    $courseid eq $env{'request.course.id'}) {
12272: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12273: 				     $env{'course.'.$courseid.'.domain'},
12274: 				     'course',$mapp,\$recursed,\@recurseup,
12275:                                      $courseid,'.',$spacequalifierrest,
12276: 				     ([$courselevelm,'map'   ],
12277:                                       [$courseleveli,'map'   ],
12278: 				      [$courselevel, 'course']));
12279: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12280: 	}
12281: # ------------------------------------------------------------------ Cascade up
12282: 	unless ($space eq '0') {
12283: 	    my @parts=split(/_/,$space);
12284: 	    my $id=pop(@parts);
12285: 	    my $part=join('_',@parts);
12286: 	    if ($part eq '') { $part='0'; }
12287: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12288: 				 $symbparm,$udom,$uname,$section,1);
12289: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12290: 	}
12291: 	if ($recurse) { return undef; }
12292: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12293: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12294: # ---------------------------------------------------- Any other user namespace
12295:     } elsif ($realm eq 'environment') {
12296: # ----------------------------------------------------------------- environment
12297: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12298: 	    return $env{'environment.'.$spacequalifierrest};
12299: 	} else {
12300: 	    if ($uname eq 'anonymous' && $udom eq '') {
12301: 		return '';
12302: 	    }
12303: 	    my %returnhash=&userenvironment($udom,$uname,
12304: 					    $spacequalifierrest);
12305: 	    return $returnhash{$spacequalifierrest};
12306: 	}
12307:     } elsif ($realm eq 'system') {
12308: # ----------------------------------------------------------------- system.time
12309: 	if ($space eq 'time') {
12310: 	    return time;
12311:         }
12312:     } elsif ($realm eq 'server') {
12313: # ----------------------------------------------------------------- system.time
12314: 	if ($space eq 'name') {
12315: 	    return $ENV{'SERVER_NAME'};
12316:         }
12317:     } elsif ($realm eq 'client') {
12318:         if ($space eq 'remote_addr') {
12319:             return $ENV{'REMOTE_ADDR'};
12320:         }
12321:     }
12322:     return '';
12323: }
12324: 
12325: sub get_reply {
12326:     my ($reply_value) = @_;
12327:     if (ref($reply_value) eq 'ARRAY') {
12328:         if (wantarray) {
12329: 	    return @$reply_value;
12330:         }
12331:         return $reply_value->[0];
12332:     } else {
12333:         return $reply_value;
12334:     }
12335: }
12336: 
12337: sub check_group_parms {
12338:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12339:         $recursed,$recurseupref) = @_;
12340:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12341:                   [$what,'course']);
12342:     my $coursereply;
12343:     foreach my $group (@{$groups}) {
12344:         my @groupitems = ();
12345:         foreach my $level (@levels) {
12346:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12347:              push(@groupitems,[$item,$level->[1]]);
12348:         }
12349:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12350:                                    $env{'course.'.$courseid.'.domain'},
12351:                                    'course',$mapp,$recursed,$recurseupref,
12352:                                    $courseid,'.['.$group.'].',$what,
12353:                                    @groupitems);
12354:         last if (defined($coursereply));
12355:     }
12356:     return $coursereply;
12357: }
12358: 
12359: sub get_map_hierarchy {
12360:     my ($mapname,$courseid) = @_;
12361:     my @recurseup = ();
12362:     if ($mapname) {
12363:         if (($cachedmapkey eq $courseid) &&
12364:             (abs($cachedmaptime-time)<5)) {
12365:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12366:                 return @{$cachedmaps{$mapname}};
12367:             }
12368:         }
12369:         my $navmap = Apache::lonnavmaps::navmap->new();
12370:         if (ref($navmap)) {
12371:             @recurseup = $navmap->recurseup_maps($mapname);
12372:             undef($navmap);
12373:             $cachedmaps{$mapname} = \@recurseup;
12374:             $cachedmaptime=time;
12375:             $cachedmapkey=$courseid;
12376:         }
12377:     }
12378:     return @recurseup;
12379: }
12380: 
12381: }
12382: 
12383: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12384:     my ($courseid,@groups) = @_;
12385:     @groups = sort(@groups);
12386:     return @groups;
12387: }
12388: 
12389: sub packages_tab_default {
12390:     my ($uri,$varname,$toolsymb)=@_;
12391:     my (undef,$part,$name)=split(/\./,$varname);
12392: 
12393:     my (@extension,@specifics,$do_default);
12394:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12395: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12396: 	if ($pack_type eq 'default') {
12397: 	    $do_default=1;
12398: 	} elsif ($pack_type eq 'extension') {
12399: 	    push(@extension,[$package,$pack_type,$pack_part]);
12400: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12401: 	    # only look at packages defaults for packages that this id is
12402: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12403: 	}
12404:     }
12405:     # first look for a package that matches the requested part id
12406:     foreach my $package (@specifics) {
12407: 	my (undef,$pack_type,$pack_part)=@{$package};
12408: 	next if ($pack_part ne $part);
12409: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12410: 	    return $packagetab{"$pack_type&$name&default"};
12411: 	}
12412:     }
12413:     # look for any possible matching non extension_ package
12414:     foreach my $package (@specifics) {
12415: 	my (undef,$pack_type,$pack_part)=@{$package};
12416: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12417: 	    return $packagetab{"$pack_type&$name&default"};
12418: 	}
12419: 	if ($pack_type eq 'part') { $pack_part='0'; }
12420: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12421: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12422: 	}
12423:     }
12424:     # look for any posible extension_ match
12425:     foreach my $package (@extension) {
12426: 	my ($package,$pack_type)=@{$package};
12427: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12428: 	    return $packagetab{"$pack_type&$name&default"};
12429: 	}
12430: 	if (defined($packagetab{$package."&$name&default"})) {
12431: 	    return $packagetab{$package."&$name&default"};
12432: 	}
12433:     }
12434:     # look for a global default setting
12435:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12436: 	return $packagetab{"default&$name&default"};
12437:     }
12438:     return undef;
12439: }
12440: 
12441: sub add_prefix_and_part {
12442:     my ($prefix,$part)=@_;
12443:     my $keyroot;
12444:     if (defined($prefix) && $prefix !~ /^__/) {
12445: 	# prefix that has a part already
12446: 	$keyroot=$prefix;
12447:     } elsif (defined($prefix)) {
12448: 	# prefix that is missing a part
12449: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12450:     } else {
12451: 	# no prefix at all
12452: 	if (defined($part)) { $keyroot='_'.$part; }
12453:     }
12454:     return $keyroot;
12455: }
12456: 
12457: # ---------------------------------------------------------------- Get metadata
12458: 
12459: my %metaentry;
12460: my %importedpartids;
12461: my %importedrespids;
12462: sub metadata {
12463:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12464:     $uri=&declutter($uri);
12465:     # if it is a non metadata possible uri return quickly
12466:     if (($uri eq '') || 
12467: 	(($uri =~ m|^/*adm/|) && 
12468: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12469:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12470: 	return undef;
12471:     }
12472:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12473: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12474: 	return undef;
12475:     }
12476:     my $filename=$uri;
12477:     $uri=~s/\.meta$//;
12478: #
12479: # Is the metadata already cached?
12480: # Look at timestamp of caching
12481: # Everything is cached by the main uri, libraries are never directly cached
12482: #
12483:     if (!defined($liburi)) {
12484: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12485: 	if (defined($cached)) { return $result->{':'.$what}; }
12486:     }
12487: 
12488: #
12489: # If the uri is for an external tool the file from
12490: # which metadata should be retrieved depends on whether
12491: # the tool had been configured to be gradable (set in the Course
12492: # Editor or Resource Editor).
12493: #
12494: # If a valid symb has been included as the third arg in the call
12495: # to &metadata() that can be used to retrieve the value of
12496: # parameter_0_gradable set for the resource, and included in the
12497: # uploaded map containing the tool. The value is retrieved via
12498: # &EXT(), if a valid symb is available.  Otherwise the value of
12499: # gradable in the exttool_$marker.db file for the tool instance
12500: # is retrieved via &get().
12501: #
12502: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12503: # hiddenresource and encrypturl (during course initialization)
12504: # the map-level parameter for resource.0.gradable included in the 
12505: # uploaded map containing the tool will not yet have been stored
12506: # in the user_course_parms.db file for the user's session, so in 
12507: # this case fall back to retrieving gradable status from the
12508: # exttool_$marker.db file.
12509: #
12510: # In order to avoid an infinite loop, &metadata() will return
12511: # before a call to &EXT(), if the uri is for an external tool
12512: # and the $what for which metadata is being requested is
12513: # parameter_0_gradable or 0_gradable.
12514: #
12515: 
12516:     if ($uri =~ /ext\.tool$/) {
12517:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12518:             return;
12519:         } else {
12520:             my ($checked,$use_passback);
12521:             if ($toolsymb ne '') {
12522:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12523:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12524:                     $checked = 1;
12525:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12526:                         $use_passback = 1;
12527:                     }
12528:                 }
12529:             }
12530:             unless ($checked) {
12531:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12532:                 $marker=~s/\D//g;
12533:                 if ($marker) {
12534:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12535:                     $use_passback = $toolsettings{'gradable'};
12536:                 }
12537:             }
12538:             if ($use_passback) {
12539:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12540:             } else {
12541:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12542:             }
12543:         }
12544:     }
12545: 
12546:     {
12547: # Imported parts would go here
12548:         my @origfiletagids=();
12549:         my $importedparts=0;
12550: 
12551: # Imported responseids would go here
12552:         my $importedresponses=0;
12553: #
12554: # Is this a recursive call for a library?
12555: #
12556: #	if (! exists($metacache{$uri})) {
12557: #	    $metacache{$uri}={};
12558: #	}
12559: 	my $cachetime = 60*60;
12560:         if ($liburi) {
12561: 	    $liburi=&declutter($liburi);
12562:             $filename=$liburi;
12563:         } else {
12564: 	    &devalidate_cache_new('meta',$uri);
12565: 	    undef(%metaentry);
12566: 	}
12567:         my %metathesekeys=();
12568:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12569: 	my $metastring;
12570: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12571: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12572: 	    $metastring = 
12573: 		&Apache::lonnet::ssi_body($which,
12574: 					  ('grade_target' => 'meta'));
12575: 	    $cachetime = 1; # only want this cached in the child not long term
12576: 	} elsif (($uri !~ m -^(editupload)/-) && 
12577:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12578: 	    my $file=&filelocation('',&clutter($filename));
12579: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12580: 	    $metastring=&getfile($file);
12581: 	}
12582:         my $parser=HTML::LCParser->new(\$metastring);
12583:         my $token;
12584:         undef %metathesekeys;
12585:         while ($token=$parser->get_token) {
12586: 	    if ($token->[0] eq 'S') {
12587: 		if (defined($token->[2]->{'package'})) {
12588: #
12589: # This is a package - get package info
12590: #
12591: 		    my $package=$token->[2]->{'package'};
12592: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12593: 		    if (defined($token->[2]->{'id'})) { 
12594: 			$keyroot.='_'.$token->[2]->{'id'}; 
12595: 		    }
12596: 		    if ($metaentry{':packages'}) {
12597: 			$metaentry{':packages'}.=','.$package.$keyroot;
12598: 		    } else {
12599: 			$metaentry{':packages'}=$package.$keyroot;
12600: 		    }
12601: 		    foreach my $pack_entry (keys(%packagetab)) {
12602: 			my $part=$keyroot;
12603: 			$part=~s/^\_//;
12604: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12605: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12606: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12607: 			    # ignore package.tab specified default values
12608:                             # here &package_tab_default() will fetch those
12609: 			    if ($subp eq 'default') { next; }
12610: 			    my $value=$packagetab{$pack_entry};
12611: 			    my $unikey;
12612: 			    if ($pack =~ /_0$/) {
12613: 				$unikey='parameter_0_'.$name;
12614: 				$part=0;
12615: 			    } else {
12616: 				$unikey='parameter'.$keyroot.'_'.$name;
12617: 			    }
12618: 			    if ($subp eq 'display') {
12619: 				$value.=' [Part: '.$part.']';
12620: 			    }
12621: 			    $metaentry{':'.$unikey.'.part'}=$part;
12622: 			    $metathesekeys{$unikey}=1;
12623: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12624: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12625: 			    }
12626: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12627: 				$metaentry{':'.$unikey}=
12628: 				    $metaentry{':'.$unikey.'.default'};
12629: 			    }
12630: 			}
12631: 		    }
12632: 		} else {
12633: #
12634: # This is not a package - some other kind of start tag
12635: #
12636: 		    my $entry=$token->[1];
12637: 		    my $unikey='';
12638: 
12639: 		    if ($entry eq 'import') {
12640: #
12641: # Importing a library here
12642: #
12643:                         my $location=$parser->get_text('/import');
12644:                         my $dir=$filename;
12645:                         $dir=~s|[^/]*$||;
12646:                         $location=&filelocation($dir,$location);
12647: 
12648:                         my $importid=$token->[2]->{'id'};
12649:                         my $importmode=$token->[2]->{'importmode'};
12650: #
12651: # Check metadata for imported file to
12652: # see if it contained response items
12653: #
12654:                         my ($origfile,@libfilekeys);
12655:                         my %currmetaentry = %metaentry;
12656:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12657:                                                            $depthcount+1));
12658:                         if (grep(/^responseorder$/,@libfilekeys)) {
12659:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12660:                                                              undef,$depthcount+1);
12661:                             if ($libresponseorder ne '') {
12662:                                 if ($#origfiletagids<0) {
12663:                                     undef(%importedrespids);
12664:                                     undef(%importedpartids);
12665:                                 }
12666:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12667:                                 if (@respids) {
12668:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12669:                                 }
12670:                                 if ($importedrespids{$importid} ne '') {
12671:                                     $importedresponses = 1;
12672: # We need to get the original file and the imported file to get the response order correct
12673: # Load and inspect original file
12674:                                     if ($#origfiletagids<0) {
12675:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12676:                                         $origfile=&getfile($origfilelocation);
12677:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12678:                                     }
12679:                                 }
12680:                             }
12681:                         }
12682: # Do not overwrite contents of %metaentry hash for resource itself with 
12683: # hash populated for imported library file
12684:                         %metaentry = %currmetaentry;
12685:                         undef(%currmetaentry);
12686:                         if ($importmode eq 'part') {
12687: # Import as part(s)
12688:                            $importedparts=1;
12689: # We need to get the original file and the imported file to get the part order correct
12690: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12691: # Load and inspect original file if we didn't do that already
12692:                            if ($#origfiletagids<0) {
12693:                                undef(%importedrespids);
12694:                                undef(%importedpartids);
12695:                                if ($origfile eq '') {
12696:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12697:                                    $origfile=&getfile($origfilelocation);
12698:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12699:                                }
12700:                            }
12701:                            my @impfilepartids;
12702: # If <partorder> tag is included in metadata for the imported file
12703: # get the parts in the imported file from that.
12704:                            if (grep(/^partorder$/,@libfilekeys)) {
12705:                                %currmetaentry = %metaentry;
12706:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12707:                                                             $depthcount+1);
12708:                                %metaentry = %currmetaentry;
12709:                                undef(%currmetaentry);
12710:                                if ($libpartorder ne '') {
12711:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12712:                                }
12713:                            } else {
12714: # If no <partorder> tag available, load and inspect imported file
12715:                                my $impfile=&getfile($location);
12716:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12717:                            }
12718:                            if ($#impfilepartids>=0) {
12719: # This problem had parts
12720:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12721:                            } else {
12722: # Importing by turning a single problem into a problem part
12723: # It gets the import-tags ID as part-ID
12724:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12725:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12726:                            }
12727:                         } else {
12728: # Import as problem or as normal import
12729:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12730:                             unless ($importmode eq 'problem') {
12731: # Normal import
12732:                                 if (defined($token->[2]->{'id'})) {
12733:                                     $unikey.='_'.$token->[2]->{'id'};
12734:                                 }
12735:                             }
12736: # Check metadata for imported file to
12737: # see if it contained parts
12738:                             if (grep(/^partorder$/,@libfilekeys)) {
12739:                                 %currmetaentry = %metaentry;
12740:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12741:                                                              $depthcount+1);
12742:                                 %metaentry = %currmetaentry;
12743:                                 undef(%currmetaentry);
12744:                                 if ($libpartorder ne '') {
12745:                                     $importedparts = 1;
12746:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12747:                                 }
12748:                             }
12749:                         }
12750: 			if ($depthcount<20) {
12751: 			    my $metadata = 
12752: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12753: 					  $depthcount+1);
12754: 			    foreach my $meta (split(',',$metadata)) {
12755: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12756: 				$metathesekeys{$meta}=1;
12757: 			    }
12758:                         }
12759: 		    } else {
12760: #
12761: # Not importing, some other kind of non-package, non-library start tag
12762: # 
12763:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12764:                         if (defined($token->[2]->{'id'})) {
12765:                             $unikey.='_'.$token->[2]->{'id'};
12766:                         }
12767: 			if (defined($token->[2]->{'name'})) { 
12768: 			    $unikey.='_'.$token->[2]->{'name'}; 
12769: 			}
12770: 			$metathesekeys{$unikey}=1;
12771: 			foreach my $param (@{$token->[3]}) {
12772: 			    $metaentry{':'.$unikey.'.'.$param} =
12773: 				$token->[2]->{$param};
12774: 			}
12775: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12776: 			my $default=$metaentry{':'.$unikey.'.default'};
12777: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12778: 		 # only ws inside the tag, and not in default, so use default
12779: 		 # as value
12780: 			    $metaentry{':'.$unikey}=$default;
12781: 			} elsif ( $internaltext =~ /\S/ ) {
12782: 		  # something interesting inside the tag
12783: 			    $metaentry{':'.$unikey}=$internaltext;
12784: 			} else {
12785: 		  # no interesting values, don't set a default
12786: 			}
12787: # end of not-a-package not-a-library import
12788: 		    }
12789: # end of not-a-package start tag
12790: 		}
12791: # the next is the end of "start tag"
12792: 	    }
12793: 	}
12794: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12795: 	$extension = lc($extension);
12796: 	if ($extension eq 'htm') { $extension='html'; }
12797: 
12798: 	foreach my $key (keys(%packagetab)) {
12799: 	    #no specific packages #how's our extension
12800: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12801: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12802: 					 \%metathesekeys);
12803: 	}
12804: 
12805: 	if (!exists($metaentry{':packages'})
12806: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12807: 	    foreach my $key (keys(%packagetab)) {
12808: 		#no specific packages well let's get default then
12809: 		if ($key!~/^default&/) { next; }
12810: 		&metadata_create_package_def($uri,$key,'default',
12811: 					     \%metathesekeys);
12812: 	    }
12813: 	}
12814: # are there custom rights to evaluate
12815: 	if ($metaentry{':copyright'} eq 'custom') {
12816: 
12817:     #
12818:     # Importing a rights file here
12819:     #
12820: 	    unless ($depthcount) {
12821: 		my $location=$metaentry{':customdistributionfile'};
12822: 		my $dir=$filename;
12823: 		$dir=~s|[^/]*$||;
12824: 		$location=&filelocation($dir,$location);
12825: 		my $rights_metadata =
12826: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12827: 			      $depthcount+1);
12828: 		foreach my $rights (split(',',$rights_metadata)) {
12829: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12830: 		    $metathesekeys{$rights}=1;
12831: 		}
12832: 	    }
12833: 	}
12834: 	# uniqifiy package listing
12835: 	my %seen;
12836: 	my @uniq_packages =
12837: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12838: 	$metaentry{':packages'} = join(',',@uniq_packages);
12839: 
12840:         if (($importedresponses) || ($importedparts)) {
12841:             if ($importedparts) {
12842: # We had imported parts and need to rebuild partorder
12843:                 $metaentry{':partorder'}='';
12844:                 $metathesekeys{'partorder'}=1;
12845:             }
12846:             if ($importedresponses) {
12847: # We had imported responses and need to rebuil responseorder
12848:                 $metaentry{':responseorder'}='';
12849:                 $metathesekeys{'responseorder'}=1;
12850:             }
12851:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12852:                 my $origid = $origfiletagids[$index+1];
12853:                 if ($origfiletagids[$index] eq 'part') {
12854: # Original part, part of the problem
12855:                     if ($importedparts) {
12856:                         $metaentry{':partorder'}.=','.$origid;
12857:                     }
12858:                 } elsif ($origfiletagids[$index] eq 'import') {
12859:                     if ($importedparts) {
12860: # We have imported parts at this position
12861:                         if ($importedpartids{$origid} ne '') {
12862:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12863:                         }
12864:                     }
12865:                     if ($importedresponses) {
12866: # We have imported responses at this position
12867:                         if ($importedrespids{$origid} ne '') {
12868:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12869:                         }
12870:                     }
12871:                 } else {
12872: # Original response item, part of the problem
12873:                     if ($importedresponses) {
12874:                         $metaentry{':responseorder'}.=','.$origid;
12875:                     }
12876:                 }
12877:             }
12878:             if ($importedparts) {
12879:                 $metaentry{':partorder'}=~s/^\,//;
12880:             }
12881:             if ($importedresponses) {
12882:                 $metaentry{':responseorder'}=~s/^\,//;
12883:             }
12884:         }
12885: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12886: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12887: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12888:         unless ($liburi) {
12889: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12890:         }
12891: # this is the end of "was not already recently cached
12892:     }
12893:     return $metaentry{':'.$what};
12894: }
12895: 
12896: sub metadata_create_package_def {
12897:     my ($uri,$key,$package,$metathesekeys)=@_;
12898:     my ($pack,$name,$subp)=split(/\&/,$key);
12899:     if ($subp eq 'default') { next; }
12900:     
12901:     if (defined($metaentry{':packages'})) {
12902: 	$metaentry{':packages'}.=','.$package;
12903:     } else {
12904: 	$metaentry{':packages'}=$package;
12905:     }
12906:     my $value=$packagetab{$key};
12907:     my $unikey;
12908:     $unikey='parameter_0_'.$name;
12909:     $metaentry{':'.$unikey.'.part'}=0;
12910:     $$metathesekeys{$unikey}=1;
12911:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12912: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12913:     }
12914:     if (defined($metaentry{':'.$unikey.'.default'})) {
12915: 	$metaentry{':'.$unikey}=
12916: 	    $metaentry{':'.$unikey.'.default'};
12917:     }
12918: }
12919: 
12920: sub metadata_generate_part0 {
12921:     my ($metadata,$metacache,$uri) = @_;
12922:     my %allnames;
12923:     foreach my $metakey (keys(%$metadata)) {
12924: 	if ($metakey=~/^parameter\_(.*)/) {
12925: 	  my $part=$$metacache{':'.$metakey.'.part'};
12926: 	  my $name=$$metacache{':'.$metakey.'.name'};
12927: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12928: 	    $allnames{$name}=$part;
12929: 	  }
12930: 	}
12931:     }
12932:     foreach my $name (keys(%allnames)) {
12933:       $$metadata{"parameter_0_$name"}=1;
12934:       my $key=":parameter_0_$name";
12935:       $$metacache{"$key.part"}='0';
12936:       $$metacache{"$key.name"}=$name;
12937:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12938: 					   $allnames{$name}.'_'.$name.
12939: 					   '.type'};
12940:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12941: 			     '.display'};
12942:       my $expr='[Part: '.$allnames{$name}.']';
12943:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12944:       $$metacache{"$key.display"}=$olddis;
12945:     }
12946: }
12947: 
12948: # ------------------------------------------------------ Devalidate title cache
12949: 
12950: sub devalidate_title_cache {
12951:     my ($url)=@_;
12952:     if (!$env{'request.course.id'}) { return; }
12953:     my $symb=&symbread($url);
12954:     if (!$symb) { return; }
12955:     my $key=$env{'request.course.id'}."\0".$symb;
12956:     &devalidate_cache_new('title',$key);
12957: }
12958: 
12959: # ------------------------------------------------- Get the title of a course
12960: 
12961: sub current_course_title {
12962:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12963: }
12964: # ------------------------------------------------- Get the title of a resource
12965: 
12966: sub gettitle {
12967:     my $urlsymb=shift;
12968:     my $symb=&symbread($urlsymb);
12969:     if ($symb) {
12970: 	my $key=$env{'request.course.id'}."\0".$symb;
12971: 	my ($result,$cached)=&is_cached_new('title',$key);
12972: 	if (defined($cached)) { 
12973: 	    return $result;
12974: 	}
12975: 	my ($map,$resid,$url)=&decode_symb($symb);
12976: 	my $title='';
12977: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12978: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12979: 	} else {
12980: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12981: 		    &GDBM_READER(),0640)) {
12982: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12983: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12984: 		untie(%bighash);
12985: 	    }
12986: 	}
12987: 	$title=~s/\&colon\;/\:/gs;
12988: 	if ($title) {
12989: # Remember both $symb and $title for dynamic metadata
12990:             $accesshash{$symb.'___crstitle'}=$title;
12991:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12992: # Cache this title and then return it
12993: 	    return &do_cache_new('title',$key,$title,600);
12994: 	}
12995: 	$urlsymb=$url;
12996:     }
12997:     my $title=&metadata($urlsymb,'title');
12998:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12999:     return $title;
13000: }
13001: 
13002: sub get_slot {
13003:     my ($which,$cnum,$cdom)=@_;
13004:     if (!$cnum || !$cdom) {
13005: 	(undef,my $courseid)=&whichuser();
13006: 	$cdom=$env{'course.'.$courseid.'.domain'};
13007: 	$cnum=$env{'course.'.$courseid.'.num'};
13008:     }
13009:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13010:     my %slotinfo;
13011:     if (exists($remembered{$key})) {
13012: 	$slotinfo{$which} = $remembered{$key};
13013:     } else {
13014: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13015: 	&Apache::lonhomework::showhash(%slotinfo);
13016: 	my ($tmp)=keys(%slotinfo);
13017: 	if ($tmp=~/^error:/) { return (); }
13018: 	$remembered{$key} = $slotinfo{$which};
13019:     }
13020:     if (ref($slotinfo{$which}) eq 'HASH') {
13021: 	return %{$slotinfo{$which}};
13022:     }
13023:     return $slotinfo{$which};
13024: }
13025: 
13026: sub get_reservable_slots {
13027:     my ($cnum,$cdom,$uname,$udom) = @_;
13028:     my $now = time;
13029:     my $reservable_info;
13030:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13031:     if (exists($remembered{$key})) {
13032:         $reservable_info = $remembered{$key};
13033:     } else {
13034:         my %resv;
13035:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13036:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13037:         $reservable_info = \%resv;
13038:         $remembered{$key} = $reservable_info;
13039:     }
13040:     return $reservable_info;
13041: }
13042: 
13043: sub get_course_slots {
13044:     my ($cnum,$cdom) = @_;
13045:     my $hashid=$cnum.':'.$cdom;
13046:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13047:     if (defined($cached)) {
13048:         if (ref($result) eq 'HASH') {
13049:             return %{$result};
13050:         }
13051:     } else {
13052:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13053:         my ($tmp) = keys(%slots);
13054:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13055:             &do_cache_new('allslots',$hashid,\%slots,600);
13056:             return %slots;
13057:         }
13058:     }
13059:     return;
13060: }
13061: 
13062: sub devalidate_slots_cache {
13063:     my ($cnum,$cdom)=@_;
13064:     my $hashid=$cnum.':'.$cdom;
13065:     &devalidate_cache_new('allslots',$hashid);
13066: }
13067: 
13068: sub get_coursechange {
13069:     my ($cdom,$cnum) = @_;
13070:     if ($cdom eq '' || $cnum eq '') {
13071:         return unless ($env{'request.course.id'});
13072:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13073:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13074:     }
13075:     my $hashid=$cdom.'_'.$cnum;
13076:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13077:     if ((defined($cached)) && ($change ne '')) {
13078:         return $change;
13079:     } else {
13080:         my %crshash;
13081:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13082:         if ($crshash{'internal.contentchange'} eq '') {
13083:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13084:             if ($change eq '') {
13085:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13086:                 $change = $crshash{'internal.created'};
13087:             }
13088:         } else {
13089:             $change = $crshash{'internal.contentchange'};
13090:         }
13091:         my $cachetime = 600;
13092:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13093:     }
13094:     return $change;
13095: }
13096: 
13097: sub devalidate_coursechange_cache {
13098:     my ($cnum,$cdom)=@_;
13099:     my $hashid=$cnum.':'.$cdom;
13100:     &devalidate_cache_new('crschange',$hashid);
13101: }
13102: 
13103: # ------------------------------------------------- Update symbolic store links
13104: 
13105: sub symblist {
13106:     my ($mapname,%newhash)=@_;
13107:     $mapname=&deversion(&declutter($mapname));
13108:     my %hash;
13109:     if (($env{'request.course.fn'}) && (%newhash)) {
13110:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13111:                       &GDBM_WRCREAT(),0640)) {
13112: 	    foreach my $url (keys(%newhash)) {
13113: 		next if ($url eq 'last_known'
13114: 			 && $env{'form.no_update_last_known'});
13115: 		$hash{declutter($url)}=&encode_symb($mapname,
13116: 						    $newhash{$url}->[1],
13117: 						    $newhash{$url}->[0]);
13118:             }
13119:             if (untie(%hash)) {
13120: 		return 'ok';
13121:             }
13122:         }
13123:     }
13124:     return 'error';
13125: }
13126: 
13127: # --------------------------------------------------------------- Verify a symb
13128: 
13129: sub symbverify {
13130:     my ($symb,$thisurl,$encstate)=@_;
13131:     my $thisfn=$thisurl;
13132:     $thisfn=&declutter($thisfn);
13133: # direct jump to resource in page or to a sequence - will construct own symbs
13134:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13135: # check URL part
13136:     my ($map,$resid,$url)=&decode_symb($symb);
13137: 
13138:     unless ($url eq $thisfn) { return 0; }
13139: 
13140:     $symb=&symbclean($symb);
13141:     $thisurl=&deversion($thisurl);
13142:     $thisfn=&deversion($thisfn);
13143: 
13144:     my %bighash;
13145:     my $okay=0;
13146: 
13147:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13148:                             &GDBM_READER(),0640)) {
13149:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13150:             $thisurl =~ s/\?.+$//;
13151:             if ($map =~ m{^uploaded/.+\.page$}) {
13152:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13153:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13154:             }
13155:         }
13156:         my $ids;
13157:         if ($map =~ m{^uploaded/.+\.page$}) {
13158:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13159:         } else {
13160:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13161:         }
13162:         unless ($ids) {
13163:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13164:             $ids=$bighash{$idkey};
13165:         }
13166:         if ($ids) {
13167: # ------------------------------------------------------------------- Has ID(s)
13168:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13169:                 $symb =~ s/\?.+$//;
13170:             }
13171: 	    foreach my $id (split(/\,/,$ids)) {
13172: 	       my ($mapid,$resid)=split(/\./,$id);
13173:                if (
13174:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13175:    eq $symb) {
13176:                    if (ref($encstate)) {
13177:                        $$encstate = $bighash{'encrypted_'.$id};
13178:                    }
13179: 		   if (($env{'request.role.adv'}) ||
13180: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13181:                        ($thisurl eq '/adm/navmaps')) {
13182: 		       $okay=1;
13183:                        last;
13184: 		   }
13185: 	       }
13186: 	   }
13187:         }
13188: 	untie(%bighash);
13189:     }
13190:     return $okay;
13191: }
13192: 
13193: # --------------------------------------------------------------- Clean-up symb
13194: 
13195: sub symbclean {
13196:     my $symb=shift;
13197:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13198: # remove version from map
13199:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13200: 
13201: # remove version from URL
13202:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13203: 
13204: # remove wrapper
13205: 
13206:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13207:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13208:     return $symb;
13209: }
13210: 
13211: # ---------------------------------------------- Split symb to find map and url
13212: 
13213: sub encode_symb {
13214:     my ($map,$resid,$url)=@_;
13215:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13216: }
13217: 
13218: sub decode_symb {
13219:     my $symb=shift;
13220:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13221:     my ($map,$resid,$url)=split(/___/,$symb);
13222:     return (&fixversion($map),$resid,&fixversion($url));
13223: }
13224: 
13225: sub fixversion {
13226:     my $fn=shift;
13227:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13228:     my %bighash;
13229:     my $uri=&clutter($fn);
13230:     my $key=$env{'request.course.id'}.'_'.$uri;
13231: # is this cached?
13232:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13233:     if (defined($cached)) { return $result; }
13234: # unfortunately not cached, or expired
13235:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13236: 	    &GDBM_READER(),0640)) {
13237:  	if ($bighash{'version_'.$uri}) {
13238:  	    my $version=$bighash{'version_'.$uri};
13239:  	    unless (($version eq 'mostrecent') || 
13240: 		    ($version==&getversion($uri))) {
13241:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13242:  	    }
13243:  	}
13244:  	untie %bighash;
13245:     }
13246:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13247: }
13248: 
13249: sub deversion {
13250:     my $url=shift;
13251:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13252:     return $url;
13253: }
13254: 
13255: # ------------------------------------------------------ Return symb list entry
13256: 
13257: sub symbread {
13258:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
13259:     my $cache_str='request.symbread.cached.'.$thisfn;
13260:     if (defined($env{$cache_str})) {
13261:         if ($ignorecachednull) {
13262:             return $env{$cache_str} unless ($env{$cache_str} eq '');
13263:         } else {
13264:             return $env{$cache_str};
13265:         }
13266:     }
13267: # no filename provided? try from environment
13268:     unless ($thisfn) {
13269:         if ($env{'request.symb'}) {
13270: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
13271: 	}
13272: 	$thisfn=$env{'request.filename'};
13273:     }
13274:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13275: # is that filename actually a symb? Verify, clean, and return
13276:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13277: 	if (&symbverify($thisfn,$1)) {
13278: 	    return $env{$cache_str}=&symbclean($thisfn);
13279: 	}
13280:     }
13281:     $thisfn=declutter($thisfn);
13282:     my %hash;
13283:     my %bighash;
13284:     my $syval='';
13285:     if (($env{'request.course.fn'}) && ($thisfn)) {
13286:         my $targetfn = $thisfn;
13287:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13288:             $targetfn = 'adm/wrapper/'.$thisfn;
13289:         }
13290: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13291: 	    $targetfn=$1;
13292: 	}
13293:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13294:                       &GDBM_READER(),0640)) {
13295: 	    $syval=$hash{$targetfn};
13296:             untie(%hash);
13297:         }
13298: # ---------------------------------------------------------- There was an entry
13299:         if ($syval) {
13300: 	    #unless ($syval=~/\_\d+$/) {
13301: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13302: 		    #&appenv({'request.ambiguous' => $thisfn});
13303: 		    #return $env{$cache_str}='';
13304: 		#}    
13305: 		#$syval.=$1;
13306: 	    #}
13307:         } else {
13308: # ------------------------------------------------------- Was not in symb table
13309:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13310:                             &GDBM_READER(),0640)) {
13311: # ---------------------------------------------- Get ID(s) for current resource
13312:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13313:               unless ($ids) { 
13314:                  $ids=$bighash{'ids_/'.$thisfn};
13315:               }
13316:               unless ($ids) {
13317: # alias?
13318: 		  $ids=$bighash{'mapalias_'.$thisfn};
13319:               }
13320:               if ($ids) {
13321: # ------------------------------------------------------------------- Has ID(s)
13322:                  my @possibilities=split(/\,/,$ids);
13323:                  if ($#possibilities==0) {
13324: # ----------------------------------------------- There is only one possibility
13325: 		     my ($mapid,$resid)=split(/\./,$ids);
13326: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13327: 						    $resid,$thisfn);
13328:                      if (ref($possibles) eq 'HASH') {
13329:                          $possibles->{$syval} = 1;    
13330:                      }
13331:                      if ($checkforblock) {
13332:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
13333:                          if (@blockers) {
13334:                              $syval = '';
13335:                              return;
13336:                          }
13337:                      }
13338:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13339: # ------------------------------------------ There is more than one possibility
13340:                      my $realpossible=0;
13341:                      foreach my $id (@possibilities) {
13342: 			 my $file=$bighash{'src_'.$id};
13343:                          my $canaccess;
13344:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13345:                              $canaccess = 1;
13346:                          } else { 
13347:                              $canaccess = &allowed('bre',$file);
13348:                          }
13349:                          if ($canaccess) {
13350:          		     my ($mapid,$resid)=split(/\./,$id);
13351:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13352:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13353: 						             $resid,$thisfn);
13354:                                  if (ref($possibles) eq 'HASH') {
13355:                                      $possibles->{$syval} = 1;
13356:                                  }
13357:                                  if ($checkforblock) {
13358:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
13359:                                      unless (@blockers > 0) {
13360:                                          $syval = $poss_syval;
13361:                                          $realpossible++;
13362:                                      }
13363:                                  } else {
13364:                                      $syval = $poss_syval;
13365:                                      $realpossible++;
13366:                                  }
13367:                              }
13368: 			 }
13369:                      }
13370: 		     if ($realpossible!=1) { $syval=''; }
13371:                  } else {
13372:                      $syval='';
13373:                  }
13374: 	      }
13375:               untie(%bighash);
13376:            }
13377:         }
13378:         if ($syval) {
13379: 	    return $env{$cache_str}=$syval;
13380:         }
13381:     }
13382:     &appenv({'request.ambiguous' => $thisfn});
13383:     return $env{$cache_str}='';
13384: }
13385: 
13386: # ---------------------------------------------------------- Return random seed
13387: 
13388: sub numval {
13389:     my $txt=shift;
13390:     $txt=~tr/A-J/0-9/;
13391:     $txt=~tr/a-j/0-9/;
13392:     $txt=~tr/K-T/0-9/;
13393:     $txt=~tr/k-t/0-9/;
13394:     $txt=~tr/U-Z/0-5/;
13395:     $txt=~tr/u-z/0-5/;
13396:     $txt=~s/\D//g;
13397:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13398:     return int($txt);
13399: }
13400: 
13401: sub numval2 {
13402:     my $txt=shift;
13403:     $txt=~tr/A-J/0-9/;
13404:     $txt=~tr/a-j/0-9/;
13405:     $txt=~tr/K-T/0-9/;
13406:     $txt=~tr/k-t/0-9/;
13407:     $txt=~tr/U-Z/0-5/;
13408:     $txt=~tr/u-z/0-5/;
13409:     $txt=~s/\D//g;
13410:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13411:     my $total;
13412:     foreach my $val (@txts) { $total+=$val; }
13413:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13414:     return int($total);
13415: }
13416: 
13417: sub numval3 {
13418:     use integer;
13419:     my $txt=shift;
13420:     $txt=~tr/A-J/0-9/;
13421:     $txt=~tr/a-j/0-9/;
13422:     $txt=~tr/K-T/0-9/;
13423:     $txt=~tr/k-t/0-9/;
13424:     $txt=~tr/U-Z/0-5/;
13425:     $txt=~tr/u-z/0-5/;
13426:     $txt=~s/\D//g;
13427:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13428:     my $total;
13429:     foreach my $val (@txts) { $total+=$val; }
13430:     if ($_64bit) { $total=(($total<<32)>>32); }
13431:     return $total;
13432: }
13433: 
13434: sub digest {
13435:     my ($data)=@_;
13436:     my $digest=&Digest::MD5::md5($data);
13437:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13438:     my ($e,$f);
13439:     {
13440:         use integer;
13441:         $e=($a+$b);
13442:         $f=($c+$d);
13443:         if ($_64bit) {
13444:             $e=(($e<<32)>>32);
13445:             $f=(($f<<32)>>32);
13446:         }
13447:     }
13448:     if (wantarray) {
13449: 	return ($e,$f);
13450:     } else {
13451: 	my $g;
13452: 	{
13453: 	    use integer;
13454: 	    $g=($e+$f);
13455: 	    if ($_64bit) {
13456: 		$g=(($g<<32)>>32);
13457: 	    }
13458: 	}
13459: 	return $g;
13460:     }
13461: }
13462: 
13463: sub latest_rnd_algorithm_id {
13464:     return '64bit5';
13465: }
13466: 
13467: sub get_rand_alg {
13468:     my ($courseid)=@_;
13469:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13470:     if ($courseid) {
13471: 	return $env{"course.$courseid.rndseed"};
13472:     }
13473:     return &latest_rnd_algorithm_id();
13474: }
13475: 
13476: sub validCODE {
13477:     my ($CODE)=@_;
13478:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13479:     return 0;
13480: }
13481: 
13482: sub getCODE {
13483:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13484:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13485: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13486: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13487: 	return $Apache::lonhomework::history{'resource.CODE'};
13488:     }
13489:     return undef;
13490: }
13491: #
13492: #  Determines the random seed for a specific context:
13493: #
13494: # parameters:
13495: #   symb      - in course context the symb for the seed.
13496: #   course_id - The course id of the form domain_coursenum.
13497: #   domain    - Domain for the user.
13498: #   course    - Course for the user.
13499: #   cenv      - environment of the course.
13500: #
13501: # NOTE:
13502: #   All parameters are picked out of the environment if missing
13503: #   or not defined.
13504: #   If a symb cannot be determined the current time is used instead.
13505: #
13506: #  For a given well defined symb, courside, domain, username,
13507: #  and course environment, the seed is reproducible.
13508: #
13509: sub rndseed {
13510:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13511:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13512:     if (!defined($symb)) {
13513: 	unless ($symb=$wsymb) { return time; }
13514:     }
13515:     if (!defined $courseid) { 
13516: 	$courseid=$wcourseid; 
13517:     }
13518:     if (!defined $domain) { $domain=$wdomain; }
13519:     if (!defined $username) { $username=$wusername }
13520: 
13521:     my $which;
13522:     if (defined($cenv->{'rndseed'})) {
13523: 	$which = $cenv->{'rndseed'};
13524:     } else {
13525: 	$which =&get_rand_alg($courseid);
13526:     }
13527:     if (defined(&getCODE())) {
13528: 
13529: 	if ($which eq '64bit5') {
13530: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13531: 	} elsif ($which eq '64bit4') {
13532: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13533: 	} else {
13534: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13535: 	}
13536:     } elsif ($which eq '64bit5') {
13537: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13538:     } elsif ($which eq '64bit4') {
13539: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13540:     } elsif ($which eq '64bit3') {
13541: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13542:     } elsif ($which eq '64bit2') {
13543: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13544:     } elsif ($which eq '64bit') {
13545: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13546:     }
13547:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13548: }
13549: 
13550: sub rndseed_32bit {
13551:     my ($symb,$courseid,$domain,$username)=@_;
13552:     {
13553: 	use integer;
13554: 	my $symbchck=unpack("%32C*",$symb) << 27;
13555: 	my $symbseed=numval($symb) << 22;
13556: 	my $namechck=unpack("%32C*",$username) << 17;
13557: 	my $nameseed=numval($username) << 12;
13558: 	my $domainseed=unpack("%32C*",$domain) << 7;
13559: 	my $courseseed=unpack("%32C*",$courseid);
13560: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13561: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13562: 	#&logthis("rndseed :$num:$symb");
13563: 	if ($_64bit) { $num=(($num<<32)>>32); }
13564: 	return $num;
13565:     }
13566: }
13567: 
13568: sub rndseed_64bit {
13569:     my ($symb,$courseid,$domain,$username)=@_;
13570:     {
13571: 	use integer;
13572: 	my $symbchck=unpack("%32S*",$symb) << 21;
13573: 	my $symbseed=numval($symb) << 10;
13574: 	my $namechck=unpack("%32S*",$username);
13575: 	
13576: 	my $nameseed=numval($username) << 21;
13577: 	my $domainseed=unpack("%32S*",$domain) << 10;
13578: 	my $courseseed=unpack("%32S*",$courseid);
13579: 	
13580: 	my $num1=$symbchck+$symbseed+$namechck;
13581: 	my $num2=$nameseed+$domainseed+$courseseed;
13582: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13583: 	#&logthis("rndseed :$num:$symb");
13584: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13585: 	return "$num1,$num2";
13586:     }
13587: }
13588: 
13589: sub rndseed_64bit2 {
13590:     my ($symb,$courseid,$domain,$username)=@_;
13591:     {
13592: 	use integer;
13593: 	# strings need to be an even # of cahracters long, it it is odd the
13594:         # last characters gets thrown away
13595: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13596: 	my $symbseed=numval($symb) << 10;
13597: 	my $namechck=unpack("%32S*",$username.' ');
13598: 	
13599: 	my $nameseed=numval($username) << 21;
13600: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13601: 	my $courseseed=unpack("%32S*",$courseid.' ');
13602: 	
13603: 	my $num1=$symbchck+$symbseed+$namechck;
13604: 	my $num2=$nameseed+$domainseed+$courseseed;
13605: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13606: 	#&logthis("rndseed :$num:$symb");
13607: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13608: 	return "$num1,$num2";
13609:     }
13610: }
13611: 
13612: sub rndseed_64bit3 {
13613:     my ($symb,$courseid,$domain,$username)=@_;
13614:     {
13615: 	use integer;
13616: 	# strings need to be an even # of cahracters long, it it is odd the
13617:         # last characters gets thrown away
13618: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13619: 	my $symbseed=numval2($symb) << 10;
13620: 	my $namechck=unpack("%32S*",$username.' ');
13621: 	
13622: 	my $nameseed=numval2($username) << 21;
13623: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13624: 	my $courseseed=unpack("%32S*",$courseid.' ');
13625: 	
13626: 	my $num1=$symbchck+$symbseed+$namechck;
13627: 	my $num2=$nameseed+$domainseed+$courseseed;
13628: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13629: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13630: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13631: 	
13632: 	return "$num1:$num2";
13633:     }
13634: }
13635: 
13636: sub rndseed_64bit4 {
13637:     my ($symb,$courseid,$domain,$username)=@_;
13638:     {
13639: 	use integer;
13640: 	# strings need to be an even # of cahracters long, it it is odd the
13641:         # last characters gets thrown away
13642: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13643: 	my $symbseed=numval3($symb) << 10;
13644: 	my $namechck=unpack("%32S*",$username.' ');
13645: 	
13646: 	my $nameseed=numval3($username) << 21;
13647: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13648: 	my $courseseed=unpack("%32S*",$courseid.' ');
13649: 	
13650: 	my $num1=$symbchck+$symbseed+$namechck;
13651: 	my $num2=$nameseed+$domainseed+$courseseed;
13652: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13653: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13654: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13655: 	
13656: 	return "$num1:$num2";
13657:     }
13658: }
13659: 
13660: sub rndseed_64bit5 {
13661:     my ($symb,$courseid,$domain,$username)=@_;
13662:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13663:     return "$num1:$num2";
13664: }
13665: 
13666: sub rndseed_CODE_64bit {
13667:     my ($symb,$courseid,$domain,$username)=@_;
13668:     {
13669: 	use integer;
13670: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13671: 	my $symbseed=numval2($symb);
13672: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13673: 	my $CODEseed=numval(&getCODE());
13674: 	my $courseseed=unpack("%32S*",$courseid.' ');
13675: 	my $num1=$symbseed+$CODEchck;
13676: 	my $num2=$CODEseed+$courseseed+$symbchck;
13677: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13678: 	#&logthis("rndseed :$num1:$num2:$symb");
13679: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13680: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13681: 	return "$num1:$num2";
13682:     }
13683: }
13684: 
13685: sub rndseed_CODE_64bit4 {
13686:     my ($symb,$courseid,$domain,$username)=@_;
13687:     {
13688: 	use integer;
13689: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13690: 	my $symbseed=numval3($symb);
13691: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13692: 	my $CODEseed=numval3(&getCODE());
13693: 	my $courseseed=unpack("%32S*",$courseid.' ');
13694: 	my $num1=$symbseed+$CODEchck;
13695: 	my $num2=$CODEseed+$courseseed+$symbchck;
13696: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13697: 	#&logthis("rndseed :$num1:$num2:$symb");
13698: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13699: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13700: 	return "$num1:$num2";
13701:     }
13702: }
13703: 
13704: sub rndseed_CODE_64bit5 {
13705:     my ($symb,$courseid,$domain,$username)=@_;
13706:     my $code = &getCODE();
13707:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13708:     return "$num1:$num2";
13709: }
13710: 
13711: sub setup_random_from_rndseed {
13712:     my ($rndseed)=@_;
13713:     if ($rndseed =~/([,:])/) {
13714:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13715:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13716:             &Math::Random::random_set_seed_from_phrase($rndseed);
13717:         } else {
13718:             &Math::Random::random_set_seed($num1,$num2);
13719:         }
13720:     } else {
13721: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13722:     }
13723: }
13724: 
13725: sub latest_receipt_algorithm_id {
13726:     return 'receipt3';
13727: }
13728: 
13729: sub recunique {
13730:     my $fucourseid=shift;
13731:     my $unique;
13732:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13733: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13734: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13735:     } else {
13736: 	$unique=$perlvar{'lonReceipt'};
13737:     }
13738:     return unpack("%32C*",$unique);
13739: }
13740: 
13741: sub recprefix {
13742:     my $fucourseid=shift;
13743:     my $prefix;
13744:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13745: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13746: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13747:     } else {
13748: 	$prefix=$perlvar{'lonHostID'};
13749:     }
13750:     return unpack("%32C*",$prefix);
13751: }
13752: 
13753: sub ireceipt {
13754:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13755: 
13756:     my $return =&recprefix($fucourseid).'-';
13757: 
13758:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13759: 	$env{'request.state'} eq 'construct') {
13760: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13761: 	return $return;
13762:     }
13763: 
13764:     my $cuname=unpack("%32C*",$funame);
13765:     my $cudom=unpack("%32C*",$fudom);
13766:     my $cucourseid=unpack("%32C*",$fucourseid);
13767:     my $cusymb=unpack("%32C*",$fusymb);
13768:     my $cunique=&recunique($fucourseid);
13769:     my $cpart=unpack("%32S*",$part);
13770:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13771: 
13772: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13773: 			       
13774: 	$return.= ($cunique%$cuname+
13775: 		   $cunique%$cudom+
13776: 		   $cusymb%$cuname+
13777: 		   $cusymb%$cudom+
13778: 		   $cucourseid%$cuname+
13779: 		   $cucourseid%$cudom+
13780: 		   $cpart%$cuname+
13781: 		   $cpart%$cudom);
13782:     } else {
13783: 	$return.= ($cunique%$cuname+
13784: 		   $cunique%$cudom+
13785: 		   $cusymb%$cuname+
13786: 		   $cusymb%$cudom+
13787: 		   $cucourseid%$cuname+
13788: 		   $cucourseid%$cudom);
13789:     }
13790:     return $return;
13791: }
13792: 
13793: sub receipt {
13794:     my ($part)=@_;
13795:     my ($symb,$courseid,$domain,$name) = &whichuser();
13796:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13797: }
13798: 
13799: sub whichuser {
13800:     my ($passedsymb)=@_;
13801:     my ($symb,$courseid,$domain,$name,$publicuser);
13802:     if (defined($env{'form.grade_symb'})) {
13803: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13804: 	my $allowed=&allowed('vgr',$tmp_courseid);
13805: 	if (!$allowed &&
13806: 	    exists($env{'request.course.sec'}) &&
13807: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13808: 	    $allowed=&allowed('vgr',$tmp_courseid.
13809: 			      '/'.$env{'request.course.sec'});
13810: 	}
13811: 	if ($allowed) {
13812: 	    ($symb)=&get_env_multiple('form.grade_symb');
13813: 	    $courseid=$tmp_courseid;
13814: 	    ($domain)=&get_env_multiple('form.grade_domain');
13815: 	    ($name)=&get_env_multiple('form.grade_username');
13816: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13817: 	}
13818:     }
13819:     if (!$passedsymb) {
13820: 	$symb=&symbread();
13821:     } else {
13822: 	$symb=$passedsymb;
13823:     }
13824:     $courseid=$env{'request.course.id'};
13825:     $domain=$env{'user.domain'};
13826:     $name=$env{'user.name'};
13827:     if ($name eq 'public' && $domain eq 'public') {
13828: 	if (!defined($env{'form.username'})) {
13829: 	    $env{'form.username'}.=time.rand(10000000);
13830: 	}
13831: 	$name.=$env{'form.username'};
13832:     }
13833:     return ($symb,$courseid,$domain,$name,$publicuser);
13834: 
13835: }
13836: 
13837: # ------------------------------------------------------------ Serves up a file
13838: # returns either the contents of the file or 
13839: # -1 if the file doesn't exist
13840: #
13841: # if the target is a file that was uploaded via DOCS, 
13842: # a check will be made to see if a current copy exists on the local server,
13843: # if it does this will be served, otherwise a copy will be retrieved from
13844: # the home server for the course and stored in /home/httpd/html/userfiles on
13845: # the local server.   
13846: 
13847: sub getfile {
13848:     my ($file) = @_;
13849:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13850:     &repcopy($file);
13851:     return &readfile($file);
13852: }
13853: 
13854: sub repcopy_userfile {
13855:     my ($file)=@_;
13856:     my $londocroot = $perlvar{'lonDocRoot'};
13857:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13858:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13859:     my ($cdom,$cnum,$filename) = 
13860: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13861:     my $uri="/uploaded/$cdom/$cnum/$filename";
13862:     if (-e "$file") {
13863: # we already have a local copy, check it out
13864: 	my @fileinfo = stat($file);
13865: 	my $rtncode;
13866: 	my $info;
13867: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13868: 	if ($lwpresp ne 'ok') {
13869: # there is no such file anymore, even though we had a local copy
13870: 	    if ($rtncode eq '404') {
13871: 		unlink($file);
13872: 	    }
13873: 	    return -1;
13874: 	}
13875: 	if ($info < $fileinfo[9]) {
13876: # nice, the file we have is up-to-date, just say okay
13877: 	    return 'ok';
13878: 	} else {
13879: # the file is outdated, get rid of it
13880: 	    unlink($file);
13881: 	}
13882:     }
13883: # one way or the other, at this point, we don't have the file
13884: # construct the correct path for the file
13885:     my @parts = ($cdom,$cnum); 
13886:     if ($filename =~ m|^(.+)/[^/]+$|) {
13887: 	push @parts, split(/\//,$1);
13888:     }
13889:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13890:     foreach my $part (@parts) {
13891: 	$path .= '/'.$part;
13892: 	if (!-e $path) {
13893: 	    mkdir($path,0770);
13894: 	}
13895:     }
13896: # now the path exists for sure
13897: # get a user agent
13898:     my $transferfile=$file.'.in.transfer';
13899: # FIXME: this should flock
13900:     if (-e $transferfile) { return 'ok'; }
13901:     my $request;
13902:     $uri=~s/^\///;
13903:     my $homeserver = &homeserver($cnum,$cdom);
13904:     my $hostname = &hostname($homeserver);
13905:     my $protocol = $protocol{$homeserver};
13906:     $protocol = 'http' if ($protocol ne 'https');
13907:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13908:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13909: # did it work?
13910:     if ($response->is_error()) {
13911: 	unlink($transferfile);
13912: 	&logthis("Userfile repcopy failed for $uri");
13913: 	return -1;
13914:     }
13915: # worked, rename the transfer file
13916:     rename($transferfile,$file);
13917:     return 'ok';
13918: }
13919: 
13920: sub tokenwrapper {
13921:     my $uri=shift;
13922:     $uri=~s|^https?\://([^/]+)||;
13923:     $uri=~s|^/||;
13924:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13925:     my $token=$1;
13926:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13927:     if ($udom && $uname && $file) {
13928: 	$file=~s|(\?\.*)*$||;
13929:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13930:         my $homeserver = &homeserver($uname,$udom);
13931:         my $hostname = &hostname($homeserver);
13932:         my $protocol = $protocol{$homeserver};
13933:         $protocol = 'http' if ($protocol ne 'https');
13934:         return $protocol.'://'.$hostname.'/'.$uri.
13935:                (($uri=~/\?/)?'&':'?').'token='.$token.
13936:                                '&tokenissued='.$perlvar{'lonHostID'};
13937:     } else {
13938:         return '/adm/notfound.html';
13939:     }
13940: }
13941: 
13942: # call with reqtype HEAD: get last modification time
13943: # call with reqtype GET: get the file contents
13944: # Do not call this with reqtype GET for large files! It loads everything into memory
13945: #
13946: sub getuploaded {
13947:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13948:     $uri=~s/^\///;
13949:     my $homeserver = &homeserver($cnum,$cdom);
13950:     my $hostname = &hostname($homeserver);
13951:     my $protocol = $protocol{$homeserver};
13952:     $protocol = 'http' if ($protocol ne 'https');
13953:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13954:     my $request=new HTTP::Request($reqtype,$uri);
13955:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13956:     $$rtncode = $response->code;
13957:     if (! $response->is_success()) {
13958: 	return 'failed';
13959:     }      
13960:     if ($reqtype eq 'HEAD') {
13961: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13962:     } elsif ($reqtype eq 'GET') {
13963: 	$$info = $response->content;
13964:     }
13965:     return 'ok';
13966: }
13967: 
13968: sub readfile {
13969:     my $file = shift;
13970:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13971:     my $fh;
13972:     open($fh,"<",$file);
13973:     my $a='';
13974:     while (my $line = <$fh>) { $a .= $line; }
13975:     return $a;
13976: }
13977: 
13978: sub filelocation {
13979:     my ($dir,$file) = @_;
13980:     my $location;
13981:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13982: 
13983:     if ($file =~ m-^/adm/-) {
13984: 	$file=~s-^/adm/wrapper/-/-;
13985: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13986:     }
13987: 
13988:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13989:         $location = $file;
13990:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13991:         my ($udom,$uname,$filename)=
13992:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13993:         my $home=&homeserver($uname,$udom);
13994:         my $is_me=0;
13995:         my @ids=&current_machine_ids();
13996:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13997:         if ($is_me) {
13998:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13999:         } else {
14000:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14001:   	      $udom.'/'.$uname.'/'.$filename;
14002:         }
14003:     } elsif ($file =~ m-^/adm/-) {
14004: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14005:     } else {
14006:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14007:         $file=~s:^/(res|priv)/:/:;
14008:         my $space=$1;
14009:         if ( !( $file =~ m:^/:) ) {
14010:             $location = $dir. '/'.$file;
14011:         } else {
14012:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14013:         }
14014:     }
14015:     $location=~s://+:/:g; # remove duplicate /
14016:     while ($location=~m{/\.\./}) {
14017: 	if ($location =~ m{/[^/]+/\.\./}) {
14018: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14019: 	} else {
14020: 	    $location=~ s{/\.\./}{/}g;
14021: 	}
14022:     } #remove dir/..
14023:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14024:     return $location;
14025: }
14026: 
14027: sub hreflocation {
14028:     my ($dir,$file)=@_;
14029:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14030: 	$file=filelocation($dir,$file);
14031:     } elsif ($file=~m-^/adm/-) {
14032: 	$file=~s-^/adm/wrapper/-/-;
14033: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14034:     }
14035:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14036: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14037:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14038: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14039: 	        {/uploaded/$1/$2/}x;
14040:     }
14041:     if ($file=~ m{^/userfiles/}) {
14042: 	$file =~ s{^/userfiles/}{/uploaded/};
14043:     }
14044:     return $file;
14045: }
14046: 
14047: 
14048: 
14049: 
14050: 
14051: sub current_machine_domains {
14052:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14053: }
14054: 
14055: sub machine_domains {
14056:     my ($hostname) = @_;
14057:     my @domains;
14058:     my %hostname = &all_hostnames();
14059:     while( my($id, $name) = each(%hostname)) {
14060: #	&logthis("-$id-$name-$hostname-");
14061: 	if ($hostname eq $name) {
14062: 	    push(@domains,&host_domain($id));
14063: 	}
14064:     }
14065:     return @domains;
14066: }
14067: 
14068: sub current_machine_ids {
14069:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14070: }
14071: 
14072: sub machine_ids {
14073:     my ($hostname) = @_;
14074:     $hostname ||= &hostname($perlvar{'lonHostID'});
14075:     my @ids;
14076:     my %name_to_host = &all_names();
14077:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14078: 	return @{ $name_to_host{$hostname} };
14079:     }
14080:     return;
14081: }
14082: 
14083: sub additional_machine_domains {
14084:     my @domains;
14085:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
14086:     while( my $line = <$fh>) {
14087:         $line =~ s/\s//g;
14088:         push(@domains,$line);
14089:     }
14090:     return @domains;
14091: }
14092: 
14093: sub default_login_domain {
14094:     my $domain = $perlvar{'lonDefDomain'};
14095:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14096:     foreach my $posdom (&current_machine_domains(),
14097:                         &additional_machine_domains()) {
14098:         if (lc($posdom) eq lc($testdomain)) {
14099:             $domain=$posdom;
14100:             last;
14101:         }
14102:     }
14103:     return $domain;
14104: }
14105: 
14106: sub shared_institution {
14107:     my ($dom) = @_;
14108:     my $same_intdom;
14109:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
14110:     if ($hostintdom ne '') {
14111:         my %iphost = &get_iphost();
14112:         my $primary_id = &domain($dom,'primary');
14113:         my $primary_ip = &get_host_ip($primary_id);
14114:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14115:             foreach my $id (@{$iphost{$primary_ip}}) {
14116:                 my $intdom = &internet_dom($id);
14117:                 if ($intdom eq $hostintdom) {
14118:                     $same_intdom = 1;
14119:                     last;
14120:                 }
14121:             }
14122:         }
14123:     }
14124:     return $same_intdom;
14125: }
14126: 
14127: sub uses_sts {
14128:     my ($ignore_cache) = @_;
14129:     my $lonhost = $perlvar{'lonHostID'};
14130:     my $hostname = &hostname($lonhost);
14131:     my $sts_on;
14132:     if ($protocol{$lonhost} eq 'https') {
14133:         my $cachetime = 12*3600;
14134:         if (!$ignore_cache) {
14135:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14136:             if (defined($cached)) {
14137:                 return $sts_on;
14138:             }
14139:         }
14140:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14141:         my $request=new HTTP::Request('HEAD',$url);
14142:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14143:         if ($response->is_success) {
14144:             my $has_sts = $response->header('Strict-Transport-Security');
14145:             if ($has_sts eq '') {
14146:                 $sts_on = 0;
14147:             } else {
14148:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14149:                     my $maxage = $1;
14150:                     if ($maxage) {
14151:                         $sts_on = 1;
14152:                     } else {
14153:                         $sts_on = 0;
14154:                     }
14155:                 } else {
14156:                     $sts_on = 0;
14157:                 }
14158:             }
14159:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14160:         }
14161:     }
14162:     return;
14163: }
14164: 
14165: # ------------------------------------------------------------- Declutters URLs
14166: 
14167: sub declutter {
14168:     my $thisfn=shift;
14169:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14170:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14171:         $thisfn=~s{^/home/httpd/html}{};
14172:     }
14173:     $thisfn=~s/^\///;
14174:     $thisfn=~s|^adm/wrapper/||;
14175:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14176:     $thisfn=~s/^res\///;
14177:     $thisfn=~s/^priv\///;
14178:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14179:         $thisfn=~s/\?.+$//;
14180:     }
14181:     return $thisfn;
14182: }
14183: 
14184: # ------------------------------------------------------------- Clutter up URLs
14185: 
14186: sub clutter {
14187:     my $thisfn='/'.&declutter(shift);
14188:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14189: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14190:        $thisfn='/res'.$thisfn; 
14191:     }
14192:     if ($thisfn !~m|^/adm|) {
14193: 	if ($thisfn =~ m|^/ext/|) {
14194: 	    $thisfn='/adm/wrapper'.$thisfn;
14195: 	} else {
14196: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14197: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14198: 	    if ($embstyle eq 'ssi'
14199: 		|| ($embstyle eq 'hdn')
14200: 		|| ($embstyle eq 'rat')
14201: 		|| ($embstyle eq 'prv')
14202: 		|| ($embstyle eq 'ign')) {
14203: 		#do nothing with these
14204: 	    } elsif (($embstyle eq 'img') 
14205: 		|| ($embstyle eq 'emb')
14206: 		|| ($embstyle eq 'wrp')) {
14207: 		$thisfn='/adm/wrapper'.$thisfn;
14208: 	    } elsif ($embstyle eq 'unk'
14209: 		     && $thisfn!~/\.(sequence|page)$/) {
14210: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14211: 	    } else {
14212: #		&logthis("Got a blank emb style");
14213: 	    }
14214: 	}
14215:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14216:         $thisfn='/adm/wrapper'.$thisfn;
14217:     }
14218:     return $thisfn;
14219: }
14220: 
14221: sub clutter_with_no_wrapper {
14222:     my $uri = &clutter(shift);
14223:     if ($uri =~ m-^/adm/-) {
14224: 	$uri =~ s-^/adm/wrapper/-/-;
14225: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14226:     }
14227:     return $uri;
14228: }
14229: 
14230: sub freeze_escape {
14231:     my ($value)=@_;
14232:     if (ref($value)) {
14233: 	$value=&nfreeze($value);
14234: 	return '__FROZEN__'.&escape($value);
14235:     }
14236:     return &escape($value);
14237: }
14238: 
14239: 
14240: sub thaw_unescape {
14241:     my ($value)=@_;
14242:     if ($value =~ /^__FROZEN__/) {
14243: 	substr($value,0,10,undef);
14244: 	$value=&unescape($value);
14245: 	return &thaw($value);
14246:     }
14247:     return &unescape($value);
14248: }
14249: 
14250: sub correct_line_ends {
14251:     my ($result)=@_;
14252:     $$result =~s/\r\n/\n/mg;
14253:     $$result =~s/\r/\n/mg;
14254: }
14255: # ================================================================ Main Program
14256: 
14257: sub goodbye {
14258:    &logthis("Starting Shut down");
14259: #not converted to using infrastruture and probably shouldn't be
14260:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14261: #converted
14262: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14263:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14264: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14265: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14266: #1.1 only
14267: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14268: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14269: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14270: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14271:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14272:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14273:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14274:    &flushcourselogs();
14275:    &logthis("Shutting down");
14276: }
14277: 
14278: sub get_dns {
14279:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14280:     if (!$ignore_cache) {
14281: 	my ($content,$cached)=
14282: 	    &Apache::lonnet::is_cached_new('dns',$url);
14283: 	if ($cached) {
14284: 	    &$func($content,$hashref);
14285: 	    return;
14286: 	}
14287:     }
14288: 
14289:     my %alldns;
14290:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14291:         foreach my $dns (<$config>) {
14292: 	    next if ($dns !~ /^\^(\S*)/x);
14293:             my $line = $1;
14294:             my ($host,$protocol) = split(/:/,$line);
14295:             if ($protocol ne 'https') {
14296:                 $protocol = 'http';
14297:             }
14298: 	    $alldns{$host} = $protocol;
14299:         }
14300:         close($config);
14301:     }
14302:     while (%alldns) {
14303: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14304: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14305:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14306:         delete($alldns{$dns});
14307: 	next if ($response->is_error());
14308:         if ($url eq '/adm/dns/loncapaCRL') {
14309:             return &$func($response);
14310:         } else {
14311: 	    my @content = split("\n",$response->content);
14312: 	    unless ($nocache) {
14313: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14314: 	    }
14315: 	    &$func(\@content,$hashref);
14316:             return;
14317:         }
14318:     }
14319:     my $which = (split('/',$url,4))[3];
14320:     if ($which eq 'loncapaCRL') {
14321:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14322:         if (-e $diskfile) {
14323:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14324:         } else {
14325:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14326:         }
14327:     } else {
14328:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14329:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14330:             my @content = <$config>;
14331:             close($config);
14332:             &$func(\@content,$hashref);
14333:         }
14334:     }
14335:     return;
14336: }
14337: 
14338: # ------------------------------------------------------Get DNS checksums file
14339: sub parse_dns_checksums_tab {
14340:     my ($lines,$hashref) = @_;
14341:     my $lonhost = $perlvar{'lonHostID'};
14342:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14343:     my $loncaparev = &get_server_loncaparev($machine_dom);
14344:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14345:     my $webconfdir = '/etc/httpd/conf';
14346:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14347:         $webconfdir = '/etc/apache2';
14348:     } elsif ($distro =~ /^sles(\d+)$/) {
14349:         if ($1 >= 10) {
14350:             $webconfdir = '/etc/apache2';
14351:         }
14352:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14353:         if ($1 >= 10.0) {
14354:             $webconfdir = '/etc/apache2';
14355:         }
14356:     }
14357:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14358:     my (%chksum,%revnum);
14359:     if (ref($lines) eq 'ARRAY') {
14360:         chomp(@{$lines});
14361:         my $version = shift(@{$lines});
14362:         if ($version eq $release) {  
14363:             foreach my $line (@{$lines}) {
14364:                 my ($file,$version,$shasum) = split(/,/,$line);
14365:                 if ($file =~ m{^/etc/httpd/conf}) {
14366:                     if ($webconfdir eq '/etc/apache2') {
14367:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14368:                     }
14369:                 }
14370:                 $chksum{$file} = $shasum;
14371:                 $revnum{$file} = $version;
14372:             }
14373:             if (ref($hashref) eq 'HASH') {
14374:                 %{$hashref} = (
14375:                                 sums     => \%chksum,
14376:                                 versions => \%revnum,
14377:                               );
14378:             }
14379:         }
14380:     }
14381:     return;
14382: }
14383: 
14384: sub fetch_dns_checksums {
14385:     my %checksums;
14386:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14387:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14388:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14389:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14390:              \%checksums);
14391:     return \%checksums;
14392: }
14393: 
14394: sub fetch_crl_pemfile {
14395:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14396: }
14397: 
14398: sub save_crl_pem {
14399:     my ($response) = @_;
14400:     my ($msg,$hadchanges);
14401:     if (ref($response)) {
14402:         my $now = time;
14403:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14404:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14405:         if (open(my $fh,'>',"$tmpcrl")) {
14406:             print $fh $response->content;
14407:             close($fh);
14408:             if (-e $lonca) {
14409:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14410:                     my $check = <PIPE>;
14411:                     close(PIPE);
14412:                     chomp($check);
14413:                     if ($check eq 'verify OK') {
14414:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14415:                         my $backup;
14416:                         if (-e $dest) {
14417:                             if (&File::Copy::move($dest,"$dest.bak")) {
14418:                                 $backup = 'ok';
14419:                             }
14420:                         }
14421:                         if (&File::Copy::move($tmpcrl,$dest)) {
14422:                             $msg = 'ok';
14423:                             if ($backup) {
14424:                                 my (%oldnums,%newnums);
14425:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14426:                                     while (<PIPE>) {
14427:                                         $oldnums{(split(/:/))[1]} = 1;
14428:                                     }
14429:                                     close(PIPE);
14430:                                 }
14431:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14432:                                     while(<PIPE>) {
14433:                                         $newnums{(split(/:/))[1]} = 1;
14434:                                     }
14435:                                     close(PIPE);
14436:                                 }
14437:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14438:                                     unless (exists($oldnums{$key})) {
14439:                                         $hadchanges = 1;
14440:                                         last;
14441:                                     }
14442:                                 }
14443:                                 unless ($hadchanges) {
14444:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14445:                                         unless (exists($newnums{$key})) {
14446:                                             $hadchanges = 1;
14447:                                             last;
14448:                                         }
14449:                                     }
14450:                                 }
14451:                             }
14452:                         }
14453:                     } else {
14454:                         unlink($tmpcrl);
14455:                     }
14456:                 } else {
14457:                     unlink($tmpcrl);
14458:                 }
14459:             } else {
14460:                 unlink($tmpcrl);
14461:             }
14462:         }
14463:     }
14464:     return ($msg,$hadchanges);
14465: }
14466: 
14467: # ------------------------------------------------------------ Read domain file
14468: {
14469:     my $loaded;
14470:     my %domain;
14471: 
14472:     sub parse_domain_tab {
14473: 	my ($lines) = @_;
14474: 	foreach my $line (@$lines) {
14475: 	    next if ($line =~ /^(\#|\s*$ )/x);
14476: 
14477: 	    chomp($line);
14478: 	    my ($name,@elements) = split(/:/,$line,9);
14479: 	    my %this_domain;
14480: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14481: 			       'lang_def', 'city', 'longi', 'lati',
14482: 			       'primary') {
14483: 		$this_domain{$field} = shift(@elements);
14484: 	    }
14485: 	    $domain{$name} = \%this_domain;
14486: 	}
14487:     }
14488: 
14489:     sub reset_domain_info {
14490: 	undef($loaded);
14491: 	undef(%domain);
14492:     }
14493: 
14494:     sub load_domain_tab {
14495: 	my ($ignore_cache,$nocache) = @_;
14496: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14497: 	my $fh;
14498: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14499: 	    my @lines = <$fh>;
14500: 	    &parse_domain_tab(\@lines);
14501: 	}
14502: 	close($fh);
14503: 	$loaded = 1;
14504:     }
14505: 
14506:     sub domain {
14507: 	&load_domain_tab() if (!$loaded);
14508: 
14509: 	my ($name,$what) = @_;
14510: 	return if ( !exists($domain{$name}) );
14511: 
14512: 	if (!$what) {
14513: 	    return $domain{$name}{'description'};
14514: 	}
14515: 	return $domain{$name}{$what};
14516:     }
14517: 
14518:     sub domain_info {
14519:         &load_domain_tab() if (!$loaded);
14520:         return %domain;
14521:     }
14522: 
14523: }
14524: 
14525: 
14526: # ------------------------------------------------------------- Read hosts file
14527: {
14528:     my %hostname;
14529:     my %hostdom;
14530:     my %libserv;
14531:     my $loaded;
14532:     my %name_to_host;
14533:     my %internetdom;
14534:     my %LC_dns_serv;
14535: 
14536:     sub parse_hosts_tab {
14537: 	my ($file) = @_;
14538: 	foreach my $configline (@$file) {
14539: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14540:             chomp($configline);
14541: 	    if ($configline =~ /^\^/) {
14542:                 if ($configline =~ /^\^([\w.\-]+)/) {
14543:                     $LC_dns_serv{$1} = 1;
14544:                 }
14545:                 next;
14546:             }
14547: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14548: 	    $name=~s/\s//g;
14549: 	    if ($id && $domain && $role && $name) {
14550:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14551:                     my $curr = $hostname{$id};
14552:                     my $skip;
14553:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14554:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14555:                             $skip = 1;
14556:                         } else {
14557:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14558:                         }
14559:                     }
14560:                     unless ($skip) {
14561:                         push(@{$name_to_host{$name}},$id);
14562:                     }
14563:                 } else {
14564:                     push(@{$name_to_host{$name}},$id);
14565:                 }
14566: 		$hostname{$id}=$name;
14567: 		$hostdom{$id}=$domain;
14568: 		if ($role eq 'library') { $libserv{$id}=$name; }
14569:                 if (defined($protocol)) {
14570:                     if ($protocol eq 'https') {
14571:                         $protocol{$id} = $protocol;
14572:                     } else {
14573:                         $protocol{$id} = 'http'; 
14574:                     }
14575:                 } else {
14576:                     $protocol{$id} = 'http';
14577:                 }
14578:                 if (defined($intdom)) {
14579:                     $internetdom{$id} = $intdom;
14580:                 }
14581: 	    }
14582: 	}
14583:     }
14584:     
14585:     sub reset_hosts_info {
14586: 	&purge_remembered();
14587: 	&reset_domain_info();
14588: 	&reset_hosts_ip_info();
14589:         undef(%internetdom);
14590: 	undef(%name_to_host);
14591: 	undef(%hostname);
14592: 	undef(%hostdom);
14593: 	undef(%libserv);
14594: 	undef($loaded);
14595:     }
14596: 
14597:     sub load_hosts_tab {
14598: 	my ($ignore_cache,$nocache) = @_;
14599: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14600: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14601: 	my @config = <$config>;
14602: 	&parse_hosts_tab(\@config);
14603: 	close($config);
14604: 	$loaded=1;
14605:     }
14606: 
14607:     sub hostname {
14608: 	&load_hosts_tab() if (!$loaded);
14609: 
14610: 	my ($lonid) = @_;
14611: 	return $hostname{$lonid};
14612:     }
14613: 
14614:     sub all_hostnames {
14615: 	&load_hosts_tab() if (!$loaded);
14616: 
14617: 	return %hostname;
14618:     }
14619: 
14620:     sub all_names {
14621:         my ($ignore_cache,$nocache) = @_;
14622: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14623: 
14624: 	return %name_to_host;
14625:     }
14626: 
14627:     sub all_host_domain {
14628:         &load_hosts_tab() if (!$loaded);
14629:         return %hostdom;
14630:     }
14631: 
14632:     sub all_host_intdom {
14633:         &load_hosts_tab() if (!$loaded);
14634:         return %internetdom;
14635:     }
14636: 
14637:     sub is_library {
14638: 	&load_hosts_tab() if (!$loaded);
14639: 
14640: 	return exists($libserv{$_[0]});
14641:     }
14642: 
14643:     sub all_library {
14644: 	&load_hosts_tab() if (!$loaded);
14645: 
14646: 	return %libserv;
14647:     }
14648: 
14649:     sub unique_library {
14650: 	#2x reverse removes all hostnames that appear more than once
14651:         my %unique = reverse &all_library();
14652:         return reverse %unique;
14653:     }
14654: 
14655:     sub get_servers {
14656: 	&load_hosts_tab() if (!$loaded);
14657: 
14658: 	my ($domain,$type) = @_;
14659: 	my %possible_hosts = ($type eq 'library') ? %libserv
14660: 	                                          : %hostname;
14661: 	my %result;
14662: 	if (ref($domain) eq 'ARRAY') {
14663: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14664: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14665: 		    $result{$host} = $hostname;
14666: 		}
14667: 	    }
14668: 	} else {
14669: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14670: 		if ($hostdom{$host} eq $domain) {
14671: 		    $result{$host} = $hostname;
14672: 		}
14673: 	    }
14674: 	}
14675: 	return %result;
14676:     }
14677: 
14678:     sub get_unique_servers {
14679:         my %unique = reverse &get_servers(@_);
14680: 	return reverse %unique;
14681:     }
14682: 
14683:     sub host_domain {
14684: 	&load_hosts_tab() if (!$loaded);
14685: 
14686: 	my ($lonid) = @_;
14687: 	return $hostdom{$lonid};
14688:     }
14689: 
14690:     sub all_domains {
14691: 	&load_hosts_tab() if (!$loaded);
14692: 
14693: 	my %seen;
14694: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14695: 	return @uniq;
14696:     }
14697: 
14698:     sub internet_dom {
14699:         &load_hosts_tab() if (!$loaded);
14700: 
14701:         my ($lonid) = @_;
14702:         return $internetdom{$lonid};
14703:     }
14704: 
14705:     sub is_LC_dns {
14706:         &load_hosts_tab() if (!$loaded);
14707: 
14708:         my ($hostname) = @_;
14709:         return exists($LC_dns_serv{$hostname});
14710:     }
14711: 
14712: }
14713: 
14714: { 
14715:     my %iphost;
14716:     my %name_to_ip;
14717:     my %lonid_to_ip;
14718: 
14719:     sub get_hosts_from_ip {
14720: 	my ($ip) = @_;
14721: 	my %iphosts = &get_iphost();
14722: 	if (ref($iphosts{$ip})) {
14723: 	    return @{$iphosts{$ip}};
14724: 	}
14725: 	return;
14726:     }
14727:     
14728:     sub reset_hosts_ip_info {
14729: 	undef(%iphost);
14730: 	undef(%name_to_ip);
14731: 	undef(%lonid_to_ip);
14732:     }
14733: 
14734:     sub get_host_ip {
14735: 	my ($lonid) = @_;
14736: 	if (exists($lonid_to_ip{$lonid})) {
14737: 	    return $lonid_to_ip{$lonid};
14738: 	}
14739: 	my $name=&hostname($lonid);
14740:    	my $ip = gethostbyname($name);
14741: 	return if (!$ip || length($ip) ne 4);
14742: 	$ip=inet_ntoa($ip);
14743: 	$name_to_ip{$name}   = $ip;
14744: 	$lonid_to_ip{$lonid} = $ip;
14745: 	return $ip;
14746:     }
14747:     
14748:     sub get_iphost {
14749: 	my ($ignore_cache,$nocache) = @_;
14750: 
14751: 	if (!$ignore_cache) {
14752: 	    if (%iphost) {
14753: 		return %iphost;
14754: 	    }
14755: 	    my ($ip_info,$cached)=
14756: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14757: 	    if ($cached) {
14758: 		%iphost      = %{$ip_info->[0]};
14759: 		%name_to_ip  = %{$ip_info->[1]};
14760: 		%lonid_to_ip = %{$ip_info->[2]};
14761: 		return %iphost;
14762: 	    }
14763: 	}
14764: 
14765: 	# get yesterday's info for fallback
14766: 	my %old_name_to_ip;
14767: 	my ($ip_info,$cached)=
14768: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14769: 	if ($cached) {
14770: 	    %old_name_to_ip = %{$ip_info->[1]};
14771: 	}
14772: 
14773: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14774: 	foreach my $name (keys(%name_to_host)) {
14775: 	    my $ip;
14776: 	    if (!exists($name_to_ip{$name})) {
14777: 		$ip = gethostbyname($name);
14778: 		if (!$ip || length($ip) ne 4) {
14779: 		    if (defined($old_name_to_ip{$name})) {
14780: 			$ip = $old_name_to_ip{$name};
14781: 			&logthis("Can't find $name defaulting to old $ip");
14782: 		    } else {
14783: 			&logthis("Name $name no IP found");
14784: 			next;
14785: 		    }
14786: 		} else {
14787: 		    $ip=inet_ntoa($ip);
14788: 		}
14789: 		$name_to_ip{$name} = $ip;
14790: 	    } else {
14791: 		$ip = $name_to_ip{$name};
14792: 	    }
14793: 	    foreach my $id (@{ $name_to_host{$name} }) {
14794: 		$lonid_to_ip{$id} = $ip;
14795: 	    }
14796: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14797: 	}
14798:         unless ($nocache) {
14799: 	    &do_cache_new('iphost','iphost',
14800: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14801: 		          48*60*60);
14802:         }
14803: 
14804: 	return %iphost;
14805:     }
14806: 
14807:     #
14808:     #  Given a DNS returns the loncapa host name for that DNS 
14809:     # 
14810:     sub host_from_dns {
14811:         my ($dns) = @_;
14812:         my @hosts;
14813:         my $ip;
14814: 
14815:         if (exists($name_to_ip{$dns})) {
14816:             $ip = $name_to_ip{$dns};
14817:         }
14818:         if (!$ip) {
14819:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14820:             if (length($ip) == 4) { 
14821: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14822:             }
14823:         }
14824:         if ($ip) {
14825: 	    @hosts = get_hosts_from_ip($ip);
14826: 	    return $hosts[0];
14827:         }
14828:         return undef;
14829:     }
14830: 
14831:     sub get_internet_names {
14832:         my ($lonid) = @_;
14833:         return if ($lonid eq '');
14834:         my ($idnref,$cached)=
14835:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14836:         if ($cached) {
14837:             return $idnref;
14838:         }
14839:         my $ip = &get_host_ip($lonid);
14840:         my @hosts = &get_hosts_from_ip($ip);
14841:         my %iphost = &get_iphost();
14842:         my (@idns,%seen);
14843:         foreach my $id (@hosts) {
14844:             my $dom = &host_domain($id);
14845:             my $prim_id = &domain($dom,'primary');
14846:             my $prim_ip = &get_host_ip($prim_id);
14847:             next if ($seen{$prim_ip});
14848:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14849:                 foreach my $id (@{$iphost{$prim_ip}}) {
14850:                     my $intdom = &internet_dom($id);
14851:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14852:                         push(@idns,$intdom);
14853:                     }
14854:                 }
14855:             }
14856:             $seen{$prim_ip} = 1;
14857:         }
14858:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14859:     }
14860: 
14861: }
14862: 
14863: sub all_loncaparevs {
14864:     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);
14865: }
14866: 
14867: # ---------------------------------------------------------- Read loncaparev table
14868: {
14869:     sub load_loncaparevs { 
14870:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14871:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14872:                 while (my $configline=<$config>) {
14873:                     chomp($configline);
14874:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14875:                     $loncaparevs{$hostid}=$loncaparev;
14876:                 }
14877:                 close($config);
14878:             }
14879:         }
14880:     }
14881: }
14882: 
14883: # ---------------------------------------------------------- Read serverhostID table
14884: {
14885:     sub load_serverhomeIDs {
14886:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14887:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14888:                 while (my $configline=<$config>) {
14889:                     chomp($configline);
14890:                     my ($name,$id)=split(/:/,$configline);
14891:                     $serverhomeIDs{$name}=$id;
14892:                 }
14893:                 close($config);
14894:             }
14895:         }
14896:     }
14897: }
14898: 
14899: 
14900: BEGIN {
14901: 
14902: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14903:     unless ($readit) {
14904: {
14905:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14906:     %perlvar = (%perlvar,%{$configvars});
14907: }
14908: 
14909: 
14910: # ------------------------------------------------------ Read spare server file
14911: {
14912:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14913: 
14914:     while (my $configline=<$config>) {
14915:        chomp($configline);
14916:        if ($configline) {
14917: 	   my ($host,$type) = split(':',$configline,2);
14918: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14919: 	   push(@{ $spareid{$type} }, $host);
14920:        }
14921:     }
14922:     close($config);
14923: }
14924: # ------------------------------------------------------------ Read permissions
14925: {
14926:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14927: 
14928:     while (my $configline=<$config>) {
14929: 	chomp($configline);
14930: 	if ($configline) {
14931: 	    my ($role,$perm)=split(/ /,$configline);
14932: 	    if ($perm ne '') { $pr{$role}=$perm; }
14933: 	}
14934:     }
14935:     close($config);
14936: }
14937: 
14938: # -------------------------------------------- Read plain texts for permissions
14939: {
14940:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14941: 
14942:     while (my $configline=<$config>) {
14943: 	chomp($configline);
14944: 	if ($configline) {
14945: 	    my ($short,@plain)=split(/:/,$configline);
14946:             %{$prp{$short}} = ();
14947: 	    if (@plain > 0) {
14948:                 $prp{$short}{'std'} = $plain[0];
14949:                 for (my $i=1; $i<@plain; $i++) {
14950:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14951:                 }
14952:             }
14953: 	}
14954:     }
14955:     close($config);
14956: }
14957: 
14958: # ---------------------------------------------------------- Read package table
14959: {
14960:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14961: 
14962:     while (my $configline=<$config>) {
14963: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14964: 	chomp($configline);
14965: 	my ($short,$plain)=split(/:/,$configline);
14966: 	my ($pack,$name)=split(/\&/,$short);
14967: 	if ($plain ne '') {
14968: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14969: 	    $packagetab{$short}=$plain; 
14970: 	}
14971:     }
14972:     close($config);
14973: }
14974: 
14975: # ---------------------------------------------------------- Read loncaparev table
14976: 
14977: &load_loncaparevs();
14978: 
14979: # ---------------------------------------------------------- Read serverhostID table
14980: 
14981: &load_serverhomeIDs();
14982: 
14983: # ---------------------------------------------------------- Read releaseslist XML
14984: {
14985:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14986:     if (-e $file) {
14987:         my $parser = HTML::LCParser->new($file);
14988:         while (my $token = $parser->get_token()) {
14989:             if ($token->[0] eq 'S') {
14990:                 my $item = $token->[1];
14991:                 my $name = $token->[2]{'name'};
14992:                 my $value = $token->[2]{'value'};
14993:                 my $valuematch = $token->[2]{'valuematch'};
14994:                 my $namematch = $token->[2]{'namematch'};
14995:                 if ($item eq 'parameter') {
14996:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14997:                         my $release = $parser->get_text();
14998:                         $release =~ s/(^\s*|\s*$ )//gx;
14999:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15000:                     }
15001:                 } elsif ($item ne '' && $name ne '') {
15002:                     my $release = $parser->get_text();
15003:                     $release =~ s/(^\s*|\s*$ )//gx;
15004:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
15005:                 }
15006:             }
15007:         }
15008:     }
15009: }
15010: 
15011: # ---------------------------------------------------------- Read managers table
15012: {
15013:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15014:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15015:             while (my $configline=<$config>) {
15016:                 chomp($configline);
15017:                 next if ($configline =~ /^\#/);
15018:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15019:                     $managerstab{$configline} = 1;
15020:                 }
15021:             }
15022:             close($config);
15023:         }
15024:     }
15025: }
15026: 
15027: # ------------- set up temporary directory
15028: {
15029:     $tmpdir = LONCAPA::tempdir();
15030: 
15031: }
15032: 
15033: # ------------- set default texengine (domain default overrides this)
15034: {
15035:     $deftex = LONCAPA::texengine();
15036: }
15037: 
15038: # ------------- set default minimum length for passwords for internal auth users
15039: {
15040:     $passwdmin = LONCAPA::passwd_min();
15041: }
15042: 
15043: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
15044: 				'compress_threshold'=> 20_000,
15045:  			        });
15046: 
15047: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15048: $dumpcount=0;
15049: $locknum=0;
15050: 
15051: &logtouch();
15052: &logthis('<font color="yellow">INFO: Read configuration</font>');
15053: $readit=1;
15054:     {
15055: 	use integer;
15056: 	my $test=(2**32)+1;
15057: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15058: 	&logthis(" Detected 64bit platform ($_64bit)");
15059:     }
15060: }
15061: }
15062: 
15063: 1;
15064: __END__
15065: 
15066: =pod
15067: 
15068: =head1 NAME
15069: 
15070: Apache::lonnet - Subroutines to ask questions about things in the network.
15071: 
15072: =head1 SYNOPSIS
15073: 
15074: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15075: 
15076:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15077: 
15078: Common parameters:
15079: 
15080: =over 4
15081: 
15082: =item *
15083: 
15084: $uname : an internal username (if $cname expecting a course Id specifically)
15085: 
15086: =item *
15087: 
15088: $udom : a domain (if $cdom expecting a course's domain specifically)
15089: 
15090: =item *
15091: 
15092: $symb : a resource instance identifier
15093: 
15094: =item *
15095: 
15096: $namespace : the name of a .db file that contains the data needed or
15097: being set.
15098: 
15099: =back
15100: 
15101: =head1 OVERVIEW
15102: 
15103: lonnet provides subroutines which interact with the
15104: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15105: about classes, users, and resources.
15106: 
15107: For many of these objects you can also use this to store data about
15108: them or modify them in various ways.
15109: 
15110: =head2 Symbs
15111: 
15112: To identify a specific instance of a resource, LON-CAPA uses symbols
15113: or "symbs"X<symb>. These identifiers are built from the URL of the
15114: map, the resource number of the resource in the map, and the URL of
15115: the resource itself. The latter is somewhat redundant, but might help
15116: if maps change.
15117: 
15118: An example is
15119: 
15120:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15121: 
15122: The respective map entry is
15123: 
15124:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15125:   title="Problem 2">
15126:  </resource>
15127: 
15128: Symbs are used by the random number generator, as well as to store and
15129: restore data specific to a certain instance of for example a problem.
15130: 
15131: =head2 Storing And Retrieving Data
15132: 
15133: X<store()>X<cstore()>X<restore()>Three of the most important functions
15134: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15135: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15136: is is the non-critical message twin of cstore. These functions are for
15137: handlers to store a perl hash to a user's permanent data space in an
15138: easy manner, and to retrieve it again on another call. It is expected
15139: that a handler would use this once at the beginning to retrieve data,
15140: and then again once at the end to send only the new data back.
15141: 
15142: The data is stored in the user's data directory on the user's
15143: homeserver under the ID of the course.
15144: 
15145: The hash that is returned by restore will have all of the previous
15146: value for all of the elements of the hash.
15147: 
15148: Example:
15149: 
15150:  #creating a hash
15151:  my %hash;
15152:  $hash{'foo'}='bar';
15153: 
15154:  #storing it
15155:  &Apache::lonnet::cstore(\%hash);
15156: 
15157:  #changing a value
15158:  $hash{'foo'}='notbar';
15159: 
15160:  #adding a new value
15161:  $hash{'bar'}='foo';
15162:  &Apache::lonnet::cstore(\%hash);
15163: 
15164:  #retrieving the hash
15165:  my %history=&Apache::lonnet::restore();
15166: 
15167:  #print the hash
15168:  foreach my $key (sort(keys(%history))) {
15169:    print("\%history{$key} = $history{$key}");
15170:  }
15171: 
15172: Will print out:
15173: 
15174:  %history{1:foo} = bar
15175:  %history{1:keys} = foo:timestamp
15176:  %history{1:timestamp} = 990455579
15177:  %history{2:bar} = foo
15178:  %history{2:foo} = notbar
15179:  %history{2:keys} = foo:bar:timestamp
15180:  %history{2:timestamp} = 990455580
15181:  %history{bar} = foo
15182:  %history{foo} = notbar
15183:  %history{timestamp} = 990455580
15184:  %history{version} = 2
15185: 
15186: Note that the special hash entries C<keys>, C<version> and
15187: C<timestamp> were added to the hash. C<version> will be equal to the
15188: total number of versions of the data that have been stored. The
15189: C<timestamp> attribute will be the UNIX time the hash was
15190: stored. C<keys> is available in every historical section to list which
15191: keys were added or changed at a specific historical revision of a
15192: hash.
15193: 
15194: B<Warning>: do not store the hash that restore returns directly. This
15195: will cause a mess since it will restore the historical keys as if the
15196: were new keys. I.E. 1:foo will become 1:1:foo etc.
15197: 
15198: Calling convention:
15199: 
15200:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15201:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15202: 
15203: For more detailed information, see lonnet specific documentation.
15204: 
15205: =head1 RETURN MESSAGES
15206: 
15207: =over 4
15208: 
15209: =item * B<con_lost>: unable to contact remote host
15210: 
15211: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15212: when the connection is brought back up
15213: 
15214: =item * B<con_failed>: unable to contact remote host and unable to save message
15215: for later delivery
15216: 
15217: =item * B<error:>: an error a occurred, a description of the error follows the :
15218: 
15219: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15220: that was requested
15221: 
15222: =back
15223: 
15224: =head1 PUBLIC SUBROUTINES
15225: 
15226: =head2 Session Environment Functions
15227: 
15228: =over 4
15229: 
15230: =item * 
15231: X<appenv()>
15232: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15233: the user envirnoment file, and will be restored for each access this
15234: user makes during this session, also modifies the %env for the current
15235: process. Optional rolesarrayref - if defined contains a reference to an array
15236: of roles which are exempt from the restriction on modifying user.role entries 
15237: in the user's environment.db and in %env.    
15238: 
15239: =item *
15240: X<delenv()>
15241: B<delenv($delthis,$regexp)>: removes all items from the session
15242: environment file that begin with $delthis. If the 
15243: optional second arg - $regexp - is true, $delthis is treated as a 
15244: regular expression, otherwise \Q$delthis\E is used. 
15245: The values are also deleted from the current processes %env.
15246: 
15247: =item * get_env_multiple($name) 
15248: 
15249: gets $name from the %env hash, it seemlessly handles the cases where multiple
15250: values may be defined and end up as an array ref.
15251: 
15252: returns an array of values
15253: 
15254: =back
15255: 
15256: =head2 User Information
15257: 
15258: =over 4
15259: 
15260: =item *
15261: X<queryauthenticate()>
15262: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15263: authentication scheme
15264: 
15265: =item *
15266: X<authenticate()>
15267: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15268: authenticate user from domain's lib servers (first use the current
15269: one). C<$upass> should be the users password.
15270: $checkdefauth is optional (value is 1 if a check should be made to
15271:    authenticate user using default authentication method, and allow
15272:    account creation if username does not have account in the domain).
15273: $clientcancheckhost is optional (value is 1 if checking whether the
15274:    server can host will occur on the client side in lonauth.pm).   
15275: 
15276: =item *
15277: X<homeserver()>
15278: B<homeserver($uname,$udom)>: find the server which has
15279: the user's directory and files (there must be only one), this caches
15280: the answer, and also caches if there is a borken connection.
15281: 
15282: =item *
15283: X<idget()>
15284: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15285: a list of student/employee IDs or clicker IDs
15286: (student/employee IDs are a unique resource in a domain, there must be 
15287: only 1 ID per username, and only 1 username per ID in a specific domain).
15288: clickerIDs are not necessarily unique, as students might share clickers.
15289: (returns hash: id=>name,id=>name)
15290: 
15291: =item *
15292: X<idrget()>
15293: B<idrget($udom,@unames)>: find the IDs behind a list of
15294: usernames (returns hash: name=>id,name=>id)
15295: 
15296: =item *
15297: X<idput()>
15298: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15299: names and associated student/employee IDs or clicker IDs.
15300: 
15301: =item *
15302: X<iddel()>
15303: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15304: student/employee ID or clicker ID username look-ups from domain.
15305: The homeserver ($uhome) and namespace ($namespace) are optional.
15306: If no $uhome is provided, it will be determined usig &homeserver()
15307: for each user.  If no $namespace is provided, the default is ids.
15308: 
15309: =item *
15310: X<updateclickers()>
15311: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15312: clicker ID-to-username look-ups in clickers.db on library server.
15313: Permitted actions are add or del (i.e., add or delete). The 
15314: clickers.db contains clickerID as keys (escaped), and each corresponding
15315: value is an escaped comma-separated list of usernames (for whom the
15316: library server is the homeserver), who registered that particular ID.
15317: If $critical is true, the update will be sent via &critical, otherwise
15318: &reply() will be used.
15319: 
15320: =item *
15321: X<rolesinit()>
15322: B<rolesinit($udom,$username)>: get user privileges.
15323: returns user role, first access and timer interval hashes
15324: 
15325: =item *
15326: X<privileged()>
15327: B<privileged($username,$domain)>: returns a true if user has a
15328: privileged and active role (i.e. su or dc), false otherwise.
15329: 
15330: =item *
15331: X<getsection()>
15332: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15333: course $cname, return section name/number or '' for "not in course"
15334: and '-1' for "no section"
15335: 
15336: =item *
15337: X<userenvironment()>
15338: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15339: passed in @what from the requested user's environment, returns a hash
15340: 
15341: =item * 
15342: X<userlog_query()>
15343: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15344: activity.log file. %filters defines filters applied when parsing the
15345: log file. These can be start or end timestamps, or the type of action
15346: - log to look for Login or Logout events, check for Checkin or
15347: Checkout, role for role selection. The response is in the form
15348: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15349: escaped strings of the action recorded in the activity.log file.
15350: 
15351: =back
15352: 
15353: =head2 User Roles
15354: 
15355: =over 4
15356: 
15357: =item *
15358: 
15359: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15360: returns codes for allowed actions.
15361: 
15362: The first argument is required, all others are optional.
15363: 
15364: $priv is the privilege being checked.
15365: $uri contains additional information about what is being checked for access (e.g.,
15366: URL, course ID etc.). 
15367: $symb is the unique resource instance identifier in a course; if needed,
15368: but not provided, it will be retrieved via a call to &symbread(). 
15369: $role is the role for which a priv is being checked (only used if priv is evb). 
15370: $clientip is the user's IP address (only used when checking for access to portfolio 
15371: files).
15372: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15373: prevents recursive calls to &allowed.
15374: 
15375:  F: full access
15376:  U,I,K: authentication modes (cxx only)
15377:  '': forbidden
15378:  1: user needs to choose course
15379:  2: browse allowed
15380:  A: passphrase authentication needed
15381:  B: access temporarily blocked because of a blocking event in a course.
15382:  D: access blocked because access is required via session initiated via deep-link 
15383: 
15384: =item *
15385: 
15386: constructaccess($url,$setpriv) : check for access to construction space URL
15387: 
15388: See if the owner domain and name in the URL match those in the
15389: expected environment.  If so, return three element list
15390: ($ownername,$ownerdomain,$ownerhome).
15391: 
15392: Otherwise return the null string.
15393: 
15394: If second argument 'setpriv' is true, it assigns the privileges,
15395: and returns the same three element list, unless the owner has
15396: blocked "ad hoc" Domain Coordinator access to the Author Space,
15397: in which case the null string is returned.
15398: 
15399: =item *
15400: 
15401: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15402: define a custom role rolename set privileges in format of lonTabs/roles.tab
15403: for system, domain, and course level. $uname and $udom are optional (current
15404: user's username and domain will be used when either of $uname or $udom are absent.
15405: 
15406: =item *
15407: 
15408: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15409: (rolesplain.tab); plain text explanation of a user role term.
15410: $type is Course (default) or Community.
15411: If $forcedefault evaluates to true, text returned will be default 
15412: text for $type. Otherwise, if this is a course, the text returned 
15413: will be a custom name for the role (if defined in the course's 
15414: environment).  If no custom name is defined the default is returned.
15415:    
15416: =item *
15417: 
15418: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15419: All arguments are optional. Returns a hash of a roles, either for
15420: co-author/assistant author roles for a user's Construction Space
15421: (default), or if $context is 'userroles', roles for the user himself,
15422: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15423: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15424: For each key, value is set to colon-separated start and end times for
15425: the role.  If no username and domain are specified, will default to
15426: current user/domain. Types, roles, and roledoms are references to arrays
15427: of role statuses (active, future or previous), roles 
15428: (e.g., cc,in, st etc.) and domains of the roles which can be used
15429: to restrict the list of roles reported. If no array ref is 
15430: provided for types, will default to return only active roles.
15431: 
15432: =item *
15433: 
15434: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15435: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15436: 
15437: Additional optional arguments are: $type (if role checking is to be restricted 
15438: to certain user status types -- previous (expired roles), active (currently
15439: available roles) or future (roles available in the future), and
15440: $hideprivileged -- if true will not report course roles for users who
15441: have active Domain Coordinator role in course's domain or in additional
15442: domains (specified in 'Domains to check for privileged users' in course
15443: environment -- set via:  Course Settings -> Classlists and staff listing).
15444: 
15445: =item *
15446: 
15447: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15448: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15449: $possdomains and $possroles are optional array refs -- to domains to check and
15450: roles to check.  If $possdomains is not specified, a dump will be done of the
15451: users' roles.db to check for a dc or su role in any domain. This can be
15452: time consuming if &privileged is called repeatedly (e.g., when displaying a
15453: classlist), so in such cases, supplying a $possdomains array is preferred, as
15454: this then allows &privileged_by_domain() to be used, which caches the identity
15455: of privileged users, eliminating the need for repeated calls to &dump().
15456: 
15457: =item *
15458: 
15459: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15460: where the outer hash keys are domains specified in the $possdomains array ref,
15461: next inner hash keys are privileged roles specified in the $roles array ref,
15462: and the innermost hash contains key = value pairs for username:domain = end:start
15463: for active or future "privileged" users with that role in that domain. To avoid
15464: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15465: innerhash are cached using priv_$role and $dom as the identifiers.
15466: 
15467: =back
15468: 
15469: =head2 User Modification
15470: 
15471: =over 4
15472: 
15473: =item *
15474: 
15475: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15476: user for the level given by URL.  Optional start and end dates (leave empty
15477: string or zero for "no date")
15478: 
15479: =item *
15480: 
15481: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15482: change a users, password, possible return values are: ok,
15483: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15484: refused
15485: 
15486: =item *
15487: 
15488: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15489: 
15490: =item *
15491: 
15492: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15493:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15494: 
15495: will update user information (firstname,middlename,lastname,generation,
15496: permanentemail), and if forceid is true, student/employee ID also.
15497: A user's institutional affiliation(s) can also be updated.
15498: User information fields will not be overwritten with empty entries 
15499: unless the field is included in the $candelete array reference.
15500: This array is included when a single user is modified via "Manage Users",
15501: or when Autoupdate.pl is run by cron in a domain.
15502: 
15503: =item *
15504: 
15505: modifystudent
15506: 
15507: modify a student's enrollment and identification information.
15508: The course id is resolved based on the current user's environment.  
15509: This means the invoking user must be a course coordinator or otherwise
15510: associated with a course.
15511: 
15512: This call is essentially a wrapper for lonnet::modifyuser and
15513: lonnet::modify_student_enrollment
15514: 
15515: Inputs: 
15516: 
15517: =over 4
15518: 
15519: =item B<$udom> Student's loncapa domain
15520: 
15521: =item B<$uname> Student's loncapa login name
15522: 
15523: =item B<$uid> Student/Employee ID
15524: 
15525: =item B<$umode> Student's authentication mode
15526: 
15527: =item B<$upass> Student's password
15528: 
15529: =item B<$first> Student's first name
15530: 
15531: =item B<$middle> Student's middle name
15532: 
15533: =item B<$last> Student's last name
15534: 
15535: =item B<$gene> Student's generation
15536: 
15537: =item B<$usec> Student's section in course
15538: 
15539: =item B<$end> Unix time of the roles expiration
15540: 
15541: =item B<$start> Unix time of the roles start date
15542: 
15543: =item B<$forceid> If defined, allow $uid to be changed
15544: 
15545: =item B<$desiredhome> server to use as home server for student
15546: 
15547: =item B<$email> Student's permanent e-mail address
15548: 
15549: =item B<$type> Type of enrollment (auto or manual)
15550: 
15551: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15552: 
15553: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15554: 
15555: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15556: 
15557: =item B<$context> role change context (shown in User Management Logs display in a course)
15558: 
15559: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15560: 
15561: =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.
15562: 
15563: =back
15564: 
15565: =item *
15566: 
15567: modify_student_enrollment
15568: 
15569: Change a student's enrollment status in a class.  The environment variable
15570: 'role.request.course' must be defined for this function to proceed.
15571: 
15572: Inputs:
15573: 
15574: =over 4
15575: 
15576: =item $udom, student's domain
15577: 
15578: =item $uname, student's name
15579: 
15580: =item $uid, student's user id
15581: 
15582: =item $first, student's first name
15583: 
15584: =item $middle
15585: 
15586: =item $last
15587: 
15588: =item $gene
15589: 
15590: =item $usec
15591: 
15592: =item $end
15593: 
15594: =item $start
15595: 
15596: =item $type
15597: 
15598: =item $locktype
15599: 
15600: =item $cid
15601: 
15602: =item $selfenroll
15603: 
15604: =item $context
15605: 
15606: =item $credits, number of credits student will earn from this class
15607: 
15608: =item $instsec, institutional course section code for student
15609: 
15610: =back
15611: 
15612: 
15613: =item *
15614: 
15615: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15616: custom role; give a custom role to a user for the level given by URL.  Specify
15617: name and domain of role author, and role name
15618: 
15619: =item *
15620: 
15621: revokerole($udom,$uname,$url,$role) : revoke a role for url
15622: 
15623: =item *
15624: 
15625: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15626: 
15627: =back
15628: 
15629: =head2 Course Infomation
15630: 
15631: =over 4
15632: 
15633: =item *
15634: 
15635: coursedescription($courseid,$options) : returns a hash of information about the
15636: specified course id, including all environment settings for the
15637: course, the description of the course will be in the hash under the
15638: key 'description'
15639: 
15640: $options is an optional parameter that if supplied is a hash reference that controls
15641: what how this function works.  It has the following key/values:
15642: 
15643: =over 4
15644: 
15645: =item freshen_cache
15646: 
15647: If defined, and the environment cache for the course is valid, it is 
15648: returned in the returned hash.
15649: 
15650: =item one_time
15651: 
15652: If defined, the last cache time is set to _now_
15653: 
15654: =item user
15655: 
15656: If defined, the supplied username is used instead of the current user.
15657: 
15658: 
15659: =back
15660: 
15661: =item *
15662: 
15663: resdata($name,$domain,$type,@which) : request for current parameter
15664: setting for a specific $type, where $type is either 'course' or 'user',
15665: @what should be a list of parameters to ask about. This routine caches
15666: answers for 10 minutes.
15667: 
15668: =item *
15669: 
15670: get_courseresdata($courseid, $domain) : dump the entire course resource
15671: data base, returning a hash that is keyed by the resource name and has
15672: values that are the resource value.  I believe that the timestamps and
15673: versions are also returned.
15674: 
15675: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15676: supplemental content area. This routine caches the number of files for 
15677: 10 minutes.
15678: 
15679: =back
15680: 
15681: =head2 Course Modification
15682: 
15683: =over 4
15684: 
15685: =item *
15686: 
15687: writecoursepref($courseid,%prefs) : write preferences (environment
15688: database) for a course
15689: 
15690: =item *
15691: 
15692: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15693: 
15694: =item *
15695: 
15696: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15697: 
15698: =item *
15699: 
15700: is_course($courseid), is_course($cdom, $cnum)
15701: 
15702: Accepts either a combined $courseid (in the form of domain_courseid) or the
15703: two component version $cdom, $cnum. It checks if the specified course exists.
15704: 
15705: Returns:
15706:     undef if the course doesn't exist, otherwise
15707:     in scalar context the combined courseid.
15708:     in list context the two components of the course identifier, domain and 
15709:     courseid.    
15710: 
15711: =back
15712: 
15713: =head2 Bubblesheet Configuration
15714: 
15715: =over 4
15716: 
15717: =item *
15718: 
15719: get_scantron_config($which)
15720: 
15721: $which - the name of the configuration to parse from the file.
15722: 
15723: Parses and returns the bubblesheet configuration line selected as a
15724: hash of configuration file fields.
15725: 
15726: 
15727: Returns:
15728:     If the named configuration is not in the file, an empty
15729:     hash is returned.
15730: 
15731:     a hash with the fields
15732:       name         - internal name for the this configuration setup
15733:       description  - text to display to operator that describes this config
15734:       CODElocation - if 0 or the string 'none'
15735:                           - no CODE exists for this config
15736:                      if -1 || the string 'letter'
15737:                           - a CODE exists for this config and is
15738:                             a string of letters
15739:                      Unsupported value (but planned for future support)
15740:                           if a positive integer
15741:                                - The CODE exists as the first n items from
15742:                                  the question section of the form
15743:                           if the string 'number'
15744:                                - The CODE exists for this config and is
15745:                                  a string of numbers
15746:       CODEstart   - (only matter if a CODE exists) column in the line where
15747:                      the CODE starts
15748:       CODElength  - length of the CODE
15749:       IDstart     - column where the student/employee ID starts
15750:       IDlength    - length of the student/employee ID info
15751:       Qstart      - column where the information from the bubbled
15752:                     'questions' start
15753:       Qlength     - number of columns comprising a single bubble line from
15754:                     the sheet. (usually either 1 or 10)
15755:       Qon         - either a single character representing the character used
15756:                     to signal a bubble was chosen in the positional setup, or
15757:                     the string 'letter' if the letter of the chosen bubble is
15758:                     in the final, or 'number' if a number representing the
15759:                     chosen bubble is in the file (1->A 0->J)
15760:       Qoff        - the character used to represent that a bubble was
15761:                     left blank
15762:       PaperID     - if the scanning process generates a unique number for each
15763:                     sheet scanned the column that this ID number starts in
15764:       PaperIDlength - number of columns that comprise the unique ID number
15765:                       for the sheet of paper
15766:       FirstName   - column that the first name starts in
15767:       FirstNameLength - number of columns that the first name spans
15768:       LastName    - column that the last name starts in
15769:       LastNameLength - number of columns that the last name spans
15770:       BubblesPerRow - number of bubbles available in each row used to
15771:                       bubble an answer. (If not specified, 10 assumed).
15772: 
15773: 
15774: =item *
15775: 
15776: get_scantronformat_file($cdom)
15777: 
15778: $cdom - the course's domain (optional); if not supplied, uses
15779: domain for current $env{'request.course.id'}.
15780: 
15781: Returns an array containing lines from the scantron format file for
15782: the domain of the course.
15783: 
15784: If a url for a custom.tab file is listed in domain's configuration.db,
15785: lines are from this file.
15786: 
15787: Otherwise, if a default.tab has been published in RES space by the
15788: domainconfig user, lines are from this file.
15789: 
15790: Otherwise, fall back to getting lines from the legacy file on the
15791: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15792: 
15793: =back
15794: 
15795: =head2 Resource Subroutines
15796: 
15797: =over 4
15798: 
15799: =item *
15800: 
15801: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15802: 
15803: =item *
15804: 
15805: repcopy($filename) : subscribes to the requested file, and attempts to
15806: replicate from the owning library server, Might return
15807: 'unavailable', 'not_found', 'forbidden', 'ok', or
15808: 'bad_request', also attempts to grab the metadata for the
15809: resource. Expects the local filesystem pathname
15810: (/home/httpd/html/res/....)
15811: 
15812: =back
15813: 
15814: =head2 Resource Information
15815: 
15816: =over 4
15817: 
15818: =item *
15819: 
15820: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15821: and returns the value of a variety of different possible values,
15822: $varname should be a request string, and the other parameters can be
15823: used to specify who and what one is asking about. Ordinarily, $cid 
15824: does not need to be specified, as it is retrived from 
15825: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15826: within lonuserstate::loadmap() when initializing a course, before
15827: $env{'request.course.id'} has been set, so it needs to be provided
15828: in that one case.
15829: 
15830: Possible values for $varname are environment.lastname (or other item
15831: from the envirnment hash), user.name (or someother aspect about the
15832: user), resource.0.maxtries (or some other part and parameter of a
15833: resource)
15834: 
15835: =item *
15836: 
15837: directcondval($number) : get current value of a condition; reads from a state
15838: string
15839: 
15840: =item *
15841: 
15842: condval($condidx) : value of condition index based on state
15843: 
15844: =item *
15845: 
15846: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15847: resource's metadata, $what should be either a specific key, or either
15848: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15849: packages that this resource currently uses, the last 3 arguments are 
15850: only used internally for recursive metadata.
15851: 
15852: the toolsymb is only used where the uri is for an external tool (for which
15853: the uri as well as the symb are guaranteed to be unique).
15854: 
15855: this function automatically caches all requests except any made recursively
15856: to retrieve a list of metadata keys for an imported library file ($liburi is 
15857: defined).
15858: 
15859: =item *
15860: 
15861: metadata_query($query,$custom,$customshow) : make a metadata query against the
15862: network of library servers; returns file handle of where SQL and regex results
15863: will be stored for query
15864: 
15865: =item *
15866: 
15867: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15868: return symbolic list entry (all arguments optional). 
15869: 
15870: Args: filename is the filename (including path) for the file for which a symb 
15871: is required; donotrecurse, if true will prevent calls to allowed() being made 
15872: to check access status if more than one resource was found in the bighash 
15873: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15874: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15875: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15876: cause possible symbs to be checked to determine if they are subject to content
15877: blocking, if so they will not be included as possible symbs; possibles is a
15878: ref to a hash, which, as a side effect, will be populated with all possible 
15879: symbs (content blocking not tested).
15880:  
15881: returns the data handle
15882: 
15883: =item *
15884: 
15885: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15886: and is a possible symb for the URL in $thisfn, and if is an encrypted
15887: resource that the user accessed using /enc/ returns a 1 on success, 0
15888: on failure, user must be in a course, as it assumes the existence of
15889: the course initial hash, and uses $env('request.course.id'}.  The third
15890: arg is an optional reference to a scalar.  If this arg is passed in the 
15891: call to symbverify, it will be set to 1 if the symb has been set to be 
15892: encrypted; otherwise it will be null.  
15893: 
15894: =item *
15895: 
15896: symbclean($symb) : removes versions numbers from a symb, returns the
15897: cleaned symb
15898: 
15899: =item *
15900: 
15901: is_on_map($uri) : checks if the $uri is somewhere on the current
15902: course map, user must be in a course for it to work.
15903: 
15904: =item *
15905: 
15906: numval($salt) : return random seed value (addend for rndseed)
15907: 
15908: =item *
15909: 
15910: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15911: a random seed, all arguments are optional, if they aren't sent it uses the
15912: environment to derive them. Note: if symb isn't sent and it can't get one
15913: from &symbread it will use the current time as its return value
15914: 
15915: =item *
15916: 
15917: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15918: unfakeable, receipt
15919: 
15920: =item *
15921: 
15922: receipt() : API to ireceipt working off of env values; given out to users
15923: 
15924: =item *
15925: 
15926: countacc($url) : count the number of accesses to a given URL
15927: 
15928: =item *
15929: 
15930: 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
15931: 
15932: =item *
15933: 
15934: 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)
15935: 
15936: =item *
15937: 
15938: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15939: 
15940: =item *
15941: 
15942: devalidate($symb) : devalidate temporary spreadsheet calculations,
15943: forcing spreadsheet to reevaluate the resource scores next time.
15944: 
15945: =item * 
15946: 
15947: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15948: when viewing in course context.
15949: 
15950:  input: six args -- filename (decluttered), course number, course domain,
15951:                     url, symb (if registered) and group (if this is a 
15952:                     group item -- e.g., bulletin board, group page etc.).
15953: 
15954:  output: array of five scalars --
15955:          $cfile -- url for file editing if editable on current server
15956:          $home -- homeserver of resource (i.e., for author if published,
15957:                                           or course if uploaded.).
15958:          $switchserver --  1 if server switch will be needed.
15959:          $forceedit -- 1 if icon/link should be to go to edit mode 
15960:          $forceview -- 1 if icon/link should be to go to view mode
15961: 
15962: =item *
15963: 
15964: is_course_upload($file,$cnum,$cdom)
15965: 
15966: Used in course context to determine if current file was uploaded to 
15967: the course (i.e., would be found in /userfiles/docs on the course's 
15968: homeserver.
15969: 
15970:   input: 3 args -- filename (decluttered), course number and course domain.
15971:   output: boolean -- 1 if file was uploaded.
15972: 
15973: =back
15974: 
15975: =head2 Storing/Retreiving Data
15976: 
15977: =over 4
15978: 
15979: =item *
15980: 
15981: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15982: permanently for this url; hashref needs to be given and should be a \%hashname;
15983: the remaining args aren't required and if they aren't passed or are '' they will
15984: be derived from the env (with the exception of $laststore, which is an 
15985: optional arg used when a user's submission is stored in grading).
15986: $laststore is $version=$timestamp, where $version is the most recent version
15987: number retrieved for the corresponding $symb in the $namespace db file, and
15988: $timestamp is the timestamp for that transaction (UNIX time).
15989: $laststore is currently only passed when cstore() is called by 
15990: structuretags::finalize_storage().
15991: 
15992: =item *
15993: 
15994: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15995: but uses critical subroutine
15996: 
15997: =item *
15998: 
15999: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16000: all args are optional
16001: 
16002: =item *
16003: 
16004: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
16005: dumps the complete (or key matching regexp) namespace into a hash
16006: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16007: normally &store()ed into
16008: 
16009: $range should be either an integer '100' (give me the first 100
16010:                                            matching records)
16011:               or be  two integers sperated by a - with no spaces
16012:                  '30-50' (give me the 30th through the 50th matching
16013:                           records)
16014: 
16015: 
16016: =item *
16017: 
16018: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16019: replaces a &store() version of data with a replacement set of data
16020: for a particular resource in a namespace passed in the $storehash hash 
16021: reference. If $tolog is true, the transaction is logged in the courselog
16022: with an action=PUTSTORE.
16023: 
16024: =item *
16025: 
16026: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16027: works very similar to store/cstore, but all data is stored in a
16028: temporary location and can be reset using tmpreset, $storehash should
16029: be a hash reference, returns nothing on success
16030: 
16031: =item *
16032: 
16033: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16034: similar to restore, but all data is stored in a temporary location and
16035: can be reset using tmpreset. Returns a hash of values on success,
16036: error string otherwise.
16037: 
16038: =item *
16039: 
16040: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16041: deltes all keys for $symb form the temporary storage hash.
16042: 
16043: =item *
16044: 
16045: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16046: reference filled in from namesp ($udom and $uname are optional)
16047: 
16048: =item *
16049: 
16050: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16051: namesp ($udom and $uname are optional)
16052: 
16053: =item *
16054: 
16055: dump($namespace,$udom,$uname,$regexp,$range) : 
16056: dumps the complete (or key matching regexp) namespace into a hash
16057: ($udom, $uname, $regexp, $range are optional)
16058: 
16059: $range should be either an integer '100' (give me the first 100
16060:                                            matching records)
16061:               or be  two integers sperated by a - with no spaces
16062:                  '30-50' (give me the 30th through the 50th matching
16063:                           records)
16064: =item *
16065: 
16066: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16067: $store can be a scalar, an array reference, or if the amount to be 
16068: incremented is > 1, a hash reference.
16069: 
16070: ($udom and $uname are optional)
16071: 
16072: =item *
16073: 
16074: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16075: ($udom and $uname are optional)
16076: 
16077: =item *
16078: 
16079: cput($namespace,$storehash,$udom,$uname) : critical put
16080: ($udom and $uname are optional)
16081: 
16082: =item *
16083: 
16084: newput($namespace,$storehash,$udom,$uname) :
16085: 
16086: Attempts to store the items in the $storehash, but only if they don't
16087: currently exist, if this succeeds you can be certain that you have 
16088: successfully created a new key value pair in the $namespace db.
16089: 
16090: 
16091: Args:
16092:  $namespace: name of database to store values to
16093:  $storehash: hashref to store to the db
16094:  $udom: (optional) domain of user containing the db
16095:  $uname: (optional) name of user caontaining the db
16096: 
16097: Returns:
16098:  'ok' -> succeeded in storing all keys of $storehash
16099:  'key_exists: <key>' -> failed to anything out of $storehash, as at
16100:                         least <key> already existed in the db (other
16101:                         requested keys may also already exist)
16102:  'error: <msg>' -> unable to tie the DB or other error occurred
16103:  'con_lost' -> unable to contact request server
16104:  'refused' -> action was not allowed by remote machine
16105: 
16106: 
16107: =item *
16108: 
16109: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16110: reference filled in from namesp (encrypts the return communication)
16111: ($udom and $uname are optional)
16112: 
16113: =item *
16114: 
16115: log($udom,$name,$home,$message) : write to permanent log for user; use
16116: critical subroutine
16117: 
16118: =item *
16119: 
16120: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16121: array reference filled in from namespace found in domain level on either
16122: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16123: 
16124: =item *
16125: 
16126: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16127: domain level either on specified domain server ($uhome) or primary domain 
16128: server ($udom and $uhome are optional)
16129: 
16130: =item * 
16131: 
16132: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16133: for: authentication, language, quotas, timezone, date locale, and portal URL in
16134: the target domain.
16135: 
16136: May also include additional key => value pairs for the following groups:
16137: 
16138: =over
16139: 
16140: =item
16141: disk quotas (MB allocated by default to portfolios and authoring spaces).
16142: 
16143: =over
16144: 
16145: =item defaultquota, authorquota
16146: 
16147: =back
16148: 
16149: =item
16150: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16151: portfolio for users).
16152: 
16153: =over
16154: 
16155: =item
16156: aboutme, blog, webdav, portfolio
16157: 
16158: =back
16159: 
16160: =item
16161: requestcourses: ability to request courses, and how requests are processed.
16162: 
16163: =over
16164: 
16165: =item
16166: official, unofficial, community, textbook, placement
16167: 
16168: =back
16169: 
16170: =item
16171: inststatus: types of institutional affiliation, and order in which they are displayed.
16172: 
16173: =over
16174: 
16175: =item
16176: inststatustypes, inststatusorder, inststatusguest
16177: 
16178: =back
16179: 
16180: =item
16181: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16182: for course's uploaded content.
16183: 
16184: =over
16185: 
16186: =item
16187: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16188: communityquota, textbookquota, placementquota
16189: 
16190: =back
16191: 
16192: =item
16193: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16194: on your servers.
16195: 
16196: =over
16197: 
16198: =item 
16199: remotesessions, hostedsessions
16200: 
16201: =back
16202: 
16203: =back
16204: 
16205: In cases where a domain coordinator has never used the "Set Domain Configuration"
16206: utility to create a configuration.db file on a domain's primary library server 
16207: only the following domain defaults: auth_def, auth_arg_def, lang_def
16208: -- corresponding values are authentication type (internal, krb4, krb5,
16209: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16210: will be available. Values are retrieved from cache (if current), unless the
16211: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16212: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16213: 
16214: Typical usage:
16215: 
16216: %domdefaults = &get_domain_defaults($target_domain);
16217: 
16218: =back
16219: 
16220: =head2 Network Status Functions
16221: 
16222: =over 4
16223: 
16224: =item *
16225: 
16226: dirlist() : return directory list based on URI (first arg).
16227: 
16228: Inputs: 1 required, 5 optional.
16229: 
16230: =over
16231: 
16232: =item 
16233: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16234: 
16235: =item
16236: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16237: 
16238: =item
16239: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16240: 
16241: =item
16242: $getpropath - boolean: 1 if prepend path using &propath(). 
16243: 
16244: =item
16245: $getuserdir - boolean: 1 if prepend path for "userfiles".
16246: 
16247: =item 
16248: $alternateRoot - path to prepend in place of path from $uri.
16249: 
16250: =back
16251: 
16252: Returns: Array of up to two items.
16253: 
16254: =over
16255: 
16256: a reference to an array of files/subdirectories
16257: 
16258: =over
16259: 
16260: Each element in the array of files/subdirectories is a & separated list of
16261: item name and the result of running stat on the item.  If dirlist was requested
16262: for a file instead of a directory, the item name will be ''. For a directory 
16263: listing, if the item is a metadata file, the element will end &N&M 
16264: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16265: default copyright set (1).  
16266: 
16267: =back
16268: 
16269: a scalar containing error condition (if encountered).
16270: 
16271: =over
16272: 
16273: =item 
16274: no_host (no homeserver identified for $username:$domain).
16275: 
16276: =item 
16277: no_such_host (server contacted for listing not identified as valid host).
16278: 
16279: =item 
16280: con_lost (connection to remote server failed).
16281: 
16282: =item 
16283: refused (invalid $username:$domain received on lond side).
16284: 
16285: =item 
16286: no_such_dir (directory at specified path on lond side does not exist). 
16287: 
16288: =item 
16289: empty (directory at specified path on lond side is empty).
16290: 
16291: =over
16292: 
16293: This is currently not encountered because the &ls3, &ls2, 
16294: &ls (_handler) routines on the lond side do not filter out
16295: . and .. from a directory listing. 
16296: 
16297: =back
16298: 
16299: =back
16300: 
16301: =back
16302: 
16303: =item *
16304: 
16305: spareserver() : find server with least workload from spare.tab
16306: 
16307: 
16308: =item *
16309: 
16310: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16311: if there is no corresponding loncapa host.
16312: 
16313: =back
16314: 
16315: 
16316: =head2 Apache Request
16317: 
16318: =over 4
16319: 
16320: =item *
16321: 
16322: ssi($url,%hash) : server side include, does a complete request cycle on url to
16323: localhost, posts hash
16324: 
16325: =back
16326: 
16327: =head2 Data to String to Data
16328: 
16329: =over 4
16330: 
16331: =item *
16332: 
16333: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16334: and '&' separators, supports elements that are arrayrefs and hashrefs
16335: 
16336: =item *
16337: 
16338: hashref2str($hashref) : convert a hashref into a string complete with
16339: escaping and '=' and '&' separators, supports elements that are
16340: arrayrefs and hashrefs
16341: 
16342: =item *
16343: 
16344: arrayref2str($arrayref) : convert an arrayref into a string complete
16345: with escaping and '&' separators, supports elements that are arrayrefs
16346: and hashrefs
16347: 
16348: =item *
16349: 
16350: str2hash($string) : convert string to hash using unescaping and
16351: splitting on '=' and '&', supports elements that are arrayrefs and
16352: hashrefs
16353: 
16354: =item *
16355: 
16356: str2array($string) : convert string to hash using unescaping and
16357: splitting on '&', supports elements that are arrayrefs and hashrefs
16358: 
16359: =back
16360: 
16361: =head2 Logging Routines
16362: 
16363: 
16364: These routines allow one to make log messages in the lonnet.log and
16365: lonnet.perm logfiles.
16366: 
16367: =over 4
16368: 
16369: =item *
16370: 
16371: logtouch() : make sure the logfile, lonnet.log, exists
16372: 
16373: =item *
16374: 
16375: logthis() : append message to the normal lonnet.log file, it gets
16376: preiodically rolled over and deleted.
16377: 
16378: =item *
16379: 
16380: logperm() : append a permanent message to lonnet.perm.log, this log
16381: file never gets deleted by any automated portion of the system, only
16382: messages of critical importance should go in here.
16383: 
16384: 
16385: =back
16386: 
16387: =head2 General File Helper Routines
16388: 
16389: =over 4
16390: 
16391: =item *
16392: 
16393: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16394: (a) files in /uploaded
16395:   (i) If a local copy of the file exists - 
16396:       compares modification date of local copy with last-modified date for 
16397:       definitive version stored on home server for course. If local copy is 
16398:       stale, requests a new version from the home server and stores it. 
16399:       If the original has been removed from the home server, then local copy 
16400:       is unlinked.
16401:   (ii) If local copy does not exist -
16402:       requests the file from the home server and stores it. 
16403:   
16404:   If $caller is 'uploadrep':  
16405:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16406:     for request for files originally uploaded via DOCS. 
16407:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16408:   
16409:   Otherwise:
16410:      This indicates a call from the content generation phase of the request.
16411:      -  returns the entire contents of the file or -1.
16412:      
16413: (b) files in /res
16414:    - returns the entire contents of a file or -1; 
16415:    it properly subscribes to and replicates the file if neccessary.
16416: 
16417: 
16418: =item *
16419: 
16420: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16421:                   reference
16422: 
16423: returns either a stat() list of data about the file or an empty list
16424: if the file doesn't exist or couldn't find out about it (connection
16425: problems or user unknown)
16426: 
16427: =item *
16428: 
16429: filelocation($dir,$file) : returns file system location of a file
16430: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16431: directory that relative $file lookups are to looked in ($dir of /a/dir
16432: and a file of ../bob will become /a/bob)
16433: 
16434: =item *
16435: 
16436: hreflocation($dir,$file) : returns file system location or a URL; same as
16437: filelocation except for hrefs
16438: 
16439: =item *
16440: 
16441: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16442: also removes beginning /home/httpd/html unless /priv/ follows it.
16443: 
16444: =back
16445: 
16446: =head2 Usererfile file routines (/uploaded*)
16447: 
16448: =over 4
16449: 
16450: =item *
16451: 
16452: userfileupload(): main rotine for putting a file in a user or course's
16453:                   filespace, arguments are,
16454: 
16455:  formname - required - this is the name of the element in $env where the
16456:            filename, and the contents of the file to create/modifed exist
16457:            the filename is in $env{'form.'.$formname.'.filename'} and the
16458:            contents of the file is located in $env{'form.'.$formname}
16459:  context - if coursedoc, store the file in the course of the active role
16460:              of the current user; 
16461:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16462:            if 'canceloverwrite': delete file in tmp/overwrites directory
16463:  subdir - required - subdirectory to put the file in under ../userfiles/
16464:          if undefined, it will be placed in "unknown"
16465: 
16466:  (This routine calls clean_filename() to remove any dangerous
16467:  characters from the filename, and then calls finuserfileupload() to
16468:  complete the transaction)
16469: 
16470:  returns either the url of the uploaded file (/uploaded/....) if successful
16471:  and /adm/notfound.html if unsuccessful
16472: 
16473: =item *
16474: 
16475: clean_filename(): routine for cleaing a filename up for storage in
16476:                  userfile space, argument is:
16477: 
16478:  filename - proposed filename
16479: 
16480: returns: the new clean filename
16481: 
16482: =item *
16483: 
16484: finishuserfileupload(): routine that creates and sends the file to
16485: userspace, probably shouldn't be called directly
16486: 
16487:   docuname: username or courseid of destination for the file
16488:   docudom: domain of user/course of destination for the file
16489:   formname: same as for userfileupload()
16490:   fname: filename (including subdirectories) for the file
16491:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16492:           if hashref, and context is scantron, will convert csv format to standard format
16493:   allfiles: reference to hash used to store objects found by parser
16494:   codebase: reference to hash used for codebases of java objects found by parser
16495:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16496:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16497:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16498:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16499:   context: if 'overwrite', will move the uploaded file from its temporary location to
16500:             userfiles to facilitate overwriting a previously uploaded file with same name.
16501:   mimetype: reference to scalar to accommodate mime type determined
16502:             from File::MMagic if $parser = parse.
16503: 
16504:  returns either the url of the uploaded file (/uploaded/....) if successful
16505:  and /adm/notfound.html if unsuccessful (or an error message if context 
16506:  was 'overwrite').
16507:  
16508: 
16509: =item *
16510: 
16511: renameuserfile(): renames an existing userfile to a new name
16512: 
16513:   Args:
16514:    docuname: username or courseid of destination for the file
16515:    docudom: domain of user/course of destination for the file
16516:    old: current file name (including any subdirs under userfiles)
16517:    new: desired file name (including any subdirs under userfiles)
16518: 
16519: =item *
16520: 
16521: mkdiruserfile(): creates a directory is a userfiles dir
16522: 
16523:   Args:
16524:    docuname: username or courseid of destination for the file
16525:    docudom: domain of user/course of destination for the file
16526:    dir: dir to create (including any subdirs under userfiles)
16527: 
16528: =item *
16529: 
16530: removeuserfile(): removes a file that exists in userfiles
16531: 
16532:   Args:
16533:    docuname: username or courseid of destination for the file
16534:    docudom: domain of user/course of destination for the file
16535:    fname: filname to delete (including any subdirs under userfiles)
16536: 
16537: =item *
16538: 
16539: removeuploadedurl(): convience function for removeuserfile()
16540: 
16541:   Args:
16542:    url:  a full /uploaded/... url to delete
16543: 
16544: =item * 
16545: 
16546: get_portfile_permissions():
16547:   Args:
16548:     domain: domain of user or course contain the portfolio files
16549:     user: name of user or num of course contain the portfolio files
16550:   Returns:
16551:     hashref of a dump of the proper file_permissions.db
16552:    
16553: 
16554: =item * 
16555: 
16556: get_access_controls():
16557: 
16558: Args:
16559:   current_permissions: the hash ref returned from get_portfile_permissions()
16560:   group: (optional) the group you want the files associated with
16561:   file: (optional) the file you want access info on
16562: 
16563: Returns:
16564:     a hash (keys are file names) of hashes containing
16565:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16566:         values are XML containing access control settings (see below) 
16567: 
16568: Internal notes:
16569: 
16570:  access controls are stored in file_permissions.db as key=value pairs.
16571:     key -> path to file/file_name\0uniqueID:scope_end_start
16572:         where scope -> public,guest,course,group,domains or users.
16573:               end -> UNIX time for end of access (0 -> no end date)
16574:               start -> UNIX time for start of access
16575: 
16576:     value -> XML description of access control
16577:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16578:             <start></start>
16579:             <end></end>
16580: 
16581:             <password></password>  for scope type = guest
16582: 
16583:             <domain></domain>     for scope type = course or group
16584:             <number></number>
16585:             <roles id="">
16586:              <role></role>
16587:              <access></access>
16588:              <section></section>
16589:              <group></group>
16590:             </roles>
16591: 
16592:             <dom></dom>         for scope type = domains
16593: 
16594:             <users>             for scope type = users
16595:              <user>
16596:               <uname></uname>
16597:               <udom></udom>
16598:              </user>
16599:             </users>
16600:            </scope> 
16601:               
16602:  Access data is also aggregated for each file in an additional key=value pair:
16603:  key -> path to file/file_name\0accesscontrol 
16604:  value -> reference to hash
16605:           hash contains key = value pairs
16606:           where key = uniqueID:scope_end_start
16607:                 value = UNIX time record was last updated
16608: 
16609:           Used to improve speed of look-ups of access controls for each file.  
16610:  
16611:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16612: 
16613: =item *
16614: 
16615: modify_access_controls():
16616: 
16617: Modifies access controls for a portfolio file
16618: Args
16619: 1. file name
16620: 2. reference to hash of required changes,
16621: 3. domain
16622: 4. username
16623:   where domain,username are the domain of the portfolio owner 
16624:   (either a user or a course) 
16625: 
16626: Returns:
16627: 1. result of additions or updates ('ok' or 'error', with error message). 
16628: 2. result of deletions ('ok' or 'error', with error message).
16629: 3. reference to hash of any new or updated access controls.
16630: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16631:    key = integer (inbound ID)
16632:    value = uniqueID
16633: 
16634: =item *
16635: 
16636: get_timebased_id():
16637: 
16638: Attempts to get a unique timestamp-based suffix for use with items added to a 
16639: course via the Course Editor (e.g., folders, composite pages, 
16640: group bulletin boards).
16641: 
16642: Args: (first three required; six others optional)
16643: 
16644: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16645:    docssequence, or name of group
16646: 
16647: 2. keyid (alphanumeric): name of temporary locking key in hash,
16648:    e.g., num, boardids
16649: 
16650: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16651:    file will be named nohist_namespace.db
16652: 
16653: 4. cdom: domain of course; default is current course domain from %env
16654: 
16655: 5. cnum: course number; default is current course number from %env
16656: 
16657: 6. idtype: set to concat if an additional digit is to be appended to the 
16658:    unix timestamp to form the suffix, if the plain timestamp is already
16659:    in use.  Default is to not do this, but simply increment the unix 
16660:    timestamp by 1 until a unique key is obtained.
16661: 
16662: 7. who: holder of locking key; defaults to user:domain for user.
16663: 
16664: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16665:    retrying); default is 3.
16666: 
16667: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16668: 
16669: Returns:
16670: 
16671: 1. suffix obtained (numeric)
16672: 
16673: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16674: 
16675: 3. error: contains (localized) error message if an error occurred.
16676: 
16677: 
16678: =back
16679: 
16680: =head2 HTTP Helper Routines
16681: 
16682: =over 4
16683: 
16684: =item *
16685: 
16686: escape() : unpack non-word characters into CGI-compatible hex codes
16687: 
16688: =item *
16689: 
16690: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16691: 
16692: =back
16693: 
16694: =head1 PRIVATE SUBROUTINES
16695: 
16696: =head2 Underlying communication routines (Shouldn't call)
16697: 
16698: =over 4
16699: 
16700: =item *
16701: 
16702: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16703: 
16704: =item *
16705: 
16706: reply() : uses subreply to send a message to remote machine, logs all failures
16707: 
16708: =item *
16709: 
16710: critical() : passes a critical message to another server; if cannot
16711: get through then place message in connection buffer directory and
16712: returns con_delayed, if incapable of saving message, returns
16713: con_failed
16714: 
16715: =item *
16716: 
16717: reconlonc() : tries to reconnect lonc client processes.
16718: 
16719: =back
16720: 
16721: =head2 Resource Access Logging
16722: 
16723: =over 4
16724: 
16725: =item *
16726: 
16727: flushcourselogs() : flush (save) buffer logs and access logs
16728: 
16729: =item *
16730: 
16731: courselog($what) : save message for course in hash
16732: 
16733: =item *
16734: 
16735: courseacclog($what) : save message for course using &courselog().  Perform
16736: special processing for specific resource types (problems, exams, quizzes, etc).
16737: 
16738: =item *
16739: 
16740: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16741: as a PerlChildExitHandler
16742: 
16743: =back
16744: 
16745: =head2 Other
16746: 
16747: =over 4
16748: 
16749: =item *
16750: 
16751: symblist($mapname,%newhash) : update symbolic storage links
16752: 
16753: =back
16754: 
16755: =cut
16756: 

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