File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1172.2.93.4.8: download - view: text, annotated - select for diffs
Wed Mar 28 10:22:10 2018 UTC (6 years, 2 months ago) by raeburn
Branches: version_2_11_2_msu
Diff to branchpoint 1.1172.2.93: preferred, unified
- For 2.11.2 (modified)
  - Include changes in 1.1369

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1172.2.93.4.8 2018/03/28 10:22:10 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 LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   80:             %managerstab);
   81: 
   82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   85:     %courseownerbuf, %coursetypebuf,$locknum);
   86: 
   87: use IO::Socket;
   88: use GDBM_File;
   89: use HTML::LCParser;
   90: use Fcntl qw(:flock);
   91: use Storable qw(thaw nfreeze);
   92: use Time::HiRes qw( sleep gettimeofday tv_interval );
   93: use Cache::Memcached;
   94: use Digest::MD5;
   95: use Math::Random;
   96: use File::MMagic;
   97: use LONCAPA qw(:DEFAULT :match);
   98: use LONCAPA::Configuration;
   99: use LONCAPA::lonmetadata;
  100: use LONCAPA::Lond;
  101: 
  102: use File::Copy;
  103: 
  104: my $readit;
  105: my $max_connection_retries = 20;     # Or some such value.
  106: 
  107: require Exporter;
  108: 
  109: our @ISA = qw (Exporter);
  110: our @EXPORT = qw(%env);
  111: 
  112: # ------------------------------------ Logging (parameters, docs, slots, roles)
  113: {
  114:     my $logid;
  115:     sub write_log {
  116: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  117:         if ($context eq 'course') {
  118:             if (($cnum eq '') || ($cdom eq '')) {
  119:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  120:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  121:             }
  122:         }
  123: 	$logid ++;
  124:         my $now = time();
  125: 	my $id=$now.'00000'.$$.'00000'.$logid;
  126:         my $logentry = {
  127:                          $id => {
  128:                                   'exe_uname' => $env{'user.name'},
  129:                                   'exe_udom'  => $env{'user.domain'},
  130:                                   'exe_time'  => $now,
  131:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
  132:                                   'delflag'   => $delflag,
  133:                                   'logentry'  => $storehash,
  134:                                   'uname'     => $uname,
  135:                                   'udom'      => $udom,
  136:                                 }
  137:                        };
  138:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  139:     }
  140: }
  141: 
  142: sub logtouch {
  143:     my $execdir=$perlvar{'lonDaemons'};
  144:     unless (-e "$execdir/logs/lonnet.log") {	
  145: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  146: 	close $fh;
  147:     }
  148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  150: }
  151: 
  152: sub logthis {
  153:     my $message=shift;
  154:     my $execdir=$perlvar{'lonDaemons'};
  155:     my $now=time;
  156:     my $local=localtime($now);
  157:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  159: 	print $fh $logstring;
  160: 	close($fh);
  161:     }
  162:     return 1;
  163: }
  164: 
  165: sub logperm {
  166:     my $message=shift;
  167:     my $execdir=$perlvar{'lonDaemons'};
  168:     my $now=time;
  169:     my $local=localtime($now);
  170:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  171: 	print $fh "$now:$message:$local\n";
  172: 	close($fh);
  173:     }
  174:     return 1;
  175: }
  176: 
  177: sub create_connection {
  178:     my ($hostname,$lonid) = @_;
  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  180: 				     Type    => SOCK_STREAM,
  181: 				     Timeout => 10);
  182:     return 0 if (!$client);
  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  184:     my $result = <$client>;
  185:     chomp($result);
  186:     return 1 if ($result eq 'done');
  187:     return 0;
  188: }
  189: 
  190: sub get_server_timezone {
  191:     my ($cnum,$cdom) = @_;
  192:     my $home=&homeserver($cnum,$cdom);
  193:     if ($home ne 'no_host') {
  194:         my $cachetime = 24*3600;
  195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  196:         if (defined($cached)) {
  197:             return $timezone;
  198:         } else {
  199:             my $timezone = &reply('servertimezone',$home);
  200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  201:         }
  202:     }
  203: }
  204: 
  205: sub get_server_distarch {
  206:     my ($lonhost,$ignore_cache) = @_;
  207:     if (defined($lonhost)) {
  208:         if (!defined(&hostname($lonhost))) {
  209:             return;
  210:         }
  211:         my $cachetime = 12*3600;
  212:         if (!$ignore_cache) {
  213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  214:             if (defined($cached)) {
  215:                 return $distarch;
  216:             }
  217:         }
  218:         my $rep = &reply('serverdistarch',$lonhost);
  219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  221:                 $rep eq '') {
  222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  223:         }
  224:     }
  225:     return;
  226: }
  227: 
  228: sub get_server_loncaparev {
  229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  230:     if (defined($lonhost)) {
  231:         if (!defined(&hostname($lonhost))) {
  232:             undef($lonhost);
  233:         }
  234:     }
  235:     if (!defined($lonhost)) {
  236:         if (defined(&domain($dom,'primary'))) {
  237:             $lonhost=&domain($dom,'primary');
  238:             if ($lonhost eq 'no_host') {
  239:                 undef($lonhost);
  240:             }
  241:         }
  242:     }
  243:     if (defined($lonhost)) {
  244:         my $cachetime = 12*3600;
  245:         if (!$ignore_cache) {
  246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  247:             if (defined($cached)) {
  248:                 return $loncaparev;
  249:             }
  250:         }
  251:         my ($answer,$loncaparev);
  252:         my @ids=&current_machine_ids();
  253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  254:             $answer = $perlvar{'lonVersion'};
  255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  256:                 $loncaparev = $1;
  257:             }
  258:         } else {
  259:             $answer = &reply('serverloncaparev',$lonhost);
  260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  261:                 if ($caller eq 'loncron') {
  262:                     my $ua=new LWP::UserAgent;
  263:                     $ua->timeout(4);
  264:                     my $protocol = $protocol{$lonhost};
  265:                     $protocol = 'http' if ($protocol ne 'https');
  266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  267:                     my $request=new HTTP::Request('GET',$url);
  268:                     my $response=$ua->request($request);
  269:                     unless ($response->is_error()) {
  270:                         my $content = $response->content;
  271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  272:                             $loncaparev = $1;
  273:                         }
  274:                     }
  275:                 } else {
  276:                     $loncaparev = $loncaparevs{$lonhost};
  277:                 }
  278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  279:                 $loncaparev = $1;
  280:             }
  281:         }
  282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  283:     }
  284: }
  285: 
  286: sub get_server_homeID {
  287:     my ($hostname,$ignore_cache,$caller) = @_;
  288:     unless ($ignore_cache) {
  289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  290:         if (defined($cached)) {
  291:             return $serverhomeID;
  292:         }
  293:     }
  294:     my $cachetime = 12*3600;
  295:     my $serverhomeID;
  296:     if ($caller eq 'loncron') { 
  297:         my @machine_ids = &machine_ids($hostname);
  298:         foreach my $id (@machine_ids) {
  299:             my $response = &reply('serverhomeID',$id);
  300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  301:                 $serverhomeID = $response;
  302:                 last;
  303:             }
  304:         }
  305:         if ($serverhomeID eq '') {
  306:             $serverhomeID = $machine_ids[-1];
  307:         }
  308:     } else {
  309:         $serverhomeID = $serverhomeIDs{$hostname};
  310:     }
  311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  312: }
  313: 
  314: sub get_remote_globals {
  315:     my ($lonhost,$whathash,$ignore_cache) = @_;
  316:     my ($result,%returnhash,%whatneeded);
  317:     if (ref($whathash) eq 'HASH') {
  318:         foreach my $what (sort(keys(%{$whathash}))) {
  319:             my $hashid = $lonhost.'-'.$what;
  320:             my ($response,$cached);
  321:             unless ($ignore_cache) {
  322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  323:             }
  324:             if (defined($cached)) {
  325:                 $returnhash{$what} = $response;
  326:             } else {
  327:                 $whatneeded{$what} = 1;
  328:             }
  329:         }
  330:         if (keys(%whatneeded) == 0) {
  331:             $result = 'ok';
  332:         } else {
  333:             my $requested = &freeze_escape(\%whatneeded);
  334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  336:                 ($rep eq 'unknown_cmd')) {
  337:                 $result = $rep;
  338:             } else {
  339:                 $result = 'ok';
  340:                 my @pairs=split(/\&/,$rep);
  341:                 foreach my $item (@pairs) {
  342:                     my ($key,$value)=split(/=/,$item,2);
  343:                     my $what = &unescape($key);
  344:                     my $hashid = $lonhost.'-'.$what;
  345:                     $returnhash{$what}=&thaw_unescape($value);
  346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  347:                 }
  348:             }
  349:         }
  350:     }
  351:     return ($result,\%returnhash);
  352: }
  353: 
  354: sub remote_devalidate_cache {
  355:     my ($lonhost,$cachekeys) = @_;
  356:     my $items;
  357:     return unless (ref($cachekeys) eq 'ARRAY');
  358:     my $cachestr = join('&',@{$cachekeys});
  359:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  360: }
  361: 
  362: # -------------------------------------------------- Non-critical communication
  363: sub subreply {
  364:     my ($cmd,$server)=@_;
  365:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  366:     #
  367:     #  With loncnew process trimming, there's a timing hole between lonc server
  368:     #  process exit and the master server picking up the listen on the AF_UNIX
  369:     #  socket.  In that time interval, a lock file will exist:
  370: 
  371:     my $lockfile=$peerfile.".lock";
  372:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  373: 	sleep(0.1);
  374:     }
  375:     # At this point, either a loncnew parent is listening or an old lonc
  376:     # or loncnew child is listening so we can connect or everything's dead.
  377:     #
  378:     #   We'll give the connection a few tries before abandoning it.  If
  379:     #   connection is not possible, we'll con_lost back to the client.
  380:     #   
  381:     my $client;
  382:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  383: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  384: 				      Type    => SOCK_STREAM,
  385: 				      Timeout => 10);
  386: 	if ($client) {
  387: 	    last;		# Connected!
  388: 	} else {
  389: 	    &create_connection(&hostname($server),$server);
  390: 	}
  391:         sleep(0.1);		# Try again later if failed connection.
  392:     }
  393:     my $answer;
  394:     if ($client) {
  395: 	print $client "sethost:$server:$cmd\n";
  396: 	$answer=<$client>;
  397: 	if (!$answer) { $answer="con_lost"; }
  398: 	chomp($answer);
  399:     } else {
  400: 	$answer = 'con_lost';	# Failed connection.
  401:     }
  402:     return $answer;
  403: }
  404: 
  405: sub reply {
  406:     my ($cmd,$server)=@_;
  407:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  408:     my $answer=subreply($cmd,$server);
  409:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  410:        &logthis("<font color=\"blue\">WARNING:".
  411:                 " $cmd to $server returned $answer</font>");
  412:     }
  413:     return $answer;
  414: }
  415: 
  416: # ----------------------------------------------------------- Send USR1 to lonc
  417: 
  418: sub reconlonc {
  419:     my ($lonid) = @_;
  420:     if ($lonid) {
  421:         my $hostname = &hostname($lonid);
  422: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  423: 	if ($hostname && -e $peerfile) {
  424: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  425: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  426: 					     Type    => SOCK_STREAM,
  427: 					     Timeout => 10);
  428: 	    if ($client) {
  429: 		print $client ("reset_retries\n");
  430: 		my $answer=<$client>;
  431: 		#reset just this one.
  432: 	    }
  433: 	}
  434: 	return;
  435:     }
  436: 
  437:     &logthis("Trying to reconnect lonc");
  438:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  439:     if (open(my $fh,"<",$loncfile)) {
  440: 	my $loncpid=<$fh>;
  441:         chomp($loncpid);
  442:         if (kill 0 => $loncpid) {
  443: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  444:             kill USR1 => $loncpid;
  445:             sleep 1;
  446:          } else {
  447: 	    &logthis(
  448:                "<font color=\"blue\">WARNING:".
  449:                " lonc at pid $loncpid not responding, giving up</font>");
  450:         }
  451:     } else {
  452: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  453:     }
  454: }
  455: 
  456: # ------------------------------------------------------ Critical communication
  457: 
  458: sub critical {
  459:     my ($cmd,$server)=@_;
  460:     unless (&hostname($server)) {
  461:         &logthis("<font color=\"blue\">WARNING:".
  462:                " Critical message to unknown server ($server)</font>");
  463:         return 'no_such_host';
  464:     }
  465:     my $answer=reply($cmd,$server);
  466:     if ($answer eq 'con_lost') {
  467: 	&reconlonc($server);
  468: 	my $answer=reply($cmd,$server);
  469:         if ($answer eq 'con_lost') {
  470:             my $now=time;
  471:             my $middlename=$cmd;
  472:             $middlename=substr($middlename,0,16);
  473:             $middlename=~s/\W//g;
  474:             my $dfilename=
  475:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  476:             $dumpcount++;
  477:             {
  478: 		my $dfh;
  479: 		if (open($dfh,">",$dfilename)) {
  480: 		    print $dfh "$cmd\n"; 
  481: 		    close($dfh);
  482: 		}
  483:             }
  484:             sleep 1;
  485:             my $wcmd='';
  486:             {
  487: 		my $dfh;
  488: 		if (open($dfh,"<",$dfilename)) {
  489: 		    $wcmd=<$dfh>; 
  490: 		    close($dfh);
  491: 		}
  492:             }
  493:             chomp($wcmd);
  494:             if ($wcmd eq $cmd) {
  495: 		&logthis("<font color=\"blue\">WARNING: ".
  496:                          "Connection buffer $dfilename: $cmd</font>");
  497:                 &logperm("D:$server:$cmd");
  498: 	        return 'con_delayed';
  499:             } else {
  500:                 &logthis("<font color=\"red\">CRITICAL:"
  501:                         ." Critical connection failed: $server $cmd</font>");
  502:                 &logperm("F:$server:$cmd");
  503:                 return 'con_failed';
  504:             }
  505:         }
  506:     }
  507:     return $answer;
  508: }
  509: 
  510: # ------------------------------------------- check if return value is an error
  511: 
  512: sub error {
  513:     my ($result) = @_;
  514:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  515: 	if ($2 == 2) { return undef; }
  516: 	return $1;
  517:     }
  518:     return undef;
  519: }
  520: 
  521: sub convert_and_load_session_env {
  522:     my ($lonidsdir,$handle)=@_;
  523:     my @profile;
  524:     {
  525: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  526: 	if (!$opened) {
  527: 	    return 0;
  528: 	}
  529: 	flock($idf,LOCK_SH);
  530: 	@profile=<$idf>;
  531: 	close($idf);
  532:     }
  533:     my %temp_env;
  534:     foreach my $line (@profile) {
  535: 	if ($line !~ m/=/) {
  536: 	    return 0;
  537: 	}
  538: 	chomp($line);
  539: 	my ($envname,$envvalue)=split(/=/,$line,2);
  540: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  541:     }
  542:     unlink("$lonidsdir/$handle.id");
  543:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  544: 	    0640)) {
  545: 	%disk_env = %temp_env;
  546: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  547: 	untie(%disk_env);
  548:     }
  549:     return 1;
  550: }
  551: 
  552: # ------------------------------------------- Transfer profile into environment
  553: my $env_loaded;
  554: sub transfer_profile_to_env {
  555:     my ($lonidsdir,$handle,$force_transfer) = @_;
  556:     if (!$force_transfer && $env_loaded) { return; } 
  557: 
  558:     if (!defined($lonidsdir)) {
  559: 	$lonidsdir = $perlvar{'lonIDsDir'};
  560:     }
  561:     if (!defined($handle)) {
  562:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  563:     }
  564: 
  565:     my $convert;
  566:     {
  567:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  568: 	if (!$opened) {
  569: 	    return;
  570: 	}
  571: 	flock($idf,LOCK_SH);
  572: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  573: 		&GDBM_READER(),0640)) {
  574: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  575: 	    untie(%disk_env);
  576: 	} else {
  577: 	    $convert = 1;
  578: 	}
  579:     }
  580:     if ($convert) {
  581: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  582: 	    &logthis("Failed to load session, or convert session.");
  583: 	}
  584:     }
  585: 
  586:     my %remove;
  587:     while ( my $envname = each(%env) ) {
  588:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  589:             if ($time < time-300) {
  590:                 $remove{$key}++;
  591:             }
  592:         }
  593:     }
  594: 
  595:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  596:     $env_loaded=1;
  597:     foreach my $expired_key (keys(%remove)) {
  598:         &delenv($expired_key);
  599:     }
  600: }
  601: 
  602: # ---------------------------------------------------- Check for valid session 
  603: sub check_for_valid_session {
  604:     my ($r,$name,$userhashref,$domref) = @_;
  605:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  606:     if ($name eq '') {
  607:         $name = 'lonID';
  608:     }
  609:     my $lonid=$cookies{$name};
  610:     return undef if (!$lonid);
  611: 
  612:     my $handle=&LONCAPA::clean_handle($lonid->value);
  613:     my $lonidsdir;
  614:     if ($name eq 'lonDAV') {
  615:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  616:     } else {
  617:         $lonidsdir=$r->dir_config('lonIDsDir');
  618:     }
  619:     if (!-e "$lonidsdir/$handle.id") {
  620:         if ((ref($domref)) && ($name eq 'lonID') &&
  621:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  622:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  623:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  624:                 $$domref = $possudom;
  625:             }
  626:         }
  627:         return undef;
  628:     }
  629: 
  630:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  631:     return undef if (!$opened);
  632: 
  633:     flock($idf,LOCK_SH);
  634:     my %disk_env;
  635:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  636: 	    &GDBM_READER(),0640)) {
  637: 	return undef;	
  638:     }
  639: 
  640:     if (!defined($disk_env{'user.name'})
  641: 	|| !defined($disk_env{'user.domain'})) {
  642: 	return undef;
  643:     }
  644: 
  645:     if (ref($userhashref) eq 'HASH') {
  646:         $userhashref->{'name'} = $disk_env{'user.name'};
  647:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  648:     }
  649: 
  650:     return $handle;
  651: }
  652: 
  653: sub timed_flock {
  654:     my ($file,$lock_type) = @_;
  655:     my $failed=0;
  656:     eval {
  657: 	local $SIG{__DIE__}='DEFAULT';
  658: 	local $SIG{ALRM}=sub {
  659: 	    $failed=1;
  660: 	    die("failed lock");
  661: 	};
  662: 	alarm(13);
  663: 	flock($file,$lock_type);
  664: 	alarm(0);
  665:     };
  666:     if ($failed) {
  667: 	return undef;
  668:     } else {
  669: 	return 1;
  670:     }
  671: }
  672: 
  673: # ---------------------------------------------------------- Append Environment
  674: 
  675: sub appenv {
  676:     my ($newenv,$roles) = @_;
  677:     if (ref($newenv) eq 'HASH') {
  678:         foreach my $key (keys(%{$newenv})) {
  679:             my $refused = 0;
  680: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  681:                 $refused = 1;
  682:                 if (ref($roles) eq 'ARRAY') {
  683:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  684:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  685:                         $refused = 0;
  686:                     }
  687:                 }
  688:             }
  689:             if ($refused) {
  690:                 &logthis("<font color=\"blue\">WARNING: ".
  691:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  692:                          .'</font>');
  693: 	        delete($newenv->{$key});
  694:             } else {
  695:                 $env{$key}=$newenv->{$key};
  696:             }
  697:         }
  698:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  699:         if ($opened
  700: 	    && &timed_flock($env_file,LOCK_EX)
  701: 	    &&
  702: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  703: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  704: 	    while (my ($key,$value) = each(%{$newenv})) {
  705: 	        $disk_env{$key} = $value;
  706: 	    }
  707: 	    untie(%disk_env);
  708:         }
  709:     }
  710:     return 'ok';
  711: }
  712: # ----------------------------------------------------- Delete from Environment
  713: 
  714: sub delenv {
  715:     my ($delthis,$regexp,$roles) = @_;
  716:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  717:         my $refused = 1;
  718:         if (ref($roles) eq 'ARRAY') {
  719:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  720:             if (grep(/^\Q$role\E$/,@{$roles})) {
  721:                 $refused = 0;
  722:             }
  723:         }
  724:         if ($refused) {
  725:             &logthis("<font color=\"blue\">WARNING: ".
  726:                      "Attempt to delete from environment ".$delthis);
  727:             return 'error';
  728:         }
  729:     }
  730:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  731:     if ($opened
  732: 	&& &timed_flock($env_file,LOCK_EX)
  733: 	&&
  734: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  735: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  736: 	foreach my $key (keys(%disk_env)) {
  737: 	    if ($regexp) {
  738:                 if ($key=~/^$delthis/) {
  739:                     delete($env{$key});
  740:                     delete($disk_env{$key});
  741:                 } 
  742:             } else {
  743:                 if ($key=~/^\Q$delthis\E/) {
  744: 		    delete($env{$key});
  745: 		    delete($disk_env{$key});
  746: 	        }
  747:             }
  748: 	}
  749: 	untie(%disk_env);
  750:     }
  751:     return 'ok';
  752: }
  753: 
  754: sub get_env_multiple {
  755:     my ($name) = @_;
  756:     my @values;
  757:     if (defined($env{$name})) {
  758:         # exists is it an array
  759:         if (ref($env{$name})) {
  760:             @values=@{ $env{$name} };
  761:         } else {
  762:             $values[0]=$env{$name};
  763:         }
  764:     }
  765:     return(@values);
  766: }
  767: 
  768: # ------------------------------------------------------------------- Locking
  769: 
  770: sub set_lock {
  771:     my ($text)=@_;
  772:     $locknum++;
  773:     my $id=$$.'-'.$locknum;
  774:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  775:              'session.lock.'.$id => $text});
  776:     return $id;
  777: }
  778: 
  779: sub get_locks {
  780:     my $num=0;
  781:     my %texts=();
  782:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  783:        if ($lock=~/\w/) {
  784:           $num++;
  785:           $texts{$lock}=$env{'session.lock.'.$lock};
  786:        }
  787:    }
  788:    return ($num,%texts);
  789: }
  790: 
  791: sub remove_lock {
  792:     my ($id)=@_;
  793:     my $newlocks='';
  794:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  795:        if (($lock=~/\w/) && ($lock ne $id)) {
  796:           $newlocks.=','.$lock;
  797:        }
  798:     }
  799:     &appenv({'session.locks' => $newlocks});
  800:     &delenv('session.lock.'.$id);
  801: }
  802: 
  803: sub remove_all_locks {
  804:     my $activelocks=$env{'session.locks'};
  805:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  806:        if ($lock=~/\w/) {
  807:           &remove_lock($lock);
  808:        }
  809:     }
  810: }
  811: 
  812: 
  813: # ------------------------------------------ Find out current server userload
  814: sub userload {
  815:     my $numusers=0;
  816:     {
  817: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  818: 	my $filename;
  819: 	my $curtime=time;
  820: 	while ($filename=readdir(LONIDS)) {
  821: 	    next if ($filename eq '.' || $filename eq '..');
  822: 	    next if ($filename =~ /publicuser_\d+\.id/);
  823: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  824: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  825: 	}
  826: 	closedir(LONIDS);
  827:     }
  828:     my $userloadpercent=0;
  829:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  830:     if ($maxuserload) {
  831: 	$userloadpercent=100*$numusers/$maxuserload;
  832:     }
  833:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  834:     return $userloadpercent;
  835: }
  836: 
  837: # ------------------------------ Find server with least workload from spare.tab
  838: 
  839: sub spareserver {
  840:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  841:     my $spare_server;
  842:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  843:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  844:                                                      :  $userloadpercent;
  845:     my ($uint_dom,$remotesessions);
  846:     if (($udom ne '') && (&domain($udom) ne '')) {
  847:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  848:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  849:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  850:         $remotesessions = $udomdefaults{'remotesessions'};
  851:     }
  852:     my $spareshash = &this_host_spares($udom);
  853:     if (ref($spareshash) eq 'HASH') {
  854:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  855:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  856:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  857:                                              $try_server));
  858: 	        ($spare_server, $lowest_load) =
  859: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  860:             }
  861:         }
  862: 
  863:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  864: 
  865:         if (!$found_server) {
  866:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  867: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  868:                     next unless (&spare_can_host($udom,$uint_dom,
  869:                                                  $remotesessions,$try_server));
  870: 	            ($spare_server, $lowest_load) =
  871: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  872:                 }
  873: 	    }
  874:         }
  875:     }
  876: 
  877:     if (!$want_server_name) {
  878:         my $protocol = 'http';
  879:         if ($protocol{$spare_server} eq 'https') {
  880:             $protocol = $protocol{$spare_server};
  881:         }
  882:         if (defined($spare_server)) {
  883:             my $hostname = &hostname($spare_server);
  884:             if (defined($hostname)) {
  885: 	        $spare_server = $protocol.'://'.$hostname;
  886:             }
  887:         }
  888:     }
  889:     return $spare_server;
  890: }
  891: 
  892: sub compare_server_load {
  893:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  894: 
  895:     if ($required) {
  896:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  897:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  898:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  899:         if (($major eq '' && $minor eq '') ||
  900:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  901:             return ($spare_server,$lowest_load);
  902:         }
  903:     }
  904: 
  905:     my $loadans     = &reply('load',    $try_server);
  906:     my $userloadans = &reply('userload',$try_server);
  907: 
  908:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  909: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  910:     }
  911: 
  912:     my $load;
  913:     if ($loadans =~ /\d/) {
  914: 	if ($userloadans =~ /\d/) {
  915: 	    #both are numbers, pick the bigger one
  916: 	    $load = ($loadans > $userloadans) ? $loadans 
  917: 		                              : $userloadans;
  918: 	} else {
  919: 	    $load = $loadans;
  920: 	}
  921:     } else {
  922: 	$load = $userloadans;
  923:     }
  924: 
  925:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  926: 	$spare_server = $try_server;
  927: 	$lowest_load  = $load;
  928:     }
  929:     return ($spare_server,$lowest_load);
  930: }
  931: 
  932: # --------------------------- ask offload servers if user already has a session
  933: sub find_existing_session {
  934:     my ($udom,$uname) = @_;
  935:     my $spareshash = &this_host_spares($udom);
  936:     if (ref($spareshash) eq 'HASH') {
  937:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  938:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  939:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  940:             }
  941:         }
  942:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  943:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  944:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  945:             }
  946:         }
  947:     }
  948:     return;
  949: }
  950: 
  951: # -------------------------------- ask if server already has a session for user
  952: sub has_user_session {
  953:     my ($lonid,$udom,$uname) = @_;
  954:     my $result = &reply(join(':','userhassession',
  955: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  956:     return 1 if ($result eq 'ok');
  957: 
  958:     return 0;
  959: }
  960: 
  961: # --------- determine least loaded server in a user's domain which allows login
  962: 
  963: sub choose_server {
  964:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
  965:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  966:     my %servers = &get_servers($udom);
  967:     my $lowest_load = 30000;
  968:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
  969:     if ($skiploadbal) {
  970:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
  971:         unless (defined($cached)) {
  972:             my $cachetime = 60*60*24;
  973:             my %domconfig =
  974:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
  975:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  976:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
  977:                                            $cachetime);
  978:             }
  979:         }
  980:     }
  981:     foreach my $lonhost (keys(%servers)) {
  982:         my $loginvia;
  983:         if ($skiploadbal) {
  984:             if (ref($balancers) eq 'HASH') {
  985:                 next if (exists($balancers->{$lonhost}));
  986:             }
  987:         }
  988:         if ($checkloginvia) {
  989:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  990:             if ($loginvia) {
  991:                 my ($server,$path) = split(/:/,$loginvia);
  992:                 ($login_host, $lowest_load) =
  993:                     &compare_server_load($server, $login_host, $lowest_load, $required);
  994:                 if ($login_host eq $server) {
  995:                     $portal_path = $path;
  996:                     $isredirect = 1;
  997:                 }
  998:             } else {
  999:                 ($login_host, $lowest_load) =
 1000:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1001:                 if ($login_host eq $lonhost) {
 1002:                     $portal_path = '';
 1003:                     $isredirect = ''; 
 1004:                 }
 1005:             }
 1006:         } else {
 1007:             ($login_host, $lowest_load) =
 1008:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1009:         }
 1010:     }
 1011:     if ($login_host ne '') {
 1012:         $hostname = &hostname($login_host);
 1013:     }
 1014:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1015: }
 1016: 
 1017: # --------------------------------------------- Try to change a user's password
 1018: 
 1019: sub changepass {
 1020:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1021:     $currentpass = &escape($currentpass);
 1022:     $newpass     = &escape($newpass);
 1023:     my $lonhost = $perlvar{'lonHostID'};
 1024:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1025: 		       $server);
 1026:     if (! $answer) {
 1027: 	&logthis("No reply on password change request to $server ".
 1028: 		 "by $uname in domain $udom.");
 1029:     } elsif ($answer =~ "^ok") {
 1030:         &logthis("$uname in $udom successfully changed their password ".
 1031: 		 "on $server.");
 1032:     } elsif ($answer =~ "^pwchange_failure") {
 1033: 	&logthis("$uname in $udom was unable to change their password ".
 1034: 		 "on $server.  The action was blocked by either lcpasswd ".
 1035: 		 "or pwchange");
 1036:     } elsif ($answer =~ "^non_authorized") {
 1037:         &logthis("$uname in $udom did not get their password correct when ".
 1038: 		 "attempting to change it on $server.");
 1039:     } elsif ($answer =~ "^auth_mode_error") {
 1040:         &logthis("$uname in $udom attempted to change their password despite ".
 1041: 		 "not being locally or internally authenticated on $server.");
 1042:     } elsif ($answer =~ "^unknown_user") {
 1043:         &logthis("$uname in $udom attempted to change their password ".
 1044: 		 "on $server but were unable to because $server is not ".
 1045: 		 "their home server.");
 1046:     } elsif ($answer =~ "^refused") {
 1047: 	&logthis("$server refused to change $uname in $udom password because ".
 1048: 		 "it was sent an unencrypted request to change the password.");
 1049:     } elsif ($answer =~ "invalid_client") {
 1050:         &logthis("$server refused to change $uname in $udom password because ".
 1051:                  "it was a reset by e-mail originating from an invalid server.");
 1052:     }
 1053:     return $answer;
 1054: }
 1055: 
 1056: # ----------------------- Try to determine user's current authentication scheme
 1057: 
 1058: sub queryauthenticate {
 1059:     my ($uname,$udom)=@_;
 1060:     my $uhome=&homeserver($uname,$udom);
 1061:     if (!$uhome) {
 1062: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1063: 	return 'no_host';
 1064:     }
 1065:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1066:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1067: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1068:     }
 1069:     return $answer;
 1070: }
 1071: 
 1072: # --------- Try to authenticate user from domain's lib servers (first this one)
 1073: 
 1074: sub authenticate {
 1075:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1076:     $upass=&escape($upass);
 1077:     $uname= &LONCAPA::clean_username($uname);
 1078:     my $uhome=&homeserver($uname,$udom,1);
 1079:     my $newhome;
 1080:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1081: # Maybe the machine was offline and only re-appeared again recently?
 1082:         &reconlonc();
 1083: # One more
 1084: 	$uhome=&homeserver($uname,$udom,1);
 1085:         if (($uhome eq 'no_host') && $checkdefauth) {
 1086:             if (defined(&domain($udom,'primary'))) {
 1087:                 $newhome=&domain($udom,'primary');
 1088:             }
 1089:             if ($newhome ne '') {
 1090:                 $uhome = $newhome;
 1091:             }
 1092:         }
 1093: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1094: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1095: 	    return 'no_host';
 1096:         }
 1097:     }
 1098:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1099:     if ($answer eq 'authorized') {
 1100:         if ($newhome) {
 1101:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1102:             return 'no_account_on_host'; 
 1103:         } else {
 1104:             &logthis("User $uname at $udom authorized by $uhome");
 1105:             return $uhome;
 1106:         }
 1107:     }
 1108:     if ($answer eq 'non_authorized') {
 1109: 	&logthis("User $uname at $udom rejected by $uhome");
 1110: 	return 'no_host'; 
 1111:     }
 1112:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1113:     return 'no_host';
 1114: }
 1115: 
 1116: sub can_host_session {
 1117:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1118:     my $canhost = 1;
 1119:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1120:     if (ref($remotesessions) eq 'HASH') {
 1121:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1122:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1123:                 $canhost = 0;
 1124:             } else {
 1125:                 $canhost = 1;
 1126:             }
 1127:         }
 1128:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1129:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1130:                 $canhost = 1;
 1131:             } else {
 1132:                 $canhost = 0;
 1133:             }
 1134:         }
 1135:         if ($canhost) {
 1136:             if ($remotesessions->{'version'} ne '') {
 1137:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1138:                 if ($reqmajor ne '' && $reqminor ne '') {
 1139:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1140:                         my $major = $1;
 1141:                         my $minor = $2;
 1142:                         if (($major < $reqmajor ) ||
 1143:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1144:                             $canhost = 0;
 1145:                         }
 1146:                     } else {
 1147:                         $canhost = 0;
 1148:                     }
 1149:                 }
 1150:             }
 1151:         }
 1152:     }
 1153:     if ($canhost) {
 1154:         if (ref($hostedsessions) eq 'HASH') {
 1155:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1156:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1157:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1158:                 if (($uint_dom ne '') && 
 1159:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1160:                     $canhost = 0;
 1161:                 } else {
 1162:                     $canhost = 1;
 1163:                 }
 1164:             }
 1165:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1166:                 if (($uint_dom ne '') && 
 1167:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1168:                     $canhost = 1;
 1169:                 } else {
 1170:                     $canhost = 0;
 1171:                 }
 1172:             }
 1173:         }
 1174:     }
 1175:     return $canhost;
 1176: }
 1177: 
 1178: sub spare_can_host {
 1179:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1180:     my $canhost=1;
 1181:     my $try_server_hostname = &hostname($try_server);
 1182:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1183:     my $serverhomedom = &host_domain($serverhomeID);
 1184:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1185:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1186:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1187:             $canhost = 0;
 1188:         }
 1189:     }
 1190:     if (($canhost) && ($uint_dom)) {
 1191:         my @intdoms;
 1192:         my $internet_names = &get_internet_names($try_server);
 1193:         if (ref($internet_names) eq 'ARRAY') {
 1194:             @intdoms = @{$internet_names};
 1195:         }
 1196:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1197:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1198:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1199:                                          $remotesessions,
 1200:                                          $defdomdefaults{'hostedsessions'});
 1201:         }
 1202:     }
 1203:     return $canhost;
 1204: }
 1205: 
 1206: sub this_host_spares {
 1207:     my ($dom) = @_;
 1208:     my ($dom_in_use,$lonhost_in_use,$result);
 1209:     my @hosts = &current_machine_ids();
 1210:     foreach my $lonhost (@hosts) {
 1211:         if (&host_domain($lonhost) eq $dom) {
 1212:             $dom_in_use = $dom;
 1213:             $lonhost_in_use = $lonhost;
 1214:             last;
 1215:         }
 1216:     }
 1217:     if ($dom_in_use ne '') {
 1218:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1219:     }
 1220:     if (ref($result) ne 'HASH') {
 1221:         $lonhost_in_use = $perlvar{'lonHostID'};
 1222:         $dom_in_use = &host_domain($lonhost_in_use);
 1223:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1224:         if (ref($result) ne 'HASH') {
 1225:             $result = \%spareid;
 1226:         }
 1227:     }
 1228:     return $result;
 1229: }
 1230: 
 1231: sub spares_for_offload  {
 1232:     my ($dom_in_use,$lonhost_in_use) = @_;
 1233:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1234:     if (defined($cached)) {
 1235:         return $result;
 1236:     } else {
 1237:         my $cachetime = 60*60*24;
 1238:         my %domconfig =
 1239:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1240:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1241:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1242:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1243:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1244:                 }
 1245:             }
 1246:         }
 1247:     }
 1248:     return;
 1249: }
 1250: 
 1251: sub get_lonbalancer_config {
 1252:     my ($servers) = @_;
 1253:     my ($currbalancer,$currtargets);
 1254:     if (ref($servers) eq 'HASH') {
 1255:         foreach my $server (keys(%{$servers})) {
 1256:             my %what = (
 1257:                          spareid => 1,
 1258:                          perlvar => 1,
 1259:                        );
 1260:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1261:             if ($result eq 'ok') {
 1262:                 if (ref($returnhash) eq 'HASH') {
 1263:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1264:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1265:                             $currbalancer = $server;
 1266:                             $currtargets = {};
 1267:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1268:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1269:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1270:                                 }
 1271:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1272:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1273:                                 }
 1274:                             }
 1275:                             last;
 1276:                         }
 1277:                     }
 1278:                 }
 1279:             }
 1280:         }
 1281:     }
 1282:     return ($currbalancer,$currtargets);
 1283: }
 1284: 
 1285: sub check_loadbalancing {
 1286:     my ($uname,$udom,$caller) = @_;
 1287:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1288:         $rule_in_effect,$offloadto,$otherserver);
 1289:     my $lonhost = $perlvar{'lonHostID'};
 1290:     my @hosts = &current_machine_ids();
 1291:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1292:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1293:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1294:     my $serverhomedom = &host_domain($lonhost);
 1295:     my $domneedscache; 
 1296:     my $cachetime = 60*60*24;
 1297: 
 1298:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1299:         $dom_in_use = $udom;
 1300:         $homeintdom = 1;
 1301:     } else {
 1302:         $dom_in_use = $serverhomedom;
 1303:     }
 1304:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1305:     unless (defined($cached)) {
 1306:         my %domconfig =
 1307:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1308:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1309:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1310:         } else {
 1311:             $domneedscache = $dom_in_use;
 1312:         }
 1313:     }
 1314:     if (ref($result) eq 'HASH') {
 1315:         ($is_balancer,$currtargets,$currrules) =
 1316:             &check_balancer_result($result,@hosts);
 1317:         if ($is_balancer) {
 1318:             if (ref($currrules) eq 'HASH') {
 1319:                 if ($homeintdom) {
 1320:                     if ($uname ne '') {
 1321:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1322:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1323:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1324:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1325:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1326:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1327:                             }
 1328:                         }
 1329:                         if ($rule_in_effect eq '') {
 1330:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1331:                             if ($userenv{'inststatus'} ne '') {
 1332:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1333:                                 my ($othertitle,$usertypes,$types) =
 1334:                                     &Apache::loncommon::sorted_inst_types($udom);
 1335:                                 if (ref($types) eq 'ARRAY') {
 1336:                                     foreach my $type (@{$types}) {
 1337:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1338:                                             if (exists($currrules->{$type})) {
 1339:                                                 $rule_in_effect = $currrules->{$type};
 1340:                                             }
 1341:                                         }
 1342:                                     }
 1343:                                 }
 1344:                             } else {
 1345:                                 if (exists($currrules->{'default'})) {
 1346:                                     $rule_in_effect = $currrules->{'default'};
 1347:                                 }
 1348:                             }
 1349:                         }
 1350:                     } else {
 1351:                         if (exists($currrules->{'default'})) {
 1352:                             $rule_in_effect = $currrules->{'default'};
 1353:                         }
 1354:                     }
 1355:                 } else {
 1356:                     if ($currrules->{'_LC_external'} ne '') {
 1357:                         $rule_in_effect = $currrules->{'_LC_external'};
 1358:                     }
 1359:                 }
 1360:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1361:                                                        $uname,$udom);
 1362:             }
 1363:         }
 1364:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1365:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1366:         unless (defined($cached)) {
 1367:             my %domconfig =
 1368:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1369:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1370:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1371:             } else {
 1372:                 $domneedscache = $serverhomedom;
 1373:             }
 1374:         }
 1375:         if (ref($result) eq 'HASH') {
 1376:             ($is_balancer,$currtargets,$currrules) =
 1377:                 &check_balancer_result($result,@hosts);
 1378:             if ($is_balancer) {
 1379:                 if (ref($currrules) eq 'HASH') {
 1380:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1381:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1382:                     }
 1383:                 }
 1384:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1385:                                                        $uname,$udom);
 1386:             }
 1387:         } else {
 1388:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1389:                 $is_balancer = 1;
 1390:                 $offloadto = &this_host_spares($dom_in_use);
 1391:             }
 1392:             unless (defined($cached)) {
 1393:                 $domneedscache = $serverhomedom;
 1394:             }
 1395:         }
 1396:     } else {
 1397:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1398:             $is_balancer = 1;
 1399:             $offloadto = &this_host_spares($dom_in_use);
 1400:         }
 1401:         unless (defined($cached)) {
 1402:             $domneedscache = $serverhomedom;
 1403:         }
 1404:     }
 1405:     if ($domneedscache) {
 1406:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1407:     }
 1408:     if ($is_balancer) {
 1409:         my $lowest_load = 30000;
 1410:         if (ref($offloadto) eq 'HASH') {
 1411:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1412:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1413:                     ($otherserver,$lowest_load) =
 1414:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1415:                 }
 1416:             }
 1417:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1418: 
 1419:             if (!$found_server) {
 1420:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1421:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1422:                         ($otherserver,$lowest_load) =
 1423:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1424:                     }
 1425:                 }
 1426:             }
 1427:         } elsif (ref($offloadto) eq 'ARRAY') {
 1428:             if (@{$offloadto} == 1) {
 1429:                 $otherserver = $offloadto->[0];
 1430:             } elsif (@{$offloadto} > 1) {
 1431:                 foreach my $try_server (@{$offloadto}) {
 1432:                     ($otherserver,$lowest_load) =
 1433:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1434:                 }
 1435:             }
 1436:         }
 1437:         unless ($caller eq 'login') {
 1438:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1439:                 $is_balancer = 0;
 1440:                 if ($uname ne '' && $udom ne '') {
 1441:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1442: 
 1443:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1444:                                  'user.loadbalcheck.time' => time});
 1445:                     }
 1446:                 }
 1447:             }
 1448:         }
 1449:     }
 1450:     return ($is_balancer,$otherserver);
 1451: }
 1452: 
 1453: sub check_balancer_result {
 1454:     my ($result,@hosts) = @_;
 1455:     my ($is_balancer,$currtargets,$currrules);
 1456:     if (ref($result) eq 'HASH') {
 1457:         if ($result->{'lonhost'} ne '') {
 1458:             my $currbalancer = $result->{'lonhost'};
 1459:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1460:                 $is_balancer = 1;
 1461:                 $currtargets = $result->{'targets'};
 1462:                 $currrules = $result->{'rules'};
 1463:             }
 1464:         } else {
 1465:             foreach my $key (keys(%{$result})) {
 1466:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1467:                     (ref($result->{$key}) eq 'HASH')) {
 1468:                     $is_balancer = 1;
 1469:                     $currrules = $result->{$key}{'rules'};
 1470:                     $currtargets = $result->{$key}{'targets'};
 1471:                     last;
 1472:                 }
 1473:             }
 1474:         }
 1475:     }
 1476:     return ($is_balancer,$currtargets,$currrules);
 1477: }
 1478: 
 1479: sub get_loadbalancer_targets {
 1480:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1481:     my $offloadto;
 1482:     if ($rule_in_effect eq 'none') {
 1483:         return [$perlvar{'lonHostID'}];
 1484:     } elsif ($rule_in_effect eq '') {
 1485:         $offloadto = $currtargets;
 1486:     } else {
 1487:         if ($rule_in_effect eq 'homeserver') {
 1488:             my $homeserver = &homeserver($uname,$udom);
 1489:             if ($homeserver ne 'no_host') {
 1490:                 $offloadto = [$homeserver];
 1491:             }
 1492:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1493:             my %domconfig =
 1494:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1495:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1496:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1497:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1498:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1499:                     }
 1500:                 }
 1501:             } else {
 1502:                 my %servers = &internet_dom_servers($udom);
 1503:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1504:                 if (&hostname($remotebalancer) ne '') {
 1505:                     $offloadto = [$remotebalancer];
 1506:                 }
 1507:             }
 1508:         } elsif (&hostname($rule_in_effect) ne '') {
 1509:             $offloadto = [$rule_in_effect];
 1510:         }
 1511:     }
 1512:     return $offloadto;
 1513: }
 1514: 
 1515: sub internet_dom_servers {
 1516:     my ($dom) = @_;
 1517:     my (%uniqservers,%servers);
 1518:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1519:     my @machinedoms = &machine_domains($primaryserver);
 1520:     foreach my $mdom (@machinedoms) {
 1521:         my %currservers = %servers;
 1522:         my %server = &get_servers($mdom);
 1523:         %servers = (%currservers,%server);
 1524:     }
 1525:     my %by_hostname;
 1526:     foreach my $id (keys(%servers)) {
 1527:         push(@{$by_hostname{$servers{$id}}},$id);
 1528:     }
 1529:     foreach my $hostname (sort(keys(%by_hostname))) {
 1530:         if (@{$by_hostname{$hostname}} > 1) {
 1531:             my $match = 0;
 1532:             foreach my $id (@{$by_hostname{$hostname}}) {
 1533:                 if (&host_domain($id) eq $dom) {
 1534:                     $uniqservers{$id} = $hostname;
 1535:                     $match = 1;
 1536:                 }
 1537:             }
 1538:             unless ($match) {
 1539:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1540:             }
 1541:         } else {
 1542:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1543:         }
 1544:     }
 1545:     return %uniqservers;
 1546: }
 1547: 
 1548: # ---------------------- Find the homebase for a user from domain's lib servers
 1549: 
 1550: my %homecache;
 1551: sub homeserver {
 1552:     my ($uname,$udom,$ignoreBadCache)=@_;
 1553:     my $index="$uname:$udom";
 1554: 
 1555:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1556: 
 1557:     my %servers = &get_servers($udom,'library');
 1558:     foreach my $tryserver (keys(%servers)) {
 1559:         next if ($ignoreBadCache ne 'true' && 
 1560: 		 exists($badServerCache{$tryserver}));
 1561: 
 1562: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1563: 	if ($answer eq 'found') {
 1564: 	    delete($badServerCache{$tryserver}); 
 1565: 	    return $homecache{$index}=$tryserver;
 1566: 	} elsif ($answer eq 'no_host') {
 1567: 	    $badServerCache{$tryserver}=1;
 1568: 	}
 1569:     }    
 1570:     return 'no_host';
 1571: }
 1572: 
 1573: # ------------------------------------- Find the usernames behind a list of IDs
 1574: 
 1575: sub idget {
 1576:     my ($udom,@ids)=@_;
 1577:     my %returnhash=();
 1578:     
 1579:     my %servers = &get_servers($udom,'library');
 1580:     foreach my $tryserver (keys(%servers)) {
 1581: 	my $idlist=join('&', map { &escape($_); } @ids);
 1582: 	$idlist=~tr/A-Z/a-z/; 
 1583: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1584: 	my @answer=();
 1585: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1586: 	    @answer=split(/\&/,$reply);
 1587: 	}                    ;
 1588: 	my $i;
 1589: 	for ($i=0;$i<=$#ids;$i++) {
 1590: 	    if ($answer[$i]) {
 1591: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1592: 	    } 
 1593: 	}
 1594:     } 
 1595:     return %returnhash;
 1596: }
 1597: 
 1598: # ------------------------------------- Find the IDs behind a list of usernames
 1599: 
 1600: sub idrget {
 1601:     my ($udom,@unames)=@_;
 1602:     my %returnhash=();
 1603:     foreach my $uname (@unames) {
 1604:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1605:     }
 1606:     return %returnhash;
 1607: }
 1608: 
 1609: # ------------------------------- Store away a list of names and associated IDs
 1610: 
 1611: sub idput {
 1612:     my ($udom,%ids)=@_;
 1613:     my %servers=();
 1614:     foreach my $uname (keys(%ids)) {
 1615: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1616:         my $uhom=&homeserver($uname,$udom);
 1617:         if ($uhom ne 'no_host') {
 1618:             my $id=&escape($ids{$uname});
 1619:             $id=~tr/A-Z/a-z/;
 1620:             my $esc_unam=&escape($uname);
 1621: 	    if ($servers{$uhom}) {
 1622: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1623:             } else {
 1624:                 $servers{$uhom}=$id.'='.$esc_unam;
 1625:             }
 1626:         }
 1627:     }
 1628:     foreach my $server (keys(%servers)) {
 1629:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1630:     }
 1631: }
 1632: 
 1633: # ---------------------------------------- Delete unwanted IDs from ids.db file
 1634: 
 1635: sub iddel {
 1636:     my ($udom,$idshashref,$uhome)=@_;
 1637:     my %result=();
 1638:     unless (ref($idshashref) eq 'HASH') {
 1639:         return %result;
 1640:     }
 1641:     my %servers=();
 1642:     while (my ($id,$uname) = each(%{$idshashref})) {
 1643:         my $uhom;
 1644:         if ($uhome) {
 1645:             $uhom = $uhome;
 1646:         } else {
 1647:             $uhom=&homeserver($uname,$udom);
 1648:         }
 1649:         if ($uhom ne 'no_host') {
 1650:             if ($servers{$uhom}) {
 1651:                 $servers{$uhom}.='&'.&escape($id);
 1652:             } else {
 1653:                 $servers{$uhom}=&escape($id);
 1654:             }
 1655:         }
 1656:     }
 1657:     foreach my $server (keys(%servers)) {
 1658:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1659:     }
 1660:     return %result;
 1661: }
 1662: 
 1663: # ------------------------------dump from db file owned by domainconfig user
 1664: sub dump_dom {
 1665:     my ($namespace, $udom, $regexp) = @_;
 1666: 
 1667:     $udom ||= $env{'user.domain'};
 1668: 
 1669:     return () unless $udom;
 1670: 
 1671:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1672: }
 1673: 
 1674: # ------------------------------------------ get items from domain db files   
 1675: 
 1676: sub get_dom {
 1677:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1678:     return if ($udom eq 'public');
 1679:     my $items='';
 1680:     foreach my $item (@$storearr) {
 1681:         $items.=&escape($item).'&';
 1682:     }
 1683:     $items=~s/\&$//;
 1684:     if (!$udom) {
 1685:         $udom=$env{'user.domain'};
 1686:         return if ($udom eq 'public');
 1687:         if (defined(&domain($udom,'primary'))) {
 1688:             $uhome=&domain($udom,'primary');
 1689:         } else {
 1690:             undef($uhome);
 1691:         }
 1692:     } else {
 1693:         if (!$uhome) {
 1694:             if (defined(&domain($udom,'primary'))) {
 1695:                 $uhome=&domain($udom,'primary');
 1696:             }
 1697:         }
 1698:     }
 1699:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1700:         my $rep;
 1701:         if ($namespace =~ /^enc/) {
 1702:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 1703:         } else {
 1704:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1705:         }
 1706:         my %returnhash;
 1707:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1708:             return %returnhash;
 1709:         }
 1710:         my @pairs=split(/\&/,$rep);
 1711:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1712:             return @pairs;
 1713:         }
 1714:         my $i=0;
 1715:         foreach my $item (@$storearr) {
 1716:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1717:             $i++;
 1718:         }
 1719:         return %returnhash;
 1720:     } else {
 1721:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1722:     }
 1723: }
 1724: 
 1725: # -------------------------------------------- put items in domain db files 
 1726: 
 1727: sub put_dom {
 1728:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1729:     if (!$udom) {
 1730:         $udom=$env{'user.domain'};
 1731:         if (defined(&domain($udom,'primary'))) {
 1732:             $uhome=&domain($udom,'primary');
 1733:         } else {
 1734:             undef($uhome);
 1735:         }
 1736:     } else {
 1737:         if (!$uhome) {
 1738:             if (defined(&domain($udom,'primary'))) {
 1739:                 $uhome=&domain($udom,'primary');
 1740:             }
 1741:         }
 1742:     } 
 1743:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1744:         my $items='';
 1745:         foreach my $item (keys(%$storehash)) {
 1746:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1747:         }
 1748:         $items=~s/\&$//;
 1749:         if ($namespace =~ /^enc/) {
 1750:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 1751:         } else {
 1752:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 1753:         }
 1754:     } else {
 1755:         &logthis("put_dom failed - no homeserver and/or domain");
 1756:     }
 1757: }
 1758: 
 1759: # --------------------- newput for items in db file owned by domainconfig user
 1760: sub newput_dom {
 1761:     my ($namespace,$storehash,$udom) = @_;
 1762:     my $result;
 1763:     if (!$udom) {
 1764:         $udom=$env{'user.domain'};
 1765:     }
 1766:     if ($udom) {
 1767:         my $uname = &get_domainconfiguser($udom);
 1768:         $result = &newput($namespace,$storehash,$udom,$uname);
 1769:     }
 1770:     return $result;
 1771: }
 1772: 
 1773: # --------------------- delete for items in db file owned by domainconfig user
 1774: sub del_dom {
 1775:     my ($namespace,$storearr,$udom)=@_;
 1776:     if (ref($storearr) eq 'ARRAY') {
 1777:         if (!$udom) {
 1778:             $udom=$env{'user.domain'};
 1779:         }
 1780:         if ($udom) {
 1781:             my $uname = &get_domainconfiguser($udom); 
 1782:             return &del($namespace,$storearr,$udom,$uname);
 1783:         }
 1784:     }
 1785: }
 1786: 
 1787: # ----------------------------------construct domainconfig user for a domain 
 1788: sub get_domainconfiguser {
 1789:     my ($udom) = @_;
 1790:     return $udom.'-domainconfig';
 1791: }
 1792: 
 1793: sub retrieve_inst_usertypes {
 1794:     my ($udom) = @_;
 1795:     my (%returnhash,@order);
 1796:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1797:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1798:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1799:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1800:     } else {
 1801:         if (defined(&domain($udom,'primary'))) {
 1802:             my $uhome=&domain($udom,'primary');
 1803:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1804:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1805:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 1806:                 return (\%returnhash,\@order);
 1807:             }
 1808:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1809:             my @pairs=split(/\&/,$hashitems);
 1810:             foreach my $item (@pairs) {
 1811:                 my ($key,$value)=split(/=/,$item,2);
 1812:                 $key = &unescape($key);
 1813:                 next if ($key =~ /^error: 2 /);
 1814:                 $returnhash{$key}=&thaw_unescape($value);
 1815:             }
 1816:             my @esc_order = split(/\&/,$orderitems);
 1817:             foreach my $item (@esc_order) {
 1818:                 push(@order,&unescape($item));
 1819:             }
 1820:         } else {
 1821:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 1822:         }
 1823:         return (\%returnhash,\@order);
 1824:     }
 1825: }
 1826: 
 1827: sub is_domainimage {
 1828:     my ($url) = @_;
 1829:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 1830:         if (&domain($1) ne '') {
 1831:             return '1';
 1832:         }
 1833:     }
 1834:     return;
 1835: }
 1836: 
 1837: sub inst_directory_query {
 1838:     my ($srch) = @_;
 1839:     my $udom = $srch->{'srchdomain'};
 1840:     my %results;
 1841:     my $homeserver = &domain($udom,'primary');
 1842:     my $outcome;
 1843:     if ($homeserver ne '') {
 1844:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 1845:             if ($srch->{'srchby'} eq 'email') {
 1846:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 1847:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.([\w.\-]+)\'?$/);
 1848:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 1849:                     (($major == 2) && ($minor < 11)) || 
 1850:                     (($major == 2) && ($minor == 11) && ($subver !~ /^2\.B/))) {
 1851:                     return;
 1852:                 }
 1853:             }
 1854:         }
 1855: 	my $queryid=&reply("querysend:instdirsearch:".
 1856: 			   &escape($srch->{'srchby'}).':'.
 1857: 			   &escape($srch->{'srchterm'}).':'.
 1858: 			   &escape($srch->{'srchtype'}),$homeserver);
 1859: 	my $host=&hostname($homeserver);
 1860: 	if ($queryid !~/^\Q$host\E\_/) {
 1861: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 1862: 	    return;
 1863: 	}
 1864: 	my $response = &get_query_reply($queryid);
 1865: 	my $maxtries = 5;
 1866: 	my $tries = 1;
 1867: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1868: 	    $response = &get_query_reply($queryid);
 1869: 	    $tries ++;
 1870: 	}
 1871: 
 1872:         if (!&error($response) && $response ne 'refused') {
 1873:             if ($response eq 'unavailable') {
 1874:                 $outcome = $response;
 1875:             } else {
 1876:                 $outcome = 'ok';
 1877:                 my @matches = split(/\n/,$response);
 1878:                 foreach my $match (@matches) {
 1879:                     my ($key,$value) = split(/=/,$match);
 1880:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1881:                 }
 1882:             }
 1883:         }
 1884:     }
 1885:     return ($outcome,%results);
 1886: }
 1887: 
 1888: sub usersearch {
 1889:     my ($srch) = @_;
 1890:     my $dom = $srch->{'srchdomain'};
 1891:     my %results;
 1892:     my %libserv = &all_library();
 1893:     my $query = 'usersearch';
 1894:     foreach my $tryserver (keys(%libserv)) {
 1895:         if (&host_domain($tryserver) eq $dom) {
 1896:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 1897:                 if ($srch->{'srchby'} eq 'email') {
 1898:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 1899:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.([\w.\-]+)\'?$/);
 1900:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 1901:                              (($major == 2) && ($minor < 11)) || 
 1902:                              (($major == 2) && ($minor == 11) && ($subver !~ /^2\.B/)));
 1903:                 }
 1904:             }
 1905:             my $host=&hostname($tryserver);
 1906:             my $queryid=
 1907:                 &reply("querysend:".&escape($query).':'.
 1908:                        &escape($srch->{'srchby'}).':'.
 1909:                        &escape($srch->{'srchtype'}).':'.
 1910:                        &escape($srch->{'srchterm'}),$tryserver);
 1911:             if ($queryid !~/^\Q$host\E\_/) {
 1912:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1913:                 next;
 1914:             }
 1915:             my $reply = &get_query_reply($queryid);
 1916:             my $maxtries = 1;
 1917:             my $tries = 1;
 1918:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1919:                 $reply = &get_query_reply($queryid);
 1920:                 $tries ++;
 1921:             }
 1922:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1923:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1924:             } else {
 1925:                 my @matches;
 1926:                 if ($reply =~ /\n/) {
 1927:                     @matches = split(/\n/,$reply);
 1928:                 } else {
 1929:                     @matches = split(/\&/,$reply);
 1930:                 }
 1931:                 foreach my $match (@matches) {
 1932:                     my ($uname,$udom,%userhash);
 1933:                     foreach my $entry (split(/:/,$match)) {
 1934:                         my ($key,$value) =
 1935:                             map {&unescape($_);} split(/=/,$entry);
 1936:                         $userhash{$key} = $value;
 1937:                         if ($key eq 'username') {
 1938:                             $uname = $value;
 1939:                         } elsif ($key eq 'domain') {
 1940:                             $udom = $value;
 1941:                         }
 1942:                     }
 1943:                     $results{$uname.':'.$udom} = \%userhash;
 1944:                 }
 1945:             }
 1946:         }
 1947:     }
 1948:     return %results;
 1949: }
 1950: 
 1951: sub get_instuser {
 1952:     my ($udom,$uname,$id) = @_;
 1953:     my $homeserver = &domain($udom,'primary');
 1954:     my ($outcome,%results);
 1955:     if ($homeserver ne '') {
 1956:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1957:                            &escape($id).':'.&escape($udom),$homeserver);
 1958:         my $host=&hostname($homeserver);
 1959:         if ($queryid !~/^\Q$host\E\_/) {
 1960:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1961:             return;
 1962:         }
 1963:         my $response = &get_query_reply($queryid);
 1964:         my $maxtries = 5;
 1965:         my $tries = 1;
 1966:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1967:             $response = &get_query_reply($queryid);
 1968:             $tries ++;
 1969:         }
 1970:         if (!&error($response) && $response ne 'refused') {
 1971:             if ($response eq 'unavailable') {
 1972:                 $outcome = $response;
 1973:             } else {
 1974:                 $outcome = 'ok';
 1975:                 my @matches = split(/\n/,$response);
 1976:                 foreach my $match (@matches) {
 1977:                     my ($key,$value) = split(/=/,$match);
 1978:                     $results{&unescape($key)} = &thaw_unescape($value);
 1979:                 }
 1980:             }
 1981:         }
 1982:     }
 1983:     my %userinfo;
 1984:     if (ref($results{$uname}) eq 'HASH') {
 1985:         %userinfo = %{$results{$uname}};
 1986:     } 
 1987:     return ($outcome,%userinfo);
 1988: }
 1989: 
 1990: sub get_multiple_instusers {
 1991:     my ($udom,$users,$caller) = @_;
 1992:     my ($outcome,$results);
 1993:     if (ref($users) eq 'HASH') {
 1994:         my $count = keys(%{$users});
 1995:         my $requested = &freeze_escape($users);
 1996:         my $homeserver = &domain($udom,'primary');
 1997:         if ($homeserver ne '') {
 1998:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 1999:             my $host=&hostname($homeserver);
 2000:             if ($queryid !~/^\Q$host\E\_/) {
 2001:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2002:                          ' for host: '.$homeserver.'in domain '.$udom);
 2003:                 return ($outcome,$results);
 2004:             }
 2005:             my $response = &get_query_reply($queryid);
 2006:             my $maxtries = 5;
 2007:             if ($count > 100) {
 2008:                 $maxtries = 1+int($count/20);
 2009:             }
 2010:             my $tries = 1;
 2011:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2012:                 $response = &get_query_reply($queryid);
 2013:                 $tries ++;
 2014:             }
 2015:             if ($response eq '') {
 2016:                 $results = {};
 2017:                 foreach my $key (keys(%{$users})) {
 2018:                     my ($uname,$id);
 2019:                     if ($caller eq 'id') {
 2020:                         $id = $key;
 2021:                     } else {
 2022:                         $uname = $key;
 2023:                     }
 2024:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2025:                     $outcome = $resp;
 2026:                     if ($resp eq 'ok') {
 2027:                         %{$results} = (%{$results}, %info);
 2028:                     } else {
 2029:                         last;
 2030:                     }
 2031:                 }
 2032:             } elsif(!&error($response) && ($response ne 'refused')) {
 2033:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2034:                     $outcome = $response;
 2035:                 } else {
 2036:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2037:                     if ($outcome eq 'ok') {
 2038:                         $results = &thaw_unescape($userdata);
 2039:                     }
 2040:                 }
 2041:             }
 2042:         }
 2043:     }
 2044:     return ($outcome,$results);
 2045: }
 2046: 
 2047: sub inst_rulecheck {
 2048:     my ($udom,$uname,$id,$item,$rules) = @_;
 2049:     my %returnhash;
 2050:     if ($udom ne '') {
 2051:         if (ref($rules) eq 'ARRAY') {
 2052:             @{$rules} = map {&escape($_);} (@{$rules});
 2053:             my $rulestr = join(':',@{$rules});
 2054:             my $homeserver=&domain($udom,'primary');
 2055:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2056:                 my $response;
 2057:                 if ($item eq 'username') {                
 2058:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2059:                                               ':'.&escape($uname).':'.$rulestr,
 2060:                                               $homeserver));
 2061:                 } elsif ($item eq 'id') {
 2062:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2063:                                               ':'.&escape($id).':'.$rulestr,
 2064:                                               $homeserver));
 2065:                 } elsif ($item eq 'selfcreate') {
 2066:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2067:                                                &escape($udom).':'.&escape($uname).
 2068:                                               ':'.$rulestr,$homeserver));
 2069:                 }
 2070:                 if ($response ne 'refused') {
 2071:                     my @pairs=split(/\&/,$response);
 2072:                     foreach my $item (@pairs) {
 2073:                         my ($key,$value)=split(/=/,$item,2);
 2074:                         $key = &unescape($key);
 2075:                         next if ($key =~ /^error: 2 /);
 2076:                         $returnhash{$key}=&thaw_unescape($value);
 2077:                     }
 2078:                 }
 2079:             }
 2080:         }
 2081:     }
 2082:     return %returnhash;
 2083: }
 2084: 
 2085: sub inst_userrules {
 2086:     my ($udom,$check) = @_;
 2087:     my (%ruleshash,@ruleorder);
 2088:     if ($udom ne '') {
 2089:         my $homeserver=&domain($udom,'primary');
 2090:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2091:             my $response;
 2092:             if ($check eq 'id') {
 2093:                 $response=&reply('instidrules:'.&escape($udom),
 2094:                                  $homeserver);
 2095:             } elsif ($check eq 'email') {
 2096:                 $response=&reply('instemailrules:'.&escape($udom),
 2097:                                  $homeserver);
 2098:             } else {
 2099:                 $response=&reply('instuserrules:'.&escape($udom),
 2100:                                  $homeserver);
 2101:             }
 2102:             if (($response ne 'refused') && ($response ne 'error') && 
 2103:                 ($response ne 'unknown_cmd') && 
 2104:                 ($response ne 'no_such_host')) {
 2105:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2106:                 my @pairs=split(/\&/,$hashitems);
 2107:                 foreach my $item (@pairs) {
 2108:                     my ($key,$value)=split(/=/,$item,2);
 2109:                     $key = &unescape($key);
 2110:                     next if ($key =~ /^error: 2 /);
 2111:                     $ruleshash{$key}=&thaw_unescape($value);
 2112:                 }
 2113:                 my @esc_order = split(/\&/,$orderitems);
 2114:                 foreach my $item (@esc_order) {
 2115:                     push(@ruleorder,&unescape($item));
 2116:                 }
 2117:             }
 2118:         }
 2119:     }
 2120:     return (\%ruleshash,\@ruleorder);
 2121: }
 2122: 
 2123: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2124: 
 2125: sub get_domain_defaults {
 2126:     my ($domain,$ignore_cache) = @_;
 2127:     return if (($domain eq '') || ($domain eq 'public'));
 2128:     my $cachetime = 60*60*24;
 2129:     unless ($ignore_cache) {
 2130:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2131:         if (defined($cached)) {
 2132:             if (ref($result) eq 'HASH') {
 2133:                 return %{$result};
 2134:             }
 2135:         }
 2136:     }
 2137:     my %domdefaults;
 2138:     my %domconfig =
 2139:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2140:                                   'requestcourses','inststatus',
 2141:                                   'coursedefaults','usersessions',
 2142:                                   'requestauthor','selfenrollment',
 2143:                                   'coursecategories','autoenroll',
 2144:                                   'helpsettings'],$domain);
 2145:     my @coursetypes = ('official','unofficial','community','textbook');
 2146:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2147:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2148:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2149:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2150:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2151:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2152:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2153:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2154:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2155:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2156:     } else {
 2157:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2158:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2159:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2160:     }
 2161:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2162:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2163:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2164:         } else {
 2165:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2166:         }
 2167:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2168:         foreach my $item (@usertools) {
 2169:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2170:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2171:             }
 2172:         }
 2173:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2174:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2175:         }
 2176:     }
 2177:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2178:         foreach my $item ('official','unofficial','community','textbook') {
 2179:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2180:         }
 2181:     }
 2182:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2183:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2184:     }
 2185:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2186:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2187:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2188:         }
 2189:     }
 2190:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2191:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2192:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2193:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2194:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2195:         }
 2196:         foreach my $type (@coursetypes) {
 2197:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2198:                 unless ($type eq 'community') {
 2199:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2200:                 }
 2201:             }
 2202:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2203:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2204:             }
 2205:             if ($domdefaults{'postsubmit'} eq 'on') {
 2206:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2207:                     $domdefaults{$type.'postsubtimeout'} =
 2208:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
 2209:                 }
 2210:             }
 2211:         }
 2212:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2213:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2214:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2215:                 if (@clonecodes) {
 2216:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2217:                 }
 2218:             }
 2219:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2220:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2221:         }
 2222:     }
 2223:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2224:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2225:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2226:         }
 2227:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2228:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2229:         }
 2230:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2231:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2232:         }
 2233:     }
 2234:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2235:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2236:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2237:                             'approval','limit');
 2238:             foreach my $type (@coursetypes) {
 2239:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2240:                     my @mgrdc = ();
 2241:                     foreach my $item (@settings) {
 2242:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2243:                             push(@mgrdc,$item);
 2244:                         }
 2245:                     }
 2246:                     if (@mgrdc) {
 2247:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2248:                     }
 2249:                 }
 2250:             }
 2251:         }
 2252:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2253:             foreach my $type (@coursetypes) {
 2254:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2255:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2256:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2257:                     }
 2258:                 }
 2259:             }
 2260:         }
 2261:     }
 2262:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2263:         $domdefaults{'catauth'} = 'std';
 2264:         $domdefaults{'catunauth'} = 'std';
 2265:         if ($domconfig{'coursecategories'}{'auth'}) {
 2266:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2267:         }
 2268:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2269:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2270:         }
 2271:     }
 2272:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2273:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2274:     }
 2275:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2276:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2277:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2278:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2279:         }
 2280:     }
 2281:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2282:     return %domdefaults;
 2283: }
 2284: 
 2285: sub course_portal_url {
 2286:     my ($cnum,$cdom) = @_;
 2287:     my $chome = &homeserver($cnum,$cdom);
 2288:     my $hostname = &hostname($chome);
 2289:     my $protocol = $protocol{$chome};
 2290:     $protocol = 'http' if ($protocol ne 'https');
 2291:     my %domdefaults = &get_domain_defaults($cdom);
 2292:     my $firsturl;
 2293:     if ($domdefaults{'portal_def'}) {
 2294:         $firsturl = $domdefaults{'portal_def'};
 2295:     } else {
 2296:         $firsturl = $protocol.'://'.$hostname;
 2297:     }
 2298:     return $firsturl;
 2299: }
 2300: 
 2301: # --------------------------------------------------- Assign a key to a student
 2302: 
 2303: sub assign_access_key {
 2304: #
 2305: # a valid key looks like uname:udom#comments
 2306: # comments are being appended
 2307: #
 2308:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2309:     $kdom=
 2310:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2311:     $knum=
 2312:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2313:     $cdom=
 2314:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2315:     $cnum=
 2316:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2317:     $udom=$env{'user.name'} unless (defined($udom));
 2318:     $uname=$env{'user.domain'} unless (defined($uname));
 2319:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2320:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2321:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2322:                                                   # assigned to this person
 2323:                                                   # - this should not happen,
 2324:                                                   # unless something went wrong
 2325:                                                   # the first time around
 2326: # ready to assign
 2327:         $logentry=$1.'; '.$logentry;
 2328:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2329:                                                  $kdom,$knum) eq 'ok') {
 2330: # key now belongs to user
 2331: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2332:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2333:                 &appenv({'environment.'.$envkey => $ckey});
 2334:                 return 'ok';
 2335:             } else {
 2336:                 return 
 2337:   'error: Count not permanently assign key, will need to be re-entered later.';
 2338: 	    }
 2339:         } else {
 2340:             return 'error: Could not assign key, try again later.';
 2341:         }
 2342:     } elsif (!$existing{$ckey}) {
 2343: # the key does not exist
 2344: 	return 'error: The key does not exist';
 2345:     } else {
 2346: # the key is somebody else's
 2347: 	return 'error: The key is already in use';
 2348:     }
 2349: }
 2350: 
 2351: # ------------------------------------------ put an additional comment on a key
 2352: 
 2353: sub comment_access_key {
 2354: #
 2355: # a valid key looks like uname:udom#comments
 2356: # comments are being appended
 2357: #
 2358:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2359:     $cdom=
 2360:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2361:     $cnum=
 2362:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2363:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2364:     if ($existing{$ckey}) {
 2365:         $existing{$ckey}.='; '.$logentry;
 2366: # ready to assign
 2367:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2368:                                                  $cdom,$cnum) eq 'ok') {
 2369: 	    return 'ok';
 2370:         } else {
 2371: 	    return 'error: Count not store comment.';
 2372:         }
 2373:     } else {
 2374: # the key does not exist
 2375: 	return 'error: The key does not exist';
 2376:     }
 2377: }
 2378: 
 2379: # ------------------------------------------------------ Generate a set of keys
 2380: 
 2381: sub generate_access_keys {
 2382:     my ($number,$cdom,$cnum,$logentry)=@_;
 2383:     $cdom=
 2384:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2385:     $cnum=
 2386:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2387:     unless (&allowed('mky',$cdom)) { return 0; }
 2388:     unless (($cdom) && ($cnum)) { return 0; }
 2389:     if ($number>10000) { return 0; }
 2390:     sleep(2); # make sure don't get same seed twice
 2391:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2392:     my $total=0;
 2393:     for (my $i=1;$i<=$number;$i++) {
 2394:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2395:                   sprintf("%lx",int(100000*rand)).'-'.
 2396:                   sprintf("%lx",int(100000*rand));
 2397:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2398:        $newkey=~s/0/h/g; # and also 0 and O
 2399:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2400:        if ($existing{$newkey}) {
 2401:            $i--;
 2402:        } else {
 2403: 	  if (&put('accesskeys',
 2404:               { $newkey => '# generated '.localtime().
 2405:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2406:                            '; '.$logentry },
 2407: 		   $cdom,$cnum) eq 'ok') {
 2408:               $total++;
 2409: 	  }
 2410:        }
 2411:     }
 2412:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2413:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2414:     return $total;
 2415: }
 2416: 
 2417: # ------------------------------------------------------- Validate an accesskey
 2418: 
 2419: sub validate_access_key {
 2420:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2421:     $cdom=
 2422:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2423:     $cnum=
 2424:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2425:     $udom=$env{'user.domain'} unless (defined($udom));
 2426:     $uname=$env{'user.name'} unless (defined($uname));
 2427:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2428:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2429: }
 2430: 
 2431: # ------------------------------------- Find the section of student in a course
 2432: sub devalidate_getsection_cache {
 2433:     my ($udom,$unam,$courseid)=@_;
 2434:     my $hashid="$udom:$unam:$courseid";
 2435:     &devalidate_cache_new('getsection',$hashid);
 2436: }
 2437: 
 2438: sub courseid_to_courseurl {
 2439:     my ($courseid) = @_;
 2440:     #already url style courseid
 2441:     return $courseid if ($courseid =~ m{^/});
 2442: 
 2443:     if (exists($env{'course.'.$courseid.'.num'})) {
 2444: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2445: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2446: 	return "/$cdom/$cnum";
 2447:     }
 2448: 
 2449:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2450:     if (exists($courseinfo{'num'})) {
 2451: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2452:     }
 2453: 
 2454:     return undef;
 2455: }
 2456: 
 2457: sub getsection {
 2458:     my ($udom,$unam,$courseid)=@_;
 2459:     my $cachetime=1800;
 2460: 
 2461:     my $hashid="$udom:$unam:$courseid";
 2462:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2463:     if (defined($cached)) { return $result; }
 2464: 
 2465:     my %Pending; 
 2466:     my %Expired;
 2467:     #
 2468:     # Each role can either have not started yet (pending), be active, 
 2469:     #    or have expired.
 2470:     #
 2471:     # If there is an active role, we are done.
 2472:     #
 2473:     # If there is more than one role which has not started yet, 
 2474:     #     choose the one which will start sooner
 2475:     # If there is one role which has not started yet, return it.
 2476:     #
 2477:     # If there is more than one expired role, choose the one which ended last.
 2478:     # If there is a role which has expired, return it.
 2479:     #
 2480:     $courseid = &courseid_to_courseurl($courseid);
 2481:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2482:     foreach my $key (keys(%roleshash)) {
 2483:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2484:         my $section=$1;
 2485:         if ($key eq $courseid.'_st') { $section=''; }
 2486:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2487:         my $now=time;
 2488:         if (defined($end) && $end && ($now > $end)) {
 2489:             $Expired{$end}=$section;
 2490:             next;
 2491:         }
 2492:         if (defined($start) && $start && ($now < $start)) {
 2493:             $Pending{$start}=$section;
 2494:             next;
 2495:         }
 2496:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2497:     }
 2498:     #
 2499:     # Presumedly there will be few matching roles from the above
 2500:     # loop and the sorting time will be negligible.
 2501:     if (scalar(keys(%Pending))) {
 2502:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2503:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2504:     } 
 2505:     if (scalar(keys(%Expired))) {
 2506:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2507:         my $time = pop(@sorted);
 2508:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2509:     }
 2510:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2511: }
 2512: 
 2513: sub save_cache {
 2514:     &purge_remembered();
 2515:     #&Apache::loncommon::validate_page();
 2516:     undef(%env);
 2517:     undef($env_loaded);
 2518: }
 2519: 
 2520: my $to_remember=-1;
 2521: my %remembered;
 2522: my %accessed;
 2523: my $kicks=0;
 2524: my $hits=0;
 2525: sub make_key {
 2526:     my ($name,$id) = @_;
 2527:     if (length($id) > 65 
 2528: 	&& length(&escape($id)) > 200) {
 2529: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2530:     }
 2531:     return &escape($name.':'.$id);
 2532: }
 2533: 
 2534: sub devalidate_cache_new {
 2535:     my ($name,$id,$debug) = @_;
 2536:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2537:     my $remembered_id=$name.':'.$id;
 2538:     $id=&make_key($name,$id);
 2539:     $memcache->delete($id);
 2540:     delete($remembered{$remembered_id});
 2541:     delete($accessed{$remembered_id});
 2542: }
 2543: 
 2544: sub is_cached_new {
 2545:     my ($name,$id,$debug) = @_;
 2546:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
 2547:                                      # keys in %remembered hash, which persists for
 2548:                                      # duration of request (no restriction on key length).
 2549:     if (exists($remembered{$remembered_id})) {
 2550: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2551: 	$accessed{$remembered_id}=[&gettimeofday()];
 2552: 	$hits++;
 2553: 	return ($remembered{$remembered_id},1);
 2554:     }
 2555:     $id=&make_key($name,$id);
 2556:     my $value = $memcache->get($id);
 2557:     if (!(defined($value))) {
 2558: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2559: 	return (undef,undef);
 2560:     }
 2561:     if ($value eq '__undef__') {
 2562: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2563: 	$value=undef;
 2564:     }
 2565:     &make_room($remembered_id,$value,$debug);
 2566:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2567:     return ($value,1);
 2568: }
 2569: 
 2570: sub do_cache_new {
 2571:     my ($name,$id,$value,$time,$debug) = @_;
 2572:     my $remembered_id=$name.':'.$id;
 2573:     $id=&make_key($name,$id);
 2574:     my $setvalue=$value;
 2575:     if (!defined($setvalue)) {
 2576: 	$setvalue='__undef__';
 2577:     }
 2578:     if (!defined($time) ) {
 2579: 	$time=600;
 2580:     }
 2581:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2582:     my $result = $memcache->set($id,$setvalue,$time);
 2583:     if (! $result) {
 2584: 	&logthis("caching of id -> $id  failed");
 2585: 	$memcache->disconnect_all();
 2586:     }
 2587:     # need to make a copy of $value
 2588:     &make_room($remembered_id,$value,$debug);
 2589:     return $value;
 2590: }
 2591: 
 2592: sub make_room {
 2593:     my ($remembered_id,$value,$debug)=@_;
 2594: 
 2595:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2596:                                     : $value;
 2597:     if ($to_remember<0) { return; }
 2598:     $accessed{$remembered_id}=[&gettimeofday()];
 2599:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2600:     my $to_kick;
 2601:     my $max_time=0;
 2602:     foreach my $other (keys(%accessed)) {
 2603: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2604: 	    $to_kick=$other;
 2605: 	    $max_time=&tv_interval($accessed{$other});
 2606: 	}
 2607:     }
 2608:     delete($remembered{$to_kick});
 2609:     delete($accessed{$to_kick});
 2610:     $kicks++;
 2611:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2612:     return;
 2613: }
 2614: 
 2615: sub purge_remembered {
 2616:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2617:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2618:     undef(%remembered);
 2619:     undef(%accessed);
 2620: }
 2621: # ------------------------------------- Read an entry from a user's environment
 2622: 
 2623: sub userenvironment {
 2624:     my ($udom,$unam,@what)=@_;
 2625:     my $items;
 2626:     foreach my $item (@what) {
 2627:         $items.=&escape($item).'&';
 2628:     }
 2629:     $items=~s/\&$//;
 2630:     my %returnhash=();
 2631:     my $uhome = &homeserver($unam,$udom);
 2632:     unless ($uhome eq 'no_host') {
 2633:         my @answer=split(/\&/, 
 2634:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2635:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2636:             return %returnhash;
 2637:         }
 2638:         my $i;
 2639:         for ($i=0;$i<=$#what;$i++) {
 2640: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2641:         }
 2642:     }
 2643:     return %returnhash;
 2644: }
 2645: 
 2646: # ---------------------------------------------------------- Get a studentphoto
 2647: sub studentphoto {
 2648:     my ($udom,$unam,$ext) = @_;
 2649:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2650:     if (defined($env{'request.course.id'})) {
 2651:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2652:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2653:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2654:             } else {
 2655:                 my ($result,$perm_reqd)=
 2656: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2657:                 if ($result eq 'ok') {
 2658:                     if (!($perm_reqd eq 'yes')) {
 2659:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2660:                     }
 2661:                 }
 2662:             }
 2663:         }
 2664:     } else {
 2665:         my ($result,$perm_reqd) = 
 2666: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2667:         if ($result eq 'ok') {
 2668:             if (!($perm_reqd eq 'yes')) {
 2669:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2670:             }
 2671:         }
 2672:     }
 2673:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2674: }
 2675: 
 2676: sub retrievestudentphoto {
 2677:     my ($udom,$unam,$ext,$type) = @_;
 2678:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2679:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2680:     if ($ret eq 'ok') {
 2681:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2682:         if ($type eq 'thumbnail') {
 2683:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2684:         }
 2685:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2686:         return $tokenurl;
 2687:     } else {
 2688:         if ($type eq 'thumbnail') {
 2689:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2690:         } else { 
 2691:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2692:         }
 2693:     }
 2694: }
 2695: 
 2696: # -------------------------------------------------------------------- New chat
 2697: 
 2698: sub chatsend {
 2699:     my ($newentry,$anon,$group)=@_;
 2700:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2701:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2702:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2703:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2704: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2705: 		   &escape($newentry)).':'.$group,$chome);
 2706: }
 2707: 
 2708: # ------------------------------------------ Find current version of a resource
 2709: 
 2710: sub getversion {
 2711:     my $fname=&clutter(shift);
 2712:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2713:     return &currentversion(&filelocation('',$fname));
 2714: }
 2715: 
 2716: sub currentversion {
 2717:     my $fname=shift;
 2718:     my $author=$fname;
 2719:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2720:     my ($udom,$uname)=split(/\//,$author);
 2721:     my $home=&homeserver($uname,$udom);
 2722:     if ($home eq 'no_host') { 
 2723:         return -1; 
 2724:     }
 2725:     my $answer=&reply("currentversion:$fname",$home);
 2726:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2727: 	return -1;
 2728:     }
 2729:     return $answer;
 2730: }
 2731: 
 2732: #
 2733: # Return special version number of resource if set by override, empty otherwise
 2734: #
 2735: sub usedversion {
 2736:     my $fname=shift;
 2737:     unless ($fname) { $fname=$env{'request.uri'}; }
 2738:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2739:     if ($urlversion) { return $urlversion; }
 2740:     return '';
 2741: }
 2742: 
 2743: # ----------------------------- Subscribe to a resource, return URL if possible
 2744: 
 2745: sub subscribe {
 2746:     my $fname=shift;
 2747:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2748:     $fname=~s/[\n\r]//g;
 2749:     my $author=$fname;
 2750:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2751:     my ($udom,$uname)=split(/\//,$author);
 2752:     my $home=homeserver($uname,$udom);
 2753:     if ($home eq 'no_host') {
 2754:         return 'not_found';
 2755:     }
 2756:     my $answer=reply("sub:$fname",$home);
 2757:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2758: 	$answer.=' by '.$home;
 2759:     }
 2760:     return $answer;
 2761: }
 2762:     
 2763: # -------------------------------------------------------------- Replicate file
 2764: 
 2765: sub repcopy {
 2766:     my $filename=shift;
 2767:     $filename=~s/\/+/\//g;
 2768:     my $londocroot = $perlvar{'lonDocRoot'};
 2769:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2770:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2771:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2772: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2773: 	return &repcopy_userfile($filename);
 2774:     }
 2775:     $filename=~s/[\n\r]//g;
 2776:     my $transname="$filename.in.transfer";
 2777: # FIXME: this should flock
 2778:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2779:     my $remoteurl=subscribe($filename);
 2780:     if ($remoteurl =~ /^con_lost by/) {
 2781: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2782:            return 'unavailable';
 2783:     } elsif ($remoteurl eq 'not_found') {
 2784: 	   #&logthis("Subscribe returned not_found: $filename");
 2785: 	   return 'not_found';
 2786:     } elsif ($remoteurl =~ /^rejected by/) {
 2787: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2788:            return 'forbidden';
 2789:     } elsif ($remoteurl eq 'directory') {
 2790:            return 'ok';
 2791:     } else {
 2792:         my $author=$filename;
 2793:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2794:         my ($udom,$uname)=split(/\//,$author);
 2795:         my $home=homeserver($uname,$udom);
 2796:         unless ($home eq $perlvar{'lonHostID'}) {
 2797:            my @parts=split(/\//,$filename);
 2798:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2799:            if ($path ne "$londocroot/res") {
 2800:                &logthis("Malconfiguration for replication: $filename");
 2801: 	       return 'bad_request';
 2802:            }
 2803:            my $count;
 2804:            for ($count=5;$count<$#parts;$count++) {
 2805:                $path.="/$parts[$count]";
 2806:                if ((-e $path)!=1) {
 2807: 		   mkdir($path,0777);
 2808:                }
 2809:            }
 2810:            my $ua=new LWP::UserAgent;
 2811:            my $request=new HTTP::Request('GET',"$remoteurl");
 2812:            my $response=$ua->request($request,$transname);
 2813:            if ($response->is_error()) {
 2814: 	       unlink($transname);
 2815:                my $message=$response->status_line;
 2816:                &logthis("<font color=\"blue\">WARNING:"
 2817:                        ." LWP get: $message: $filename</font>");
 2818:                return 'unavailable';
 2819:            } else {
 2820: 	       if ($remoteurl!~/\.meta$/) {
 2821:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2822:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2823:                   if ($mresponse->is_error()) {
 2824: 		      unlink($filename.'.meta');
 2825:                       &logthis(
 2826:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2827:                   }
 2828: 	       }
 2829:                rename($transname,$filename);
 2830:                return 'ok';
 2831:            }
 2832:        }
 2833:     }
 2834: }
 2835: 
 2836: # ------------------------------------------------ Get server side include body
 2837: sub ssi_body {
 2838:     my ($filelink,%form)=@_;
 2839:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2840:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2841:     }
 2842:     my $output='';
 2843:     my $response;
 2844:     if ($filelink=~/^https?\:/) {
 2845:        ($output,$response)=&externalssi($filelink);
 2846:     } else {
 2847:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2848:        $filelink .= 'inhibitmenu=yes';
 2849:        ($output,$response)=&ssi($filelink,%form);
 2850:     }
 2851:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2852:     $output=~s/^.*?\<body[^\>]*\>//si;
 2853:     $output=~s/\<\/body\s*\>.*?$//si;
 2854:     if (wantarray) {
 2855:         return ($output, $response);
 2856:     } else {
 2857:         return $output;
 2858:     }
 2859: }
 2860: 
 2861: # --------------------------------------------------------- Server Side Include
 2862: 
 2863: sub absolute_url {
 2864:     my ($host_name) = @_;
 2865:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2866:     if ($host_name eq '') {
 2867: 	$host_name = $ENV{'SERVER_NAME'};
 2868:     }
 2869:     return $protocol.$host_name;
 2870: }
 2871: 
 2872: #
 2873: #   Server side include.
 2874: # Parameters:
 2875: #  fn     Possibly encrypted resource name/id.
 2876: #  form   Hash that describes how the rendering should be done
 2877: #         and other things.
 2878: # Returns:
 2879: #   Scalar context: The content of the response.
 2880: #   Array context:  2 element list of the content and the full response object.
 2881: #     
 2882: sub ssi {
 2883: 
 2884:     my ($fn,%form)=@_;
 2885:     my $ua=new LWP::UserAgent;
 2886:     my $request;
 2887: 
 2888:     $form{'no_update_last_known'}=1;
 2889:     &Apache::lonenc::check_encrypt(\$fn);
 2890:     if (%form) {
 2891:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2892:       $request->content(join('&',map {
 2893:             my $name = escape($_);
 2894:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
 2895:             ? join("&$name=", map {escape($_) } @{$form{$_}})
 2896:             : &escape($form{$_}) );
 2897:         } keys(%form)));
 2898:     } else {
 2899:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2900:     }
 2901: 
 2902:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2903:     my $response= $ua->request($request);
 2904:     if (wantarray) {
 2905: 	return ($response->content, $response);
 2906:     } else {
 2907: 	return $response->content;
 2908:     }
 2909: }
 2910: 
 2911: sub externalssi {
 2912:     my ($url)=@_;
 2913:     my $ua=new LWP::UserAgent;
 2914:     my $request=new HTTP::Request('GET',$url);
 2915:     my $response=$ua->request($request);
 2916:     if (wantarray) {
 2917:         return ($response->content, $response);
 2918:     } else {
 2919:         return $response->content;
 2920:     }
 2921: }
 2922: 
 2923: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2924: 
 2925: sub allowuploaded {
 2926:     my ($srcurl,$url)=@_;
 2927:     $url=&clutter(&declutter($url));
 2928:     my $dir=$url;
 2929:     $dir=~s/\/[^\/]+$//;
 2930:     my %httpref=();
 2931:     my $httpurl=&hreflocation('',$url);
 2932:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2933:     &Apache::lonnet::appenv(\%httpref);
 2934: }
 2935: 
 2936: #
 2937: # Determine if the current user should be able to edit a particular resource,
 2938: # when viewing in course context.
 2939: # (a) When viewing resource used to determine if "Edit" item is included in
 2940: #     Functions.
 2941: # (b) When displaying folder contents in course editor, used to determine if
 2942: #     "Edit" link will be displayed alongside resource.
 2943: #
 2944: #  input: six args -- filename (decluttered), course number, course domain,
 2945: #                   url, symb (if registered) and group (if this is a group
 2946: #                   item -- e.g., bulletin board, group page etc.).
 2947: #  output: array of five scalars --
 2948: #          $cfile -- url for file editing if editable on current server
 2949: #          $home -- homeserver of resource (i.e., for author if published,
 2950: #                                           or course if uploaded.).
 2951: #          $switchserver --  1 if server switch will be needed.
 2952: #          $forceedit -- 1 if icon/link should be to go to edit mode
 2953: #          $forceview -- 1 if icon/link should be to go to view mode
 2954: #
 2955: 
 2956: sub can_edit_resource {
 2957:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2958:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2959: #
 2960: # For aboutme pages user can only edit his/her own.
 2961: #
 2962:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2963:         my ($sdom,$sname) = ($1,$2);
 2964:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2965:             $home = $env{'user.home'};
 2966:             $cfile = $resurl;
 2967:             if ($env{'form.forceedit'}) {
 2968:                 $forceview = 1;
 2969:             } else {
 2970:                 $forceedit = 1;
 2971:             }
 2972:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2973:         } else {
 2974:             return;
 2975:         }
 2976:     }
 2977: 
 2978:     if ($env{'request.course.id'}) {
 2979:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2980:         if ($group ne '') {
 2981: # if this is a group homepage or group bulletin board, check group privs
 2982:             my $allowed = 0;
 2983:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2984:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2985:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2986:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2987:                     $allowed = 1;
 2988:                 }
 2989:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2990:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2991:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2992:                     $allowed = 1;
 2993:                 }
 2994:             }
 2995:             if ($allowed) {
 2996:                 $home=&homeserver($cnum,$cdom);
 2997:                 if ($env{'form.forceedit'}) {
 2998:                     $forceview = 1;
 2999:                 } else {
 3000:                     $forceedit = 1;
 3001:                 }
 3002:                 $cfile = $resurl;
 3003:             } else {
 3004:                 return;
 3005:             }
 3006:         } else {
 3007:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3008:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3009:                     return;
 3010:                 }
 3011:             } elsif (!$crsedit) {
 3012: #
 3013: # No edit allowed where CC has switched to student role.
 3014: #
 3015:                 return;
 3016:             }
 3017:         }
 3018:     }
 3019: 
 3020:     if ($file ne '') {
 3021:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3022:             if (&is_course_upload($file,$cnum,$cdom)) {
 3023:                 $uploaded = 1;
 3024:                 $incourse = 1;
 3025:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3026:                     $cfile = &hreflocation('',$file);
 3027:                     if ($env{'form.forceedit'}) {
 3028:                         $forceview = 1;
 3029:                     } else {
 3030:                         $forceedit = 1;
 3031:                     }
 3032:                 }
 3033:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3034:                 $incourse = 1;
 3035:                 if ($env{'form.forceedit'}) {
 3036:                     $forceview = 1;
 3037:                 } else {
 3038:                     $forceedit = 1;
 3039:                 }
 3040:                 $cfile = $resurl;
 3041:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 3042:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3043:                     $incourse = 1;
 3044:                     if ($env{'form.forceedit'}) {
 3045:                         $forceview = 1;
 3046:                     } else {
 3047:                         $forceedit = 1;
 3048:                     }
 3049:                     $cfile = $resurl;
 3050:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3051:                     $incourse = 1;
 3052:                     $cfile = $resurl.'/smpedit';
 3053:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3054:                     $incourse = 1;
 3055:                     if ($env{'form.forceedit'}) {
 3056:                         $forceview = 1;
 3057:                     } else {
 3058:                         $forceedit = 1;
 3059:                     }
 3060:                     $cfile = $resurl;
 3061:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3062:                     $incourse = 1;
 3063:                     if ($env{'form.forceedit'}) {
 3064:                         $forceview = 1;
 3065:                     } else {
 3066:                         $forceedit = 1;
 3067:                     }
 3068:                     $cfile = $resurl;
 3069:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3070:                     $incourse = 1;
 3071:                     if ($env{'form.forceedit'}) {
 3072:                         $forceview = 1;
 3073:                     } else {
 3074:                         $forceedit = 1;
 3075:                     }
 3076:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3077:                 }
 3078:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3079:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3080:                 if (&is_on_map($template)) {
 3081:                     $incourse = 1;
 3082:                     $forceview = 1;
 3083:                     $cfile = $template;
 3084:                 }
 3085:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3086:                     $incourse = 1;
 3087:                     if ($env{'form.forceedit'}) {
 3088:                         $forceview = 1;
 3089:                     } else {
 3090:                         $forceedit = 1;
 3091:                     }
 3092:                     $cfile = $resurl;
 3093:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3094:                 $incourse = 1;
 3095:                 if ($env{'form.forceedit'}) {
 3096:                     $forceview = 1;
 3097:                 } else {
 3098:                     $forceedit = 1;
 3099:                 }
 3100:                 $cfile = $resurl;
 3101:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3102:                 $incourse = 1;
 3103:                 $forceview = 1;
 3104:                 if ($symb) {
 3105:                     my ($map,$id,$res)=&decode_symb($symb);
 3106:                     $env{'request.symb'} = $symb;
 3107:                     $cfile = &clutter($res);
 3108:                 } else {
 3109:                     $cfile = $env{'form.suppurl'};
 3110:                     my $escfile = &unescape($cfile);
 3111:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3112:                         $cfile = '/adm/wrapper'.$escfile;
 3113:                     } else {
 3114:                         $escfile =~ s{^http://}{};
 3115:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3116:                     }
 3117:                 }
 3118:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3119:                 if ($env{'form.forceedit'}) {
 3120:                     $forceview = 1;
 3121:                 } else {
 3122:                     $forceedit = 1;
 3123:                 }
 3124:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3125:             }
 3126:         }
 3127:         if ($uploaded || $incourse) {
 3128:             $home=&homeserver($cnum,$cdom);
 3129:         } elsif ($file !~ m{/$}) {
 3130:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3131:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3132:             # Check that the user has permission to edit this resource
 3133:             my $setpriv = 1;
 3134:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3135:             if (defined($cfudom)) {
 3136:                 $home=&homeserver($cfuname,$cfudom);
 3137:                 $cfile=$file;
 3138:             }
 3139:         }
 3140:         if (($cfile ne '') && (!$incourse || $uploaded) &&
 3141:             (($home ne '') && ($home ne 'no_host'))) {
 3142:             my @ids=&current_machine_ids();
 3143:             unless (grep(/^\Q$home\E$/,@ids)) {
 3144:                 $switchserver=1;
 3145:             }
 3146:         }
 3147:     }
 3148:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3149: }
 3150: 
 3151: sub is_course_upload {
 3152:     my ($file,$cnum,$cdom) = @_;
 3153:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3154:     $uploadpath =~ s{^\/}{};
 3155:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3156:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3157:         return 1;
 3158:     }
 3159:     return;
 3160: }
 3161: 
 3162: sub in_course {
 3163:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3164:     if ($hideprivileged) {
 3165:         my $skipuser;
 3166:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3167:         my @possdoms = ($cdom);
 3168:         if ($coursehash{'checkforpriv'}) {
 3169:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3170:         }
 3171:         if (&privileged($uname,$udom,\@possdoms)) {
 3172:             $skipuser = 1;
 3173:             if ($coursehash{'nothideprivileged'}) {
 3174:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3175:                     my $user;
 3176:                     if ($item =~ /:/) {
 3177:                         $user = $item;
 3178:                     } else {
 3179:                         $user = join(':',split(/[\@]/,$item));
 3180:                     }
 3181:                     if ($user eq $uname.':'.$udom) {
 3182:                         undef($skipuser);
 3183:                         last;
 3184:                     }
 3185:                 }
 3186:             }
 3187:             if ($skipuser) {
 3188:                 return 0;
 3189:             }
 3190:         }
 3191:     }
 3192:     $type ||= 'any';
 3193:     if (!defined($cdom) || !defined($cnum)) {
 3194:         my $cid  = $env{'request.course.id'};
 3195:         $cdom = $env{'course.'.$cid.'.domain'};
 3196:         $cnum = $env{'course.'.$cid.'.num'};
 3197:     }
 3198:     my $typesref;
 3199:     if (($type eq 'any') || ($type eq 'all')) {
 3200:         $typesref = ['active','previous','future'];
 3201:     } elsif ($type eq 'previous' || $type eq 'future') {
 3202:         $typesref = [$type];
 3203:     }
 3204:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3205:                               $typesref,undef,[$cdom]);
 3206:     my ($tmp) = keys(%roles);
 3207:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3208:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3209:     if (@course_roles > 0) {
 3210:         return 1;
 3211:     }
 3212:     return 0;
 3213: }
 3214: 
 3215: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3216: # input: action, courseID, current domain, intended
 3217: #        path to file, source of file, instruction to parse file for objects,
 3218: #        ref to hash for embedded objects,
 3219: #        ref to hash for codebase of java objects.
 3220: #        reference to scalar to accommodate mime type determined
 3221: #          from File::MMagic if $parser = parse.
 3222: #
 3223: # output: url to file (if action was uploaddoc), 
 3224: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3225: #
 3226: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3227: # course.
 3228: #
 3229: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3230: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3231: #          course's home server.
 3232: #
 3233: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3234: #          be copied from $source (current location) to 
 3235: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3236: #         and will then be copied to
 3237: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3238: #         course's home server.
 3239: #
 3240: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3241: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3242: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3243: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3244: #         in course's home server.
 3245: #
 3246: 
 3247: sub process_coursefile {
 3248:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3249:         $mimetype)=@_;
 3250:     my $fetchresult;
 3251:     my $home=&homeserver($docuname,$docudom);
 3252:     if ($action eq 'propagate') {
 3253:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3254: 			     $home);
 3255:     } else {
 3256:         my $fpath = '';
 3257:         my $fname = $file;
 3258:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3259:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3260:         my $filepath = &build_filepath($fpath);
 3261:         if ($action eq 'copy') {
 3262:             if ($source eq '') {
 3263:                 $fetchresult = 'no source file';
 3264:                 return $fetchresult;
 3265:             } else {
 3266:                 my $destination = $filepath.'/'.$fname;
 3267:                 rename($source,$destination);
 3268:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3269:                                  $home);
 3270:             }
 3271:         } elsif ($action eq 'uploaddoc') {
 3272:             open(my $fh,'>',$filepath.'/'.$fname);
 3273:             print $fh $env{'form.'.$source};
 3274:             close($fh);
 3275:             if ($parser eq 'parse') {
 3276:                 my $mm = new File::MMagic;
 3277:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3278:                 if ($type eq 'text/html') {
 3279:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3280:                     unless ($parse_result eq 'ok') {
 3281:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3282:                     }
 3283:                 }
 3284:                 if (ref($mimetype)) {
 3285:                     $$mimetype = $type;
 3286:                 } 
 3287:             }
 3288:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3289:                                  $home);
 3290:             if ($fetchresult eq 'ok') {
 3291:                 return '/uploaded/'.$fpath.'/'.$fname;
 3292:             } else {
 3293:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3294:                         ' to host '.$home.': '.$fetchresult);
 3295:                 return '/adm/notfound.html';
 3296:             }
 3297:         }
 3298:     }
 3299:     unless ( $fetchresult eq 'ok') {
 3300:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3301:              ' to host '.$home.': '.$fetchresult);
 3302:     }
 3303:     return $fetchresult;
 3304: }
 3305: 
 3306: sub build_filepath {
 3307:     my ($fpath) = @_;
 3308:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3309:     unless ($fpath eq '') {
 3310:         my @parts=split('/',$fpath);
 3311:         foreach my $part (@parts) {
 3312:             $filepath.= '/'.$part;
 3313:             if ((-e $filepath)!=1) {
 3314:                 mkdir($filepath,0777);
 3315:             }
 3316:         }
 3317:     }
 3318:     return $filepath;
 3319: }
 3320: 
 3321: sub store_edited_file {
 3322:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3323:     my $file = $primary_url;
 3324:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3325:     my $fpath = '';
 3326:     my $fname = $file;
 3327:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3328:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3329:     my $filepath = &build_filepath($fpath);
 3330:     open(my $fh,'>',$filepath.'/'.$fname);
 3331:     print $fh $content;
 3332:     close($fh);
 3333:     my $home=&homeserver($docuname,$docudom);
 3334:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3335: 			  $home);
 3336:     if ($$fetchresult eq 'ok') {
 3337:         return '/uploaded/'.$fpath.'/'.$fname;
 3338:     } else {
 3339:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3340: 		 ' to host '.$home.': '.$$fetchresult);
 3341:         return '/adm/notfound.html';
 3342:     }
 3343: }
 3344: 
 3345: sub clean_filename {
 3346:     my ($fname,$args)=@_;
 3347: # Replace Windows backslashes by forward slashes
 3348:     $fname=~s/\\/\//g;
 3349:     if (!$args->{'keep_path'}) {
 3350:         # Get rid of everything but the actual filename
 3351: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3352:     }
 3353: # Replace spaces by underscores
 3354:     $fname=~s/\s+/\_/g;
 3355: # Replace all other weird characters by nothing
 3356:     $fname=~s{[^/\w\.\-]}{}g;
 3357: # Replace all .\d. sequences with _\d. so they no longer look like version
 3358: # numbers
 3359:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3360:     return $fname;
 3361: }
 3362: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3363: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3364: # image with the same aspect ratio as the original, but with dimensions which do 
 3365: # not exceed $resizewidth and $resizeheight.
 3366:  
 3367: sub resizeImage {
 3368:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3369:     my $ima = Image::Magick->new;
 3370:     my $resized;
 3371:     if (-e $img_path) {
 3372:         $ima->Read($img_path);
 3373:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3374:             my $width = $ima->Get('width');
 3375:             my $height = $ima->Get('height');
 3376:             if ($width > $resizewidth) {
 3377: 	        my $factor = $width/$resizewidth;
 3378:                 my $newheight = $height/$factor;
 3379:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3380:                 $resized = 1;
 3381:             }
 3382:         }
 3383:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3384:             my $width = $ima->Get('width');
 3385:             my $height = $ima->Get('height');
 3386:             if ($height > $resizeheight) {
 3387:                 my $factor = $height/$resizeheight;
 3388:                 my $newwidth = $width/$factor;
 3389:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3390:                 $resized = 1;
 3391:             }
 3392:         }
 3393:         if ($resized) {
 3394:             $ima->Write($img_path);
 3395:         }
 3396:     }
 3397:     return;
 3398: }
 3399: 
 3400: # --------------- Take an uploaded file and put it into the userfiles directory
 3401: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3402: #                    the desired filename is in $env{"form.$formname.filename"}
 3403: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3404: #                                    canceloverwrite, or ''. 
 3405: #                   if 'coursedoc': upload to the current course
 3406: #                   if 'existingfile': write file to tmp/overwrites directory 
 3407: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3408: #                   $context is passed as argument to &finishuserfileupload
 3409: #        $subdir - directory in userfile to store the file into
 3410: #        $parser - instruction to parse file for objects ($parser = parse)    
 3411: #        $allfiles - reference to hash for embedded objects
 3412: #        $codebase - reference to hash for codebase of java objects
 3413: #        $desuname - username for permanent storage of uploaded file
 3414: #        $dsetudom - domain for permanaent storage of uploaded file
 3415: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3416: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3417: #        $resizewidth - width (pixels) to which to resize uploaded image
 3418: #        $resizeheight - height (pixels) to which to resize uploaded image
 3419: #        $mimetype - reference to scalar to accommodate mime type determined
 3420: #                    from File::MMagic.
 3421: # 
 3422: # output: url of file in userspace, or error: <message> 
 3423: #             or /adm/notfound.html if failure to upload occurse
 3424: 
 3425: sub userfileupload {
 3426:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3427:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3428:     if (!defined($subdir)) { $subdir='unknown'; }
 3429:     my $fname=$env{'form.'.$formname.'.filename'};
 3430:     $fname=&clean_filename($fname);
 3431:     # See if there is anything left
 3432:     unless ($fname) { return 'error: no uploaded file'; }
 3433:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3434:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3435:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3436:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3437:         my $now = time;
 3438:         my $filepath;
 3439:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3440:              $filepath = 'tmp/helprequests/'.$now;
 3441:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3442:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3443:                          '_'.$env{'user.domain'}.'/pending';
 3444:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3445:             my ($docuname,$docudom);
 3446:             if ($destudom =~ /^$match_domain$/) {
 3447:                 $docudom = $destudom;
 3448:             } else {
 3449:                 $docudom = $env{'user.domain'};
 3450:             }
 3451:             if ($destuname =~ /^$match_username$/) {
 3452:                 $docuname = $destuname;
 3453:             } else {
 3454:                 $docuname = $env{'user.name'};
 3455:             }
 3456:             if (exists($env{'form.group'})) {
 3457:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3458:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3459:             }
 3460:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3461:             if ($context eq 'canceloverwrite') {
 3462:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3463:                 if (-e  $tempfile) {
 3464:                     my @info = stat($tempfile);
 3465:                     if ($info[9] eq $env{'form.timestamp'}) {
 3466:                         unlink($tempfile);
 3467:                     }
 3468:                 }
 3469:                 return;
 3470:             }
 3471:         }
 3472:         # Create the directory if not present
 3473:         my @parts=split(/\//,$filepath);
 3474:         my $fullpath = $perlvar{'lonDaemons'};
 3475:         for (my $i=0;$i<@parts;$i++) {
 3476:             $fullpath .= '/'.$parts[$i];
 3477:             if ((-e $fullpath)!=1) {
 3478:                 mkdir($fullpath,0777);
 3479:             }
 3480:         }
 3481:         open(my $fh,'>',$fullpath.'/'.$fname);
 3482:         print $fh $env{'form.'.$formname};
 3483:         close($fh);
 3484:         if ($context eq 'existingfile') {
 3485:             my @info = stat($fullpath.'/'.$fname);
 3486:             return ($fullpath.'/'.$fname,$info[9]);
 3487:         } else {
 3488:             return $fullpath.'/'.$fname;
 3489:         }
 3490:     }
 3491:     if ($subdir eq 'scantron') {
 3492:         $fname = 'scantron_orig_'.$fname;
 3493:     } else {
 3494:         $fname="$subdir/$fname";
 3495:     }
 3496:     if ($context eq 'coursedoc') {
 3497: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3498: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3499:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3500:             return &finishuserfileupload($docuname,$docudom,
 3501: 					 $formname,$fname,$parser,$allfiles,
 3502: 					 $codebase,$thumbwidth,$thumbheight,
 3503:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3504:         } else {
 3505:             if ($env{'form.folder'}) {
 3506:                 $fname=$env{'form.folder'}.'/'.$fname;
 3507:             }
 3508:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3509: 				       $fname,$formname,$parser,
 3510: 				       $allfiles,$codebase,$mimetype);
 3511:         }
 3512:     } elsif (defined($destuname)) {
 3513:         my $docuname=$destuname;
 3514:         my $docudom=$destudom;
 3515: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3516: 				     $parser,$allfiles,$codebase,
 3517:                                      $thumbwidth,$thumbheight,
 3518:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3519:     } else {
 3520:         my $docuname=$env{'user.name'};
 3521:         my $docudom=$env{'user.domain'};
 3522:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3523:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3524:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3525:         }
 3526: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3527: 				     $parser,$allfiles,$codebase,
 3528:                                      $thumbwidth,$thumbheight,
 3529:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3530:     }
 3531: }
 3532: 
 3533: sub finishuserfileupload {
 3534:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3535:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3536:     my $path=$docudom.'/'.$docuname.'/';
 3537:     my $filepath=$perlvar{'lonDocRoot'};
 3538:   
 3539:     my ($fnamepath,$file,$fetchthumb);
 3540:     $file=$fname;
 3541:     if ($fname=~m|/|) {
 3542:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3543: 	$path.=$fnamepath.'/';
 3544:     }
 3545:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3546:     my $count;
 3547:     for ($count=4;$count<=$#parts;$count++) {
 3548:         $filepath.="/$parts[$count]";
 3549:         if ((-e $filepath)!=1) {
 3550: 	    mkdir($filepath,0777);
 3551:         }
 3552:     }
 3553: 
 3554: # Save the file
 3555:     {
 3556: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 3557: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3558: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3559: 	    return '/adm/notfound.html';
 3560: 	}
 3561:         if ($context eq 'overwrite') {
 3562:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3563:             my $target = $filepath.'/'.$file;
 3564:             if (-e $source) {
 3565:                 my @info = stat($source);
 3566:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3567:                     unless (&File::Copy::move($source,$target)) {
 3568:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3569:                         return "Moving from $source failed";
 3570:                     }
 3571:                 } else {
 3572:                     return "Temporary file: $source had unexpected date/time for last modification";
 3573:                 }
 3574:             } else {
 3575:                 return "Temporary file: $source missing";
 3576:             }
 3577:         } elsif (!print FH ($env{'form.'.$formname})) {
 3578: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3579: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3580: 	    return '/adm/notfound.html';
 3581: 	}
 3582: 	close(FH);
 3583:         if ($resizewidth && $resizeheight) {
 3584:             my $mm = new File::MMagic;
 3585:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3586:             if ($mime_type =~ m{^image/}) {
 3587: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3588:             }  
 3589: 	}
 3590:     }
 3591:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3592:         if (ref($mimetype)) {
 3593:             if ($$mimetype eq '') {
 3594:                 my $mm = new File::MMagic;
 3595:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3596:                 $$mimetype = $type;
 3597:             }
 3598:         }
 3599:     }
 3600:     if ($parser eq 'parse') {
 3601:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3602:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3603:                                                        $allfiles,$codebase);
 3604:             unless ($parse_result eq 'ok') {
 3605:                 &logthis('Failed to parse '.$filepath.$file.
 3606: 	   	         ' for embedded media: '.$parse_result); 
 3607:             }
 3608:         }
 3609:     }
 3610:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3611:         my $input = $filepath.'/'.$file;
 3612:         my $output = $filepath.'/'.'tn-'.$file;
 3613:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3614:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 3615:         system({$args[0]} @args);
 3616:         if (-e $filepath.'/'.'tn-'.$file) {
 3617:             $fetchthumb  = 1; 
 3618:         }
 3619:     }
 3620:  
 3621: # Notify homeserver to grep it
 3622: #
 3623:     my $docuhome=&homeserver($docuname,$docudom);	
 3624:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3625:     if ($fetchresult eq 'ok') {
 3626:         if ($fetchthumb) {
 3627:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3628:             if ($thumbresult ne 'ok') {
 3629:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3630:                          $docuhome.': '.$thumbresult);
 3631:             }
 3632:         }
 3633: #
 3634: # Return the URL to it
 3635:         return '/uploaded/'.$path.$file;
 3636:     } else {
 3637:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3638: 		 ': '.$fetchresult);
 3639:         return '/adm/notfound.html';
 3640:     }
 3641: }
 3642: 
 3643: sub extract_embedded_items {
 3644:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3645:     my @state = ();
 3646:     my (%lastids,%related,%shockwave,%flashvars);
 3647:     my %javafiles = (
 3648:                       codebase => '',
 3649:                       code => '',
 3650:                       archive => ''
 3651:                     );
 3652:     my %mediafiles = (
 3653:                       src => '',
 3654:                       movie => '',
 3655:                      );
 3656:     my $p;
 3657:     if ($content) {
 3658:         $p = HTML::LCParser->new($content);
 3659:     } else {
 3660:         $p = HTML::LCParser->new($fullpath);
 3661:     }
 3662:     while (my $t=$p->get_token()) {
 3663: 	if ($t->[0] eq 'S') {
 3664: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3665: 	    push(@state, $tagname);
 3666:             if (lc($tagname) eq 'allow') {
 3667:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3668:             }
 3669: 	    if (lc($tagname) eq 'img') {
 3670: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3671: 	    }
 3672: 	    if (lc($tagname) eq 'a') {
 3673:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3674: 		    &add_filetype($allfiles,$attr->{'href'},'href');
 3675:                 }
 3676: 	    }
 3677:             if (lc($tagname) eq 'script') {
 3678:                 my $src;
 3679:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3680:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3681:                 } else {
 3682:                     if ($attr->{'src'} ne '') {
 3683:                         $src = $attr->{'src'};
 3684:                         &add_filetype($allfiles,$src,'src');
 3685:                     }
 3686:                 }
 3687:                 my $text = $p->get_trimmed_text();
 3688:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3689:                     my @swfargs = split(/,/,$1);
 3690:                     foreach my $item (@swfargs) {
 3691:                         $item =~ s/["']//g;
 3692:                         $item =~ s/^\s+//;
 3693:                         $item =~ s/\s+$//;
 3694:                     }
 3695:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3696:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3697:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3698:                         } else {
 3699:                             $related{$swfargs[0]} = [$swfargs[2]];
 3700:                         }
 3701:                     }
 3702:                 }
 3703:             }
 3704:             if (lc($tagname) eq 'link') {
 3705:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3706:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3707:                 }
 3708:             }
 3709: 	    if (lc($tagname) eq 'object' ||
 3710: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3711: 		foreach my $item (keys(%javafiles)) {
 3712: 		    $javafiles{$item} = '';
 3713: 		}
 3714:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3715:                     $lastids{lc($tagname)} = $attr->{'id'};
 3716:                 }
 3717: 	    }
 3718: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3719: 		my $name = lc($attr->{'name'});
 3720: 		foreach my $item (keys(%javafiles)) {
 3721: 		    if ($name eq $item) {
 3722: 			$javafiles{$item} = $attr->{'value'};
 3723: 			last;
 3724: 		    }
 3725: 		}
 3726:                 my $pathfrom;
 3727: 		foreach my $item (keys(%mediafiles)) {
 3728: 		    if ($name eq $item) {
 3729:                         $pathfrom = $attr->{'value'};
 3730:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3731: 			&add_filetype($allfiles,$pathfrom,$name);
 3732: 			last;
 3733: 		    }
 3734: 		}
 3735:                 if ($name eq 'flashvars') {
 3736:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3737:                 }
 3738:                 if ($pathfrom ne '') {
 3739:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3740:                                          $pathfrom);
 3741:                 }
 3742: 	    }
 3743: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3744: 		foreach my $item (keys(%javafiles)) {
 3745: 		    if ($attr->{$item}) {
 3746: 			$javafiles{$item} = $attr->{$item};
 3747: 			last;
 3748: 		    }
 3749: 		}
 3750: 		foreach my $item (keys(%mediafiles)) {
 3751: 		    if ($attr->{$item}) {
 3752: 			&add_filetype($allfiles,$attr->{$item},$item);
 3753: 			last;
 3754: 		    }
 3755: 		}
 3756:                 if (lc($tagname) eq 'embed') {
 3757:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3758:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3759:                                              $attr->{'src'});
 3760:                     }
 3761:                 }
 3762: 	    }
 3763:             if (lc($tagname) eq 'iframe') {
 3764:                 my $src = $attr->{'src'} ;
 3765:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3766:                     &add_filetype($allfiles,$src,'src');
 3767:                 } elsif ($src =~ m{^/}) {
 3768:                     if ($env{'request.course.id'}) {
 3769:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3770:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3771:                         my $url = &hreflocation('',$fullpath);
 3772:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3773:                             my $relpath = $1;
 3774:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3775:                                 &add_filetype($allfiles,$1,'src');
 3776:                             }
 3777:                         }
 3778:                     }
 3779:                 }
 3780:             }
 3781:             if ($t->[4] =~ m{/>$}) {
 3782:                 pop(@state);
 3783:             }
 3784: 	} elsif ($t->[0] eq 'E') {
 3785: 	    my ($tagname) = ($t->[1]);
 3786: 	    if ($javafiles{'codebase'} ne '') {
 3787: 		$javafiles{'codebase'} .= '/';
 3788: 	    }  
 3789: 	    if (lc($tagname) eq 'applet' ||
 3790: 		lc($tagname) eq 'object' ||
 3791: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3792: 		) {
 3793: 		foreach my $item (keys(%javafiles)) {
 3794: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3795: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3796: 			&add_filetype($allfiles,$file,$item);
 3797: 		    }
 3798: 		}
 3799: 	    } 
 3800: 	    pop @state;
 3801: 	}
 3802:     }
 3803:     foreach my $id (sort(keys(%flashvars))) {
 3804:         if ($shockwave{$id} ne '') {
 3805:             my @pairs = split(/\&/,$flashvars{$id});
 3806:             foreach my $pair (@pairs) {
 3807:                 my ($key,$value) = split(/\=/,$pair);
 3808:                 if ($key eq 'thumb') {
 3809:                     &add_filetype($allfiles,$value,$key);
 3810:                 } elsif ($key eq 'content') {
 3811:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3812:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3813:                     if ($ext ne '') {
 3814:                         &add_filetype($allfiles,$path.$value,$ext);
 3815:                     }
 3816:                 }
 3817:             }
 3818:         }
 3819:     }
 3820:     return 'ok';
 3821: }
 3822: 
 3823: sub add_filetype {
 3824:     my ($allfiles,$file,$type)=@_;
 3825:     if (exists($allfiles->{$file})) {
 3826: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3827: 	    push(@{$allfiles->{$file}}, &escape($type));
 3828: 	}
 3829:     } else {
 3830: 	@{$allfiles->{$file}} = (&escape($type));
 3831:     }
 3832: }
 3833: 
 3834: sub embedded_dependency {
 3835:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3836:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3837:         if (($identifier ne '') &&
 3838:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3839:             ($pathfrom ne '')) {
 3840:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3841:             foreach my $dep (@{$related->{$identifier}}) {
 3842:                 &add_filetype($allfiles,$path.$dep,'object');
 3843:             }
 3844:         }
 3845:     }
 3846:     return;
 3847: }
 3848: 
 3849: sub removeuploadedurl {
 3850:     my ($url)=@_;	
 3851:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3852:     return &removeuserfile($uname,$udom,$fname);
 3853: }
 3854: 
 3855: sub removeuserfile {
 3856:     my ($docuname,$docudom,$fname)=@_;
 3857:     my $home=&homeserver($docuname,$docudom);    
 3858:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3859:     if ($result eq 'ok') {	
 3860:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3861:             my $metafile = $fname.'.meta';
 3862:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3863: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3864:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3865:             my $sqlresult = 
 3866:                 &update_portfolio_table($docuname,$docudom,$file,
 3867:                                         'portfolio_metadata',$group,
 3868:                                         'delete');
 3869:         }
 3870:     }
 3871:     return $result;
 3872: }
 3873: 
 3874: sub mkdiruserfile {
 3875:     my ($docuname,$docudom,$dir)=@_;
 3876:     my $home=&homeserver($docuname,$docudom);
 3877:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3878: }
 3879: 
 3880: sub renameuserfile {
 3881:     my ($docuname,$docudom,$old,$new)=@_;
 3882:     my $home=&homeserver($docuname,$docudom);
 3883:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3884:                         &escape("$old").':'.&escape("$new"),$home);
 3885:     if ($result eq 'ok') {
 3886:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3887:             my $oldmeta = $old.'.meta';
 3888:             my $newmeta = $new.'.meta';
 3889:             my $metaresult = 
 3890:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3891: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3892:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3893:             my $sqlresult = 
 3894:                 &update_portfolio_table($docuname,$docudom,$file,
 3895:                                         'portfolio_metadata',$group,
 3896:                                         'delete');
 3897:         }
 3898:     }
 3899:     return $result;
 3900: }
 3901: 
 3902: # ------------------------------------------------------------------------- Log
 3903: 
 3904: sub log {
 3905:     my ($dom,$nam,$hom,$what)=@_;
 3906:     return critical("log:$dom:$nam:$what",$hom);
 3907: }
 3908: 
 3909: # ------------------------------------------------------------------ Course Log
 3910: #
 3911: # This routine flushes several buffers of non-mission-critical nature
 3912: #
 3913: 
 3914: sub flushcourselogs {
 3915:     &logthis('Flushing log buffers');
 3916: #
 3917: # course logs
 3918: # This is a log of all transactions in a course, which can be used
 3919: # for data mining purposes
 3920: #
 3921: # It also collects the courseid database, which lists last transaction
 3922: # times and course titles for all courseids
 3923: #
 3924:     my %courseidbuffer=();
 3925:     foreach my $crsid (keys(%courselogs)) {
 3926:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3927: 		          &escape($courselogs{$crsid}),
 3928: 		          $coursehombuf{$crsid}) eq 'ok') {
 3929: 	    delete $courselogs{$crsid};
 3930:         } else {
 3931:             &logthis('Failed to flush log buffer for '.$crsid);
 3932:             if (length($courselogs{$crsid})>40000) {
 3933:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3934:                         " exceeded maximum size, deleting.</font>");
 3935:                delete $courselogs{$crsid};
 3936:             }
 3937:         }
 3938:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3939:             'description' => $coursedescrbuf{$crsid},
 3940:             'inst_code'    => $courseinstcodebuf{$crsid},
 3941:             'type'        => $coursetypebuf{$crsid},
 3942:             'owner'       => $courseownerbuf{$crsid},
 3943:         };
 3944:     }
 3945: #
 3946: # Write course id database (reverse lookup) to homeserver of courses 
 3947: # Is used in pickcourse
 3948: #
 3949:     foreach my $crs_home (keys(%courseidbuffer)) {
 3950:         my $response = &courseidput(&host_domain($crs_home),
 3951:                                     $courseidbuffer{$crs_home},
 3952:                                     $crs_home,'timeonly');
 3953:     }
 3954: #
 3955: # File accesses
 3956: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3957: #
 3958:     foreach my $entry (keys(%accesshash)) {
 3959:         if ($entry =~ /___count$/) {
 3960:             my ($dom,$name);
 3961:             ($dom,$name,undef)=
 3962: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3963:             if (! defined($dom) || $dom eq '' || 
 3964:                 ! defined($name) || $name eq '') {
 3965:                 my $cid = $env{'request.course.id'};
 3966:                 $dom  = $env{'request.'.$cid.'.domain'};
 3967:                 $name = $env{'request.'.$cid.'.num'};
 3968:             }
 3969:             my $value = $accesshash{$entry};
 3970:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3971:             my %temphash=($url => $value);
 3972:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3973:             if ($result eq 'ok') {
 3974:                 delete $accesshash{$entry};
 3975:             }
 3976:         } else {
 3977:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3978:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3979:             my %temphash=($entry => $accesshash{$entry});
 3980:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3981:                 delete $accesshash{$entry};
 3982:             }
 3983:         }
 3984:     }
 3985: #
 3986: # Roles
 3987: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3988: #
 3989:     foreach my $entry (keys(%userrolehash)) {
 3990:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3991: 	    split(/\:/,$entry);
 3992:         if (&Apache::lonnet::put('nohist_userroles',
 3993:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3994:                 $rudom,$runame) eq 'ok') {
 3995: 	    delete $userrolehash{$entry};
 3996:         }
 3997:     }
 3998: #
 3999: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4000: #
 4001:     my %domrolebuffer = ();
 4002:     foreach my $entry (keys(%domainrolehash)) {
 4003:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4004:         if ($domrolebuffer{$rudom}) {
 4005:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4006:                       '='.&escape($domainrolehash{$entry});
 4007:         } else {
 4008:             $domrolebuffer{$rudom}.=&escape($entry).
 4009:                       '='.&escape($domainrolehash{$entry});
 4010:         }
 4011:         delete $domainrolehash{$entry};
 4012:     }
 4013:     foreach my $dom (keys(%domrolebuffer)) {
 4014:         my %servers;
 4015:         if (defined(&domain($dom,'primary'))) {
 4016:             my $primary=&domain($dom,'primary');
 4017:             my $hostname=&hostname($primary);
 4018:             $servers{$primary} = $hostname;
 4019:         } else {
 4020:             %servers = &get_servers($dom,'library');
 4021:         }
 4022: 	foreach my $tryserver (keys(%servers)) {
 4023: 	    if (&reply('domroleput:'.$dom.':'.
 4024: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4025: 	        last;
 4026: 	    } else {
 4027: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4028: 	    }
 4029:         }
 4030:     }
 4031:     $dumpcount++;
 4032: }
 4033: 
 4034: sub courselog {
 4035:     my $what=shift;
 4036:     $what=time.':'.$what;
 4037:     unless ($env{'request.course.id'}) { return ''; }
 4038:     $coursedombuf{$env{'request.course.id'}}=
 4039:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4040:     $coursenumbuf{$env{'request.course.id'}}=
 4041:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4042:     $coursehombuf{$env{'request.course.id'}}=
 4043:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4044:     $coursedescrbuf{$env{'request.course.id'}}=
 4045:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4046:     $courseinstcodebuf{$env{'request.course.id'}}=
 4047:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4048:     $courseownerbuf{$env{'request.course.id'}}=
 4049:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4050:     $coursetypebuf{$env{'request.course.id'}}=
 4051:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4052:     if (defined $courselogs{$env{'request.course.id'}}) {
 4053: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4054:     } else {
 4055: 	$courselogs{$env{'request.course.id'}}.=$what;
 4056:     }
 4057:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4058: 	&flushcourselogs();
 4059:     }
 4060: }
 4061: 
 4062: sub courseacclog {
 4063:     my $fnsymb=shift;
 4064:     unless ($env{'request.course.id'}) { return ''; }
 4065:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4066:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4067:         $what.=':POST';
 4068:         # FIXME: Probably ought to escape things....
 4069: 	foreach my $key (keys(%env)) {
 4070:             if ($key=~/^form\.(.*)/) {
 4071:                 my $formitem = $1;
 4072:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4073:                     $what.=':'.$formitem.'='.$env{$key};
 4074:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4075:                     $what.=':'.$formitem.'='.$env{$key};
 4076:                 }
 4077:             }
 4078:         }
 4079:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4080:         # FIXME: We should not be depending on a form parameter that someone
 4081:         # editing lonsearchcat.pm might change in the future.
 4082:         if ($env{'form.phase'} eq 'course_search') {
 4083:             $what.= ':POST';
 4084:             # FIXME: Probably ought to escape things....
 4085:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4086:                                  'crsdiscuss') {
 4087:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4088:             }
 4089:         }
 4090:     }
 4091:     &courselog($what);
 4092: }
 4093: 
 4094: sub countacc {
 4095:     my $url=&declutter(shift);
 4096:     return if (! defined($url) || $url eq '');
 4097:     unless ($env{'request.course.id'}) { return ''; }
 4098: #
 4099: # Mark that this url was used in this course
 4100: #
 4101:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4102: #
 4103: # Increase the access count for this resource in this child process
 4104: #
 4105:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4106:     $accesshash{$key}++;
 4107: }
 4108: 
 4109: sub linklog {
 4110:     my ($from,$to)=@_;
 4111:     $from=&declutter($from);
 4112:     $to=&declutter($to);
 4113:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4114:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4115: }
 4116: 
 4117: sub statslog {
 4118:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4119:     if ($users<2) { return; }
 4120:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4121:             'course'       => $env{'request.course.id'},
 4122:             'sections'     => '"all"',
 4123:             'num_students' => $users,
 4124:             'part'         => $part,
 4125:             'symb'         => $symb,
 4126:             'mean_tries'   => $av_attempts,
 4127:             'deg_of_diff'  => $degdiff});
 4128:     foreach my $key (keys(%dynstore)) {
 4129:         $accesshash{$key}=$dynstore{$key};
 4130:     }
 4131: }
 4132:   
 4133: sub userrolelog {
 4134:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4135:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4136:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4137:        $userrolehash
 4138:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4139:                     =$tend.':'.$tstart;
 4140:     }
 4141:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4142:        $userrolehash
 4143:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4144:                     =$tend.':'.$tstart;
 4145:     }
 4146:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4147:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4148:        $domainrolehash
 4149:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4150:                     = $tend.':'.$tstart;
 4151:     }
 4152: }
 4153: 
 4154: sub courserolelog {
 4155:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4156:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4157:         my $cdom = $1;
 4158:         my $cnum = $2;
 4159:         my $sec = $3;
 4160:         my $namespace = 'rolelog';
 4161:         my %storehash = (
 4162:                            role    => $trole,
 4163:                            start   => $tstart,
 4164:                            end     => $tend,
 4165:                            selfenroll => $selfenroll,
 4166:                            context    => $context,
 4167:                         );
 4168:         if ($trole eq 'gr') {
 4169:             $namespace = 'groupslog';
 4170:             $storehash{'group'} = $sec;
 4171:         } else {
 4172:             $storehash{'section'} = $sec;
 4173:         }
 4174:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4175:                    $domain,$cnum,$cdom);
 4176:         if (($trole ne 'st') || ($sec ne '')) {
 4177:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4178:         }
 4179:     }
 4180:     return;
 4181: }
 4182: 
 4183: sub domainrolelog {
 4184:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4185:     if ($area =~ m{^/($match_domain)/$}) {
 4186:         my $cdom = $1;
 4187:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4188:         my $namespace = 'rolelog';
 4189:         my %storehash = (
 4190:                            role    => $trole,
 4191:                            start   => $tstart,
 4192:                            end     => $tend,
 4193:                            context => $context,
 4194:                         );
 4195:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4196:                    $domain,$domconfiguser,$cdom);
 4197:     }
 4198:     return;
 4199: 
 4200: }
 4201: 
 4202: sub coauthorrolelog {
 4203:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4204:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4205:         my $audom = $1;
 4206:         my $auname = $2;
 4207:         my $namespace = 'rolelog';
 4208:         my %storehash = (
 4209:                            role    => $trole,
 4210:                            start   => $tstart,
 4211:                            end     => $tend,
 4212:                            context => $context,
 4213:                         );
 4214:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4215:                    $domain,$auname,$audom);
 4216:     }
 4217:     return;
 4218: }
 4219: 
 4220: sub get_course_adv_roles {
 4221:     my ($cid,$codes) = @_;
 4222:     $cid=$env{'request.course.id'} unless (defined($cid));
 4223:     my %coursehash=&coursedescription($cid);
 4224:     my $crstype = &Apache::loncommon::course_type($cid);
 4225:     my %nothide=();
 4226:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4227:         if ($user !~ /:/) {
 4228: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4229:         } else {
 4230:             $nothide{$user}=1;
 4231:         }
 4232:     }
 4233:     my @possdoms = ($coursehash{'domain'});
 4234:     if ($coursehash{'checkforpriv'}) {
 4235:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4236:     }
 4237:     my %returnhash=();
 4238:     my %dumphash=
 4239:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4240:     my $now=time;
 4241:     my %privileged;
 4242:     foreach my $entry (keys(%dumphash)) {
 4243: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4244:         if (($tstart) && ($tstart<0)) { next; }
 4245:         if (($tend) && ($tend<$now)) { next; }
 4246:         if (($tstart) && ($now<$tstart)) { next; }
 4247:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4248: 	if ($username eq '' || $domain eq '') { next; }
 4249:         if ((&privileged($username,$domain,\@possdoms)) &&
 4250:             (!$nothide{$username.':'.$domain})) { next; }
 4251: 	if ($role eq 'cr') { next; }
 4252:         if ($codes) {
 4253:             if ($section) { $role .= ':'.$section; }
 4254:             if ($returnhash{$role}) {
 4255:                 $returnhash{$role}.=','.$username.':'.$domain;
 4256:             } else {
 4257:                 $returnhash{$role}=$username.':'.$domain;
 4258:             }
 4259:         } else {
 4260:             my $key=&plaintext($role,$crstype);
 4261:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4262:             if ($returnhash{$key}) {
 4263: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4264:             } else {
 4265:                 $returnhash{$key}=$username.':'.$domain;
 4266:             }
 4267:         }
 4268:     }
 4269:     return %returnhash;
 4270: }
 4271: 
 4272: sub get_my_roles {
 4273:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4274:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4275:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4276:     my (%dumphash,%nothide);
 4277:     if ($context eq 'userroles') {
 4278:         %dumphash = &dump('roles',$udom,$uname);
 4279:     } else {
 4280:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4281:         if ($hidepriv) {
 4282:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4283:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4284:                 if ($user !~ /:/) {
 4285:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4286:                 } else {
 4287:                     $nothide{$user} = 1;
 4288:                 }
 4289:             }
 4290:         }
 4291:     }
 4292:     my %returnhash=();
 4293:     my $now=time;
 4294:     my %privileged;
 4295:     foreach my $entry (keys(%dumphash)) {
 4296:         my ($role,$tend,$tstart);
 4297:         if ($context eq 'userroles') {
 4298:             next if ($entry =~ /^rolesdef/);
 4299: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4300:         } else {
 4301:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4302:         }
 4303:         if (($tstart) && ($tstart<0)) { next; }
 4304:         my $status = 'active';
 4305:         if (($tend) && ($tend<=$now)) {
 4306:             $status = 'previous';
 4307:         } 
 4308:         if (($tstart) && ($now<$tstart)) {
 4309:             $status = 'future';
 4310:         }
 4311:         if (ref($types) eq 'ARRAY') {
 4312:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4313:                 next;
 4314:             } 
 4315:         } else {
 4316:             if ($status ne 'active') {
 4317:                 next;
 4318:             }
 4319:         }
 4320:         my ($rolecode,$username,$domain,$section,$area);
 4321:         if ($context eq 'userroles') {
 4322:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4323:             (undef,$domain,$username,$section) = split(/\//,$area);
 4324:         } else {
 4325:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4326:         }
 4327:         if (ref($roledoms) eq 'ARRAY') {
 4328:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4329:                 next;
 4330:             }
 4331:         }
 4332:         if (ref($roles) eq 'ARRAY') {
 4333:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4334:                 if ($role =~ /^cr\//) {
 4335:                     if (!grep(/^cr$/,@{$roles})) {
 4336:                         next;
 4337:                     }
 4338:                 } elsif ($role =~ /^gr\//) {
 4339:                     if (!grep(/^gr$/,@{$roles})) {
 4340:                         next;
 4341:                     }
 4342:                 } else {
 4343:                     next;
 4344:                 }
 4345:             }
 4346:         }
 4347:         if ($hidepriv) {
 4348:             my @privroles = ('dc','su');
 4349:             if ($context eq 'userroles') {
 4350:                 next if (grep(/^\Q$role\E$/,@privroles));
 4351:             } else {
 4352:                 my $possdoms = [$domain];
 4353:                 if (ref($roledoms) eq 'ARRAY') {
 4354:                    push(@{$possdoms},@{$roledoms});
 4355:                 }
 4356:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4357:                     if (!$nothide{$username.':'.$domain}) {
 4358:                         next;
 4359:                     }
 4360:                 }
 4361:             }
 4362:         }
 4363:         if ($withsec) {
 4364:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4365:                 $tstart.':'.$tend;
 4366:         } else {
 4367:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4368:         }
 4369:     }
 4370:     return %returnhash;
 4371: }
 4372: 
 4373: sub get_all_adhocroles {
 4374:     my ($dom) = @_;
 4375:     my @roles_by_num = ();
 4376:     my %domdefaults = &get_domain_defaults($dom);
 4377:     my (%description,%access_in_dom,%access_info);
 4378:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4379:         my $count = 0;
 4380:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4381:         my %ordered;
 4382:         foreach my $role (sort(keys(%domcurrent))) {
 4383:             my ($order,$desc,$access_in_dom);
 4384:             if (ref($domcurrent{$role}) eq 'HASH') {
 4385:                 $order = $domcurrent{$role}{'order'};
 4386:                 $desc = $domcurrent{$role}{'desc'};
 4387:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4388:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4389:             }
 4390:             if ($order eq '') {
 4391:                 $order = $count;
 4392:             }
 4393:             $ordered{$order} = $role;
 4394:             if ($desc ne '') {
 4395:                 $description{$role} = $desc;
 4396:             } else {
 4397:                 $description{$role}= $role;
 4398:             }
 4399:             $count++;
 4400:         }
 4401:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4402:             push(@roles_by_num,$ordered{$item});
 4403:         }
 4404:     }
 4405:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4406: }
 4407: 
 4408: sub get_my_adhocroles {
 4409:     my ($cid,$checkreg) = @_;
 4410:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4411:     if ($env{'request.course.id'} eq $cid) {
 4412:         $cdom = $env{'course.'.$cid.'.domain'};
 4413:         $cnum = $env{'course.'.$cid.'.num'};
 4414:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4415:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4416:         $cdom = $1;
 4417:         $cnum = $2;
 4418:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4419:                                      $cdom,$cnum);
 4420:     }
 4421:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4422:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4423:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4424:         if ($rosterhash{$user} ne '') {
 4425:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4426:             return ([],{}) if ($type eq 'auto');
 4427:         }
 4428:     }
 4429:     if (($cdom ne '') && ($cnum ne ''))  {
 4430:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4431:             my $then=$env{'user.login.time'};
 4432:             my $update=$env{'user.update.time'};
 4433:             if (!$update) {
 4434:                 $update = $then;
 4435:             }
 4436:             my @liveroles;
 4437:             foreach my $role ('dh','da') {
 4438:                 if ($env{"user.role.$role./$cdom/"}) {
 4439:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4440:                     my $limit = $update;
 4441:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4442:                         $limit = $then;
 4443:                     }
 4444:                     my $activerole = 1;
 4445:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4446:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4447:                     if ($activerole) {
 4448:                         push(@liveroles,$role);
 4449:                     }
 4450:                 }
 4451:             }
 4452:             if (@liveroles) {
 4453:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4454:                     my ($accessref,$accessinfo,%access_in_dom);
 4455:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4456:                     if (ref($roles_by_num) eq 'ARRAY') {
 4457:                         if (@{$roles_by_num}) {
 4458:                             my %settings;
 4459:                             if ($env{'request.course.id'} eq $cid) {
 4460:                                 foreach my $envkey (keys(%env)) {
 4461:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4462:                                         $settings{$1} = $env{$envkey};
 4463:                                     }
 4464:                                 }
 4465:                             } else {
 4466:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4467:                             }
 4468:                             my %setincrs;
 4469:                             if ($settings{'internal.adhocaccess'}) {
 4470:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4471:                             }
 4472:                             my @statuses;
 4473:                             if ($env{'environment.inststatus'}) {
 4474:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4475:                             }
 4476:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4477:                             if (ref($accessref) eq 'HASH') {
 4478:                                 %access_in_dom = %{$accessref};
 4479:                             }
 4480:                             foreach my $role (@{$roles_by_num}) {
 4481:                                 my ($curraccess,@okstatus,@personnel);
 4482:                                 if ($setincrs{$role}) {
 4483:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4484:                                     if ($curraccess eq 'status') {
 4485:                                         @okstatus = split(/\&/,$rest);
 4486:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4487:                                         @personnel = split(/\&/,$rest);
 4488:                                     }
 4489:                                 } else {
 4490:                                     $curraccess = $access_in_dom{$role};
 4491:                                     if (ref($accessinfo) eq 'HASH') {
 4492:                                         if ($curraccess eq 'status') {
 4493:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4494:                                                 @okstatus = @{$accessinfo->{$role}};
 4495:                                             }
 4496:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4497:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4498:                                                 @personnel = @{$accessinfo->{$role}};
 4499:                                             }
 4500:                                         }
 4501:                                     }
 4502:                                 }
 4503:                                 if ($curraccess eq 'none') {
 4504:                                     next;
 4505:                                 } elsif ($curraccess eq 'all') {
 4506:                                     push(@possroles,$role);
 4507:                                 } elsif ($curraccess eq 'dh') {
 4508:                                     if (grep(/^dh$/,@liveroles)) {
 4509:                                         push(@possroles,$role);
 4510:                                     } else {
 4511:                                         next;
 4512:                                     }
 4513:                                 } elsif ($curraccess eq 'da') {
 4514:                                     if (grep(/^da$/,@liveroles)) {
 4515:                                         push(@possroles,$role);
 4516:                                     } else {
 4517:                                         next;
 4518:                                     }
 4519:                                 } elsif ($curraccess eq 'status') {
 4520:                                     if (@okstatus) {
 4521:                                         if (!@statuses) {
 4522:                                             if (grep(/^default$/,@okstatus)) {
 4523:                                                 push(@possroles,$role);
 4524:                                             }
 4525:                                         } else {
 4526:                                             foreach my $status (@okstatus) {
 4527:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 4528:                                                     push(@possroles,$role);
 4529:                                                     last;
 4530:                                                 }
 4531:                                             }
 4532:                                         }
 4533:                                     }
 4534:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4535:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 4536:                                         if ($curraccess eq 'exc') {
 4537:                                             push(@possroles,$role);
 4538:                                         }
 4539:                                     } elsif ($curraccess eq 'inc') {
 4540:                                         push(@possroles,$role);
 4541:                                     }
 4542:                                 }
 4543:                             }
 4544:                         }
 4545:                     }
 4546:                 }
 4547:             }
 4548:         }
 4549:     }
 4550:     unless (ref($description) eq 'HASH') {
 4551:         if (ref($roles_by_num) eq 'ARRAY') {
 4552:             my %desc;
 4553:             map { $desc{$_} = $_; } (@{$roles_by_num});
 4554:             $description = \%desc;
 4555:         } else {
 4556:             $description = {};
 4557:         }
 4558:     }
 4559:     return (\@possroles,$description);
 4560: }
 4561: 
 4562: # ----------------------------------------------------- Frontpage Announcements
 4563: #
 4564: #
 4565: 
 4566: sub postannounce {
 4567:     my ($server,$text)=@_;
 4568:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4569:     unless ($text=~/\w/) { $text=''; }
 4570:     return &reply('setannounce:'.&escape($text),$server);
 4571: }
 4572: 
 4573: sub getannounce {
 4574: 
 4575:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4576: 	my $announcement='';
 4577: 	while (my $line = <$fh>) { $announcement .= $line; }
 4578: 	close($fh);
 4579: 	if ($announcement=~/\w/) { 
 4580: 	    return 
 4581:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4582:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4583: 	} else {
 4584: 	    return '';
 4585: 	}
 4586:     } else {
 4587: 	return '';
 4588:     }
 4589: }
 4590: 
 4591: # ---------------------------------------------------------- Course ID routines
 4592: # Deal with domain's nohist_courseid.db files
 4593: #
 4594: 
 4595: sub courseidput {
 4596:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4597:     return unless (ref($storehash) eq 'HASH');
 4598:     my $outcome;
 4599:     if ($caller eq 'timeonly') {
 4600:         my $cids = '';
 4601:         foreach my $item (keys(%$storehash)) {
 4602:             $cids.=&escape($item).'&';
 4603:         }
 4604:         $cids=~s/\&$//;
 4605:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4606:                           $coursehome);       
 4607:     } else {
 4608:         my $items = '';
 4609:         foreach my $item (keys(%$storehash)) {
 4610:             $items.= &escape($item).'='.
 4611:                      &freeze_escape($$storehash{$item}).'&';
 4612:         }
 4613:         $items=~s/\&$//;
 4614:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4615:                           $coursehome);
 4616:     }
 4617:     if ($outcome eq 'unknown_cmd') {
 4618:         my $what;
 4619:         foreach my $cid (keys(%$storehash)) {
 4620:             $what .= &escape($cid).'=';
 4621:             foreach my $item ('description','inst_code','owner','type') {
 4622:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4623:             }
 4624:             $what =~ s/\:$/&/;
 4625:         }
 4626:         $what =~ s/\&$//;  
 4627:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4628:     } else {
 4629:         return $outcome;
 4630:     }
 4631: }
 4632: 
 4633: sub courseiddump {
 4634:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4635:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4636:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4637:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4638:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 4639:     my $as_hash = 1;
 4640:     my %returnhash;
 4641:     if (!$domfilter) { $domfilter=''; }
 4642:     my %libserv = &all_library();
 4643:     foreach my $tryserver (keys(%libserv)) {
 4644:         if ( (  $hostidflag == 1 
 4645: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4646: 	     || (!defined($hostidflag)) ) {
 4647: 
 4648: 	    if (($domfilter eq '') ||
 4649: 		(&host_domain($tryserver) eq $domfilter)) {
 4650:                 my $rep;
 4651:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
 4652:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
 4653:                         join(":", (&host_domain($tryserver), $sincefilter,
 4654:                                 &escape($descfilter), &escape($instcodefilter),
 4655:                                 &escape($ownerfilter), &escape($coursefilter),
 4656:                                 &escape($typefilter), &escape($regexp_ok),
 4657:                                 $as_hash, &escape($selfenrollonly),
 4658:                                 &escape($catfilter), $showhidden, $caller,
 4659:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
 4660:                                 &escape($createdbefore), &escape($createdafter),
 4661:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 4662:                                 $reqcrsdom,&escape($reqinstcode))));
 4663:                 } else {
 4664:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4665:                              $sincefilter.':'.&escape($descfilter).':'.
 4666:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4667:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4668:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4669:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4670:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4671:                              &escape($cc_clone).':'.$cloneonly.':'.
 4672:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4673:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 4674:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 4675:                 }
 4676: 
 4677:                 my @pairs=split(/\&/,$rep);
 4678:                 foreach my $item (@pairs) {
 4679:                     my ($key,$value)=split(/\=/,$item,2);
 4680:                     $key = &unescape($key);
 4681:                     next if ($key =~ /^error: 2 /);
 4682:                     my $result = &thaw_unescape($value);
 4683:                     if (ref($result) eq 'HASH') {
 4684:                         $returnhash{$key}=$result;
 4685:                     } else {
 4686:                         my @responses = split(/:/,$value);
 4687:                         my @items = ('description','inst_code','owner','type');
 4688:                         for (my $i=0; $i<@responses; $i++) {
 4689:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4690:                         }
 4691:                     }
 4692:                 }
 4693:             }
 4694:         }
 4695:     }
 4696:     return %returnhash;
 4697: }
 4698: 
 4699: sub courselastaccess {
 4700:     my ($cdom,$cnum,$hostidref) = @_;
 4701:     my %returnhash;
 4702:     if ($cdom && $cnum) {
 4703:         my $chome = &homeserver($cnum,$cdom);
 4704:         if ($chome ne 'no_host') {
 4705:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4706:             &extract_lastaccess(\%returnhash,$rep);
 4707:         }
 4708:     } else {
 4709:         if (!$cdom) { $cdom=''; }
 4710:         my %libserv = &all_library();
 4711:         foreach my $tryserver (keys(%libserv)) {
 4712:             if (ref($hostidref) eq 'ARRAY') {
 4713:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4714:             } 
 4715:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4716:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4717:                 &extract_lastaccess(\%returnhash,$rep);
 4718:             }
 4719:         }
 4720:     }
 4721:     return %returnhash;
 4722: }
 4723: 
 4724: sub extract_lastaccess {
 4725:     my ($returnhash,$rep) = @_;
 4726:     if (ref($returnhash) eq 'HASH') {
 4727:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4728:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4729:                  $rep eq '') {
 4730:             my @pairs=split(/\&/,$rep);
 4731:             foreach my $item (@pairs) {
 4732:                 my ($key,$value)=split(/\=/,$item,2);
 4733:                 $key = &unescape($key);
 4734:                 next if ($key =~ /^error: 2 /);
 4735:                 $returnhash->{$key} = &thaw_unescape($value);
 4736:             }
 4737:         }
 4738:     }
 4739:     return;
 4740: }
 4741: 
 4742: # ---------------------------------------------------------- DC e-mail
 4743: 
 4744: sub dcmailput {
 4745:     my ($domain,$msgid,$message,$server)=@_;
 4746:     my $status = &Apache::lonnet::critical(
 4747:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4748:        &escape($message),$server);
 4749:     return $status;
 4750: }
 4751: 
 4752: sub dcmaildump {
 4753:     my ($dom,$startdate,$enddate,$senders) = @_;
 4754:     my %returnhash=();
 4755: 
 4756:     if (defined(&domain($dom,'primary'))) {
 4757:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4758:                                                          &escape($enddate).':';
 4759: 	my @esc_senders=map { &escape($_)} @$senders;
 4760: 	$cmd.=&escape(join('&',@esc_senders));
 4761: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4762:             my ($key,$value) = split(/\=/,$line,2);
 4763:             if (($key) && ($value)) {
 4764:                 $returnhash{&unescape($key)} = &unescape($value);
 4765:             }
 4766:         }
 4767:     }
 4768:     return %returnhash;
 4769: }
 4770: # ---------------------------------------------------------- Domain roles
 4771: 
 4772: sub get_domain_roles {
 4773:     my ($dom,$roles,$startdate,$enddate)=@_;
 4774:     if ((!defined($startdate)) || ($startdate eq '')) {
 4775:         $startdate = '.';
 4776:     }
 4777:     if ((!defined($enddate)) || ($enddate eq '')) {
 4778:         $enddate = '.';
 4779:     }
 4780:     my $rolelist;
 4781:     if (ref($roles) eq 'ARRAY') {
 4782:         $rolelist = join('&',@{$roles});
 4783:     }
 4784:     my %personnel = ();
 4785: 
 4786:     my %servers = &get_servers($dom,'library');
 4787:     foreach my $tryserver (keys(%servers)) {
 4788: 	%{$personnel{$tryserver}}=();
 4789: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4790: 					    &escape($startdate).':'.
 4791: 					    &escape($enddate).':'.
 4792: 					    &escape($rolelist), $tryserver))) {
 4793: 	    my ($key,$value) = split(/\=/,$line,2);
 4794: 	    if (($key) && ($value)) {
 4795: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4796: 	    }
 4797: 	}
 4798:     }
 4799:     return %personnel;
 4800: }
 4801: 
 4802: sub get_active_domroles {
 4803:     my ($dom,$roles) = @_;
 4804:     return () unless (ref($roles) eq 'ARRAY');
 4805:     my $now = time;
 4806:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 4807:     my %domroles;
 4808:     foreach my $server (keys(%dompersonnel)) {
 4809:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 4810:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 4811:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 4812:         }
 4813:     }
 4814:     return %domroles;
 4815: }
 4816: 
 4817: # ----------------------------------------------------------- Interval timing 
 4818: 
 4819: {
 4820: # Caches needed for speedup of navmaps
 4821: # We don't want to cache this for very long at all (5 seconds at most)
 4822: # 
 4823: # The user for whom we cache
 4824: my $cachedkey='';
 4825: # The cached times for this user
 4826: my %cachedtimes=();
 4827: # When this was last done
 4828: my $cachedtime='';
 4829: 
 4830: sub load_all_first_access {
 4831:     my ($uname,$udom,$ignorecache)=@_;
 4832:     if (($cachedkey eq $uname.':'.$udom) &&
 4833:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 4834:         (!$ignorecache)) {
 4835:         return;
 4836:     }
 4837:     $cachedtime=time;
 4838:     $cachedkey=$uname.':'.$udom;
 4839:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4840: }
 4841: 
 4842: sub get_first_access {
 4843:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 4844:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4845:     if ($argsymb) { $symb=$argsymb; }
 4846:     my ($map,$id,$res)=&decode_symb($symb);
 4847:     if ($argmap) { $map = $argmap; }
 4848:     if ($type eq 'course') {
 4849: 	$res='course';
 4850:     } elsif ($type eq 'map') {
 4851: 	$res=&symbread($map);
 4852:     } else {
 4853: 	$res=$symb;
 4854:     }
 4855:     &load_all_first_access($uname,$udom,$ignorecache);
 4856:     return $cachedtimes{"$courseid\0$res"};
 4857: }
 4858: 
 4859: sub set_first_access {
 4860:     my ($type,$interval)=@_;
 4861:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4862:     my ($map,$id,$res)=&decode_symb($symb);
 4863:     if ($type eq 'course') {
 4864: 	$res='course';
 4865:     } elsif ($type eq 'map') {
 4866: 	$res=&symbread($map);
 4867:     } else {
 4868: 	$res=$symb;
 4869:     }
 4870:     $cachedkey='';
 4871:     my $firstaccess=&get_first_access($type,$symb,$map);
 4872:     if (!$firstaccess) {
 4873:         my $start = time;
 4874: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4875:                           $udom,$uname);
 4876:         if ($putres eq 'ok') {
 4877:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4878:                  $udom,$uname); 
 4879:             &appenv(
 4880:                      {
 4881:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4882:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4883:                      }
 4884:                   );
 4885:         }
 4886:         return $putres;
 4887:     }
 4888:     return 'already_set';
 4889: }
 4890: }
 4891: 
 4892: sub checkout {
 4893:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 4894:     my $now=time;
 4895:     my $lonhost=$perlvar{'lonHostID'};
 4896:     my $infostr=&escape(
 4897:                  'CHECKOUTTOKEN&'.
 4898:                  $tuname.'&'.
 4899:                  $tudom.'&'.
 4900:                  $tcrsid.'&'.
 4901:                  $symb.'&'.
 4902:                  $now.'&'.$ENV{'REMOTE_ADDR'});
 4903:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 4904:     if ($token=~/^error\:/) {
 4905:         &logthis("<font color=\"blue\">WARNING: ".
 4906:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 4907:                  "</font>");
 4908:         return '';
 4909:     }
 4910: 
 4911:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 4912:     $token=~tr/a-z/A-Z/;
 4913: 
 4914:     my %infohash=('resource.0.outtoken' => $token,
 4915:                   'resource.0.checkouttime' => $now,
 4916:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 4917: 
 4918:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 4919:        return '';
 4920:     } else {
 4921:         &logthis("<font color=\"blue\">WARNING: ".
 4922:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 4923:                  "</font>");
 4924:     }
 4925: 
 4926:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 4927:                          &escape('Checkout '.$infostr.' - '.
 4928:                                                  $token)) ne 'ok') {
 4929:         return '';
 4930:     } else {
 4931:         &logthis("<font color=\"blue\">WARNING: ".
 4932:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 4933:                  "</font>");
 4934:     }
 4935:     return $token;
 4936: }
 4937: 
 4938: # ------------------------------------------------------------ Check in an item
 4939: 
 4940: sub checkin {
 4941:     my $token=shift;
 4942:     my $now=time;
 4943:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 4944:     $lonhost=~tr/A-Z/a-z/;
 4945:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 4946:     $dtoken=~s/\W/\_/g;
 4947:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 4948:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 4949: 
 4950:     unless (($tuname) && ($tudom)) {
 4951:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 4952:         return '';
 4953:     }
 4954: 
 4955:     unless (&allowed('mgr',$tcrsid)) {
 4956:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 4957:                  $env{'user.name'}.' - '.$env{'user.domain'});
 4958:         return '';
 4959:     }
 4960: 
 4961:     my %infohash=('resource.0.intoken' => $token,
 4962:                   'resource.0.checkintime' => $now,
 4963:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 4964: 
 4965:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 4966:        return '';
 4967:     }
 4968: 
 4969:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 4970:                          &escape('Checkin - '.$token)) ne 'ok') {
 4971:         return '';
 4972:     }
 4973: 
 4974:     return ($symb,$tuname,$tudom,$tcrsid);
 4975: }
 4976: 
 4977: # --------------------------------------------- Set Expire Date for Spreadsheet
 4978: 
 4979: sub expirespread {
 4980:     my ($uname,$udom,$stype,$usymb)=@_;
 4981:     my $cid=$env{'request.course.id'}; 
 4982:     if ($cid) {
 4983:        my $now=time;
 4984:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4985:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4986:                             $env{'course.'.$cid.'.num'}.
 4987: 	        	    ':nohist_expirationdates:'.
 4988:                             &escape($key).'='.$now,
 4989:                             $env{'course.'.$cid.'.home'})
 4990:     }
 4991:     return 'ok';
 4992: }
 4993: 
 4994: # ----------------------------------------------------- Devalidate Spreadsheets
 4995: 
 4996: sub devalidate {
 4997:     my ($symb,$uname,$udom)=@_;
 4998:     my $cid=$env{'request.course.id'}; 
 4999:     if ($cid) {
 5000:         # delete the stored spreadsheets for
 5001:         # - the student level sheet of this user in course's homespace
 5002:         # - the assessment level sheet for this resource 
 5003:         #   for this user in user's homespace
 5004: 	# - current conditional state info
 5005: 	my $key=$uname.':'.$udom.':';
 5006:         my $status=
 5007: 	    &del('nohist_calculatedsheets',
 5008: 		 [$key.'studentcalc:'],
 5009: 		 $env{'course.'.$cid.'.domain'},
 5010: 		 $env{'course.'.$cid.'.num'})
 5011: 		.' '.
 5012: 	    &del('nohist_calculatedsheets_'.$cid,
 5013: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5014:         unless ($status eq 'ok ok') {
 5015:            &logthis('Could not devalidate spreadsheet '.
 5016:                     $uname.' at '.$udom.' for '.
 5017: 		    $symb.': '.$status);
 5018:         }
 5019: 	&delenv('user.state.'.$cid);
 5020:     }
 5021: }
 5022: 
 5023: sub get_scalar {
 5024:     my ($string,$end) = @_;
 5025:     my $value;
 5026:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5027: 	$value = $1;
 5028:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5029: 	$value = $1;
 5030:     }
 5031:     return &unescape($value);
 5032: }
 5033: 
 5034: sub array2str {
 5035:   my (@array) = @_;
 5036:   my $result=&arrayref2str(\@array);
 5037:   $result=~s/^__ARRAY_REF__//;
 5038:   $result=~s/__END_ARRAY_REF__$//;
 5039:   return $result;
 5040: }
 5041: 
 5042: sub arrayref2str {
 5043:   my ($arrayref) = @_;
 5044:   my $result='__ARRAY_REF__';
 5045:   foreach my $elem (@$arrayref) {
 5046:     if(ref($elem) eq 'ARRAY') {
 5047:       $result.=&arrayref2str($elem).'&';
 5048:     } elsif(ref($elem) eq 'HASH') {
 5049:       $result.=&hashref2str($elem).'&';
 5050:     } elsif(ref($elem)) {
 5051:       #print("Got a ref of ".(ref($elem))." skipping.");
 5052:     } else {
 5053:       $result.=&escape($elem).'&';
 5054:     }
 5055:   }
 5056:   $result=~s/\&$//;
 5057:   $result .= '__END_ARRAY_REF__';
 5058:   return $result;
 5059: }
 5060: 
 5061: sub hash2str {
 5062:   my (%hash) = @_;
 5063:   my $result=&hashref2str(\%hash);
 5064:   $result=~s/^__HASH_REF__//;
 5065:   $result=~s/__END_HASH_REF__$//;
 5066:   return $result;
 5067: }
 5068: 
 5069: sub hashref2str {
 5070:   my ($hashref)=@_;
 5071:   my $result='__HASH_REF__';
 5072:   foreach my $key (sort(keys(%$hashref))) {
 5073:     if (ref($key) eq 'ARRAY') {
 5074:       $result.=&arrayref2str($key).'=';
 5075:     } elsif (ref($key) eq 'HASH') {
 5076:       $result.=&hashref2str($key).'=';
 5077:     } elsif (ref($key)) {
 5078:       $result.='=';
 5079:       #print("Got a ref of ".(ref($key))." skipping.");
 5080:     } else {
 5081: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5082:     }
 5083: 
 5084:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5085:       $result.=&arrayref2str($hashref->{$key}).'&';
 5086:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5087:       $result.=&hashref2str($hashref->{$key}).'&';
 5088:     } elsif(ref($hashref->{$key})) {
 5089:        $result.='&';
 5090:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5091:     } else {
 5092:       $result.=&escape($hashref->{$key}).'&';
 5093:     }
 5094:   }
 5095:   $result=~s/\&$//;
 5096:   $result .= '__END_HASH_REF__';
 5097:   return $result;
 5098: }
 5099: 
 5100: sub str2hash {
 5101:     my ($string)=@_;
 5102:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5103:     return %$hash;
 5104: }
 5105: 
 5106: sub str2hashref {
 5107:   my ($string) = @_;
 5108: 
 5109:   my %hash;
 5110: 
 5111:   if($string !~ /^__HASH_REF__/) {
 5112:       if (! ($string eq '' || !defined($string))) {
 5113: 	  $hash{'error'}='Not hash reference';
 5114:       }
 5115:       return (\%hash, $string);
 5116:   }
 5117: 
 5118:   $string =~ s/^__HASH_REF__//;
 5119: 
 5120:   while($string !~ /^__END_HASH_REF__/) {
 5121:       #key
 5122:       my $key='';
 5123:       if($string =~ /^__HASH_REF__/) {
 5124:           ($key, $string)=&str2hashref($string);
 5125:           if(defined($key->{'error'})) {
 5126:               $hash{'error'}='Bad data';
 5127:               return (\%hash, $string);
 5128:           }
 5129:       } elsif($string =~ /^__ARRAY_REF__/) {
 5130:           ($key, $string)=&str2arrayref($string);
 5131:           if($key->[0] eq 'Array reference error') {
 5132:               $hash{'error'}='Bad data';
 5133:               return (\%hash, $string);
 5134:           }
 5135:       } else {
 5136:           $string =~ s/^(.*?)=//;
 5137: 	  $key=&unescape($1);
 5138:       }
 5139:       $string =~ s/^=//;
 5140: 
 5141:       #value
 5142:       my $value='';
 5143:       if($string =~ /^__HASH_REF__/) {
 5144:           ($value, $string)=&str2hashref($string);
 5145:           if(defined($value->{'error'})) {
 5146:               $hash{'error'}='Bad data';
 5147:               return (\%hash, $string);
 5148:           }
 5149:       } elsif($string =~ /^__ARRAY_REF__/) {
 5150:           ($value, $string)=&str2arrayref($string);
 5151:           if($value->[0] eq 'Array reference error') {
 5152:               $hash{'error'}='Bad data';
 5153:               return (\%hash, $string);
 5154:           }
 5155:       } else {
 5156: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5157:       }
 5158:       $string =~ s/^&//;
 5159: 
 5160:       $hash{$key}=$value;
 5161:   }
 5162: 
 5163:   $string =~ s/^__END_HASH_REF__//;
 5164: 
 5165:   return (\%hash, $string);
 5166: }
 5167: 
 5168: sub str2array {
 5169:     my ($string)=@_;
 5170:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5171:     return @$array;
 5172: }
 5173: 
 5174: sub str2arrayref {
 5175:   my ($string) = @_;
 5176:   my @array;
 5177: 
 5178:   if($string !~ /^__ARRAY_REF__/) {
 5179:       if (! ($string eq '' || !defined($string))) {
 5180: 	  $array[0]='Array reference error';
 5181:       }
 5182:       return (\@array, $string);
 5183:   }
 5184: 
 5185:   $string =~ s/^__ARRAY_REF__//;
 5186: 
 5187:   while($string !~ /^__END_ARRAY_REF__/) {
 5188:       my $value='';
 5189:       if($string =~ /^__HASH_REF__/) {
 5190:           ($value, $string)=&str2hashref($string);
 5191:           if(defined($value->{'error'})) {
 5192:               $array[0] ='Array reference error';
 5193:               return (\@array, $string);
 5194:           }
 5195:       } elsif($string =~ /^__ARRAY_REF__/) {
 5196:           ($value, $string)=&str2arrayref($string);
 5197:           if($value->[0] eq 'Array reference error') {
 5198:               $array[0] ='Array reference error';
 5199:               return (\@array, $string);
 5200:           }
 5201:       } else {
 5202: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5203:       }
 5204:       $string =~ s/^&//;
 5205: 
 5206:       push(@array, $value);
 5207:   }
 5208: 
 5209:   $string =~ s/^__END_ARRAY_REF__//;
 5210: 
 5211:   return (\@array, $string);
 5212: }
 5213: 
 5214: # -------------------------------------------------------------------Temp Store
 5215: 
 5216: sub tmpreset {
 5217:   my ($symb,$namespace,$domain,$stuname) = @_;
 5218:   if (!$symb) {
 5219:     $symb=&symbread();
 5220:     if (!$symb) { $symb= $env{'request.url'}; }
 5221:   }
 5222:   $symb=escape($symb);
 5223: 
 5224:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5225:   $namespace=~s/\//\_/g;
 5226:   $namespace=~s/\W//g;
 5227: 
 5228:   if (!$domain) { $domain=$env{'user.domain'}; }
 5229:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5230:   if ($domain eq 'public' && $stuname eq 'public') {
 5231:       $stuname=$ENV{'REMOTE_ADDR'};
 5232:   }
 5233:   my $path=LONCAPA::tempdir();
 5234:   my %hash;
 5235:   if (tie(%hash,'GDBM_File',
 5236: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5237: 	  &GDBM_WRCREAT(),0640)) {
 5238:     foreach my $key (keys(%hash)) {
 5239:       if ($key=~ /:$symb/) {
 5240: 	delete($hash{$key});
 5241:       }
 5242:     }
 5243:   }
 5244: }
 5245: 
 5246: sub tmpstore {
 5247:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5248: 
 5249:   if (!$symb) {
 5250:     $symb=&symbread();
 5251:     if (!$symb) { $symb= $env{'request.url'}; }
 5252:   }
 5253:   $symb=escape($symb);
 5254: 
 5255:   if (!$namespace) {
 5256:     # I don't think we would ever want to store this for a course.
 5257:     # it seems this will only be used if we don't have a course.
 5258:     #$namespace=$env{'request.course.id'};
 5259:     #if (!$namespace) {
 5260:       $namespace=$env{'request.state'};
 5261:     #}
 5262:   }
 5263:   $namespace=~s/\//\_/g;
 5264:   $namespace=~s/\W//g;
 5265:   if (!$domain) { $domain=$env{'user.domain'}; }
 5266:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5267:   if ($domain eq 'public' && $stuname eq 'public') {
 5268:       $stuname=$ENV{'REMOTE_ADDR'};
 5269:   }
 5270:   my $now=time;
 5271:   my %hash;
 5272:   my $path=LONCAPA::tempdir();
 5273:   if (tie(%hash,'GDBM_File',
 5274: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5275: 	  &GDBM_WRCREAT(),0640)) {
 5276:     $hash{"version:$symb"}++;
 5277:     my $version=$hash{"version:$symb"};
 5278:     my $allkeys=''; 
 5279:     foreach my $key (keys(%$storehash)) {
 5280:       $allkeys.=$key.':';
 5281:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5282:     }
 5283:     $hash{"$version:$symb:timestamp"}=$now;
 5284:     $allkeys.='timestamp';
 5285:     $hash{"$version:keys:$symb"}=$allkeys;
 5286:     if (untie(%hash)) {
 5287:       return 'ok';
 5288:     } else {
 5289:       return "error:$!";
 5290:     }
 5291:   } else {
 5292:     return "error:$!";
 5293:   }
 5294: }
 5295: 
 5296: # -----------------------------------------------------------------Temp Restore
 5297: 
 5298: sub tmprestore {
 5299:   my ($symb,$namespace,$domain,$stuname) = @_;
 5300: 
 5301:   if (!$symb) {
 5302:     $symb=&symbread();
 5303:     if (!$symb) { $symb= $env{'request.url'}; }
 5304:   }
 5305:   $symb=escape($symb);
 5306: 
 5307:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5308: 
 5309:   if (!$domain) { $domain=$env{'user.domain'}; }
 5310:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5311:   if ($domain eq 'public' && $stuname eq 'public') {
 5312:       $stuname=$ENV{'REMOTE_ADDR'};
 5313:   }
 5314:   my %returnhash;
 5315:   $namespace=~s/\//\_/g;
 5316:   $namespace=~s/\W//g;
 5317:   my %hash;
 5318:   my $path=LONCAPA::tempdir();
 5319:   if (tie(%hash,'GDBM_File',
 5320: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5321: 	  &GDBM_READER(),0640)) {
 5322:     my $version=$hash{"version:$symb"};
 5323:     $returnhash{'version'}=$version;
 5324:     my $scope;
 5325:     for ($scope=1;$scope<=$version;$scope++) {
 5326:       my $vkeys=$hash{"$scope:keys:$symb"};
 5327:       my @keys=split(/:/,$vkeys);
 5328:       my $key;
 5329:       $returnhash{"$scope:keys"}=$vkeys;
 5330:       foreach $key (@keys) {
 5331: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5332: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5333:       }
 5334:     }
 5335:     if (!(untie(%hash))) {
 5336:       return "error:$!";
 5337:     }
 5338:   } else {
 5339:     return "error:$!";
 5340:   }
 5341:   return %returnhash;
 5342: }
 5343: 
 5344: # ----------------------------------------------------------------------- Store
 5345: 
 5346: sub store {
 5347:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5348:     my $home='';
 5349: 
 5350:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5351: 
 5352:     $symb=&symbclean($symb);
 5353:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5354: 
 5355:     if (!$domain) { $domain=$env{'user.domain'}; }
 5356:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5357: 
 5358:     &devalidate($symb,$stuname,$domain);
 5359: 
 5360:     $symb=escape($symb);
 5361:     if (!$namespace) { 
 5362:        unless ($namespace=$env{'request.course.id'}) { 
 5363:           return ''; 
 5364:        } 
 5365:     }
 5366:     if (!$home) { $home=$env{'user.home'}; }
 5367: 
 5368:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5369:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5370: 
 5371:     my $namevalue='';
 5372:     foreach my $key (keys(%$storehash)) {
 5373:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5374:     }
 5375:     $namevalue=~s/\&$//;
 5376:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5377:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5378: }
 5379: 
 5380: # -------------------------------------------------------------- Critical Store
 5381: 
 5382: sub cstore {
 5383:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5384:     my $home='';
 5385: 
 5386:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5387: 
 5388:     $symb=&symbclean($symb);
 5389:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5390: 
 5391:     if (!$domain) { $domain=$env{'user.domain'}; }
 5392:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5393: 
 5394:     &devalidate($symb,$stuname,$domain);
 5395: 
 5396:     $symb=escape($symb);
 5397:     if (!$namespace) { 
 5398:        unless ($namespace=$env{'request.course.id'}) { 
 5399:           return ''; 
 5400:        } 
 5401:     }
 5402:     if (!$home) { $home=$env{'user.home'}; }
 5403: 
 5404:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5405:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5406: 
 5407:     my $namevalue='';
 5408:     foreach my $key (keys(%$storehash)) {
 5409:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5410:     }
 5411:     $namevalue=~s/\&$//;
 5412:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5413:     return critical
 5414:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5415: }
 5416: 
 5417: # --------------------------------------------------------------------- Restore
 5418: 
 5419: sub restore {
 5420:     my ($symb,$namespace,$domain,$stuname) = @_;
 5421:     my $home='';
 5422: 
 5423:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5424: 
 5425:     if (!$symb) {
 5426:         return if ($namespace eq 'courserequests');
 5427:         unless ($symb=escape(&symbread())) { return ''; }
 5428:     } else {
 5429:         unless ($namespace eq 'courserequests') {
 5430:             $symb=&escape(&symbclean($symb));
 5431:         }
 5432:     }
 5433:     if (!$namespace) { 
 5434:        unless ($namespace=$env{'request.course.id'}) { 
 5435:           return ''; 
 5436:        } 
 5437:     }
 5438:     if (!$domain) { $domain=$env{'user.domain'}; }
 5439:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5440:     if (!$home) { $home=$env{'user.home'}; }
 5441:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5442: 
 5443:     my %returnhash=();
 5444:     foreach my $line (split(/\&/,$answer)) {
 5445: 	my ($name,$value)=split(/\=/,$line);
 5446:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5447:     }
 5448:     my $version;
 5449:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5450:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5451:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5452:        }
 5453:     }
 5454:     return %returnhash;
 5455: }
 5456: 
 5457: # ---------------------------------------------------------- Course Description
 5458: #
 5459: #  
 5460: 
 5461: sub coursedescription {
 5462:     my ($courseid,$args)=@_;
 5463:     $courseid=~s/^\///;
 5464:     $courseid=~s/\_/\//g;
 5465:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5466:     my $chome=&homeserver($cnum,$cdomain);
 5467:     my $normalid=$cdomain.'_'.$cnum;
 5468:     # need to always cache even if we get errors otherwise we keep 
 5469:     # trying and trying and trying to get the course description.
 5470:     my %envhash=();
 5471:     my %returnhash=();
 5472:     
 5473:     my $expiretime=600;
 5474:     if ($env{'request.course.id'} eq $normalid) {
 5475: 	$expiretime=120;
 5476:     }
 5477: 
 5478:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5479:     if (!$args->{'freshen_cache'}
 5480: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5481: 	foreach my $key (keys(%env)) {
 5482: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5483: 	    my ($setting) = $1;
 5484: 	    $returnhash{$setting} = $env{$key};
 5485: 	}
 5486: 	return %returnhash;
 5487:     }
 5488: 
 5489:     # get the data again
 5490: 
 5491:     if (!$args->{'one_time'}) {
 5492: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5493:     }
 5494: 
 5495:     if ($chome ne 'no_host') {
 5496:        %returnhash=&dump('environment',$cdomain,$cnum);
 5497:        if (!exists($returnhash{'con_lost'})) {
 5498: 	   my $username = $env{'user.name'}; # Defult username
 5499: 	   if(defined $args->{'user'}) {
 5500: 	       $username = $args->{'user'};
 5501: 	   }
 5502:            $returnhash{'home'}= $chome;
 5503: 	   $returnhash{'domain'} = $cdomain;
 5504: 	   $returnhash{'num'} = $cnum;
 5505:            if (!defined($returnhash{'type'})) {
 5506:                $returnhash{'type'} = 'Course';
 5507:            }
 5508:            while (my ($name,$value) = each %returnhash) {
 5509:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5510:            }
 5511:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5512:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5513: 	       $username.'_'.$cdomain.'_'.$cnum;
 5514:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5515:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5516:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5517:        }
 5518:     }
 5519:     if (!$args->{'one_time'}) {
 5520: 	&appenv(\%envhash);
 5521:     }
 5522:     return %returnhash;
 5523: }
 5524: 
 5525: sub update_released_required {
 5526:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5527:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5528:         $cid = $env{'request.course.id'};
 5529:         $cdom = $env{'course.'.$cid.'.domain'};
 5530:         $cnum = $env{'course.'.$cid.'.num'};
 5531:         $chome = $env{'course.'.$cid.'.home'};
 5532:     }
 5533:     if ($needsrelease) {
 5534:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5535:         my $needsupdate;
 5536:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5537:             $needsupdate = 1;
 5538:         } else {
 5539:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5540:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5541:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5542:                 $needsupdate = 1;
 5543:             }
 5544:         }
 5545:         if ($needsupdate) {
 5546:             my %needshash = (
 5547:                              'internal.releaserequired' => $needsrelease,
 5548:                             );
 5549:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5550:             if ($putresult eq 'ok') {
 5551:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5552:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5553:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5554:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5555:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5556:                 }
 5557:             }
 5558:         }
 5559:     }
 5560:     return;
 5561: }
 5562: 
 5563: # -------------------------------------------------See if a user is privileged
 5564: 
 5565: sub privileged {
 5566:     my ($username,$domain,$possdomains,$possroles)=@_;
 5567:     my $now = time;
 5568:     my $roles;
 5569:     if (ref($possroles) eq 'ARRAY') {
 5570:         $roles = $possroles;
 5571:     } else {
 5572:         $roles = ['dc','su'];
 5573:     }
 5574:     if (ref($possdomains) eq 'ARRAY') {
 5575:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5576:         foreach my $dom (@{$possdomains}) {
 5577:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5578:                 (ref($privileged{$dom}) eq 'HASH')) {
 5579:                 foreach my $role (@{$roles}) {
 5580:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5581:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5582:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5583:                             return 1 unless (($end && $end < $now) ||
 5584:                                              ($start && $start > $now));
 5585:                         }
 5586:                     }
 5587:                 }
 5588:             }
 5589:         }
 5590:     } else {
 5591:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5592:         my $now = time;
 5593: 
 5594:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5595:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5596:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5597:                 return 1 unless ($tend && $tend < $now)
 5598:                         or ($tstart && $tstart > $now);
 5599:             }
 5600:         }
 5601:     }
 5602:     return 0;
 5603: }
 5604: 
 5605: sub privileged_by_domain {
 5606:     my ($domains,$roles) = @_;
 5607:     my %privileged = ();
 5608:     my $cachetime = 60*60*24;
 5609:     my $now = time;
 5610:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5611:         return %privileged;
 5612:     }
 5613:     foreach my $dom (@{$domains}) {
 5614:         next if (ref($privileged{$dom}) eq 'HASH');
 5615:         my $needroles;
 5616:         foreach my $role (@{$roles}) {
 5617:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5618:             if (defined($cached)) {
 5619:                 if (ref($result) eq 'HASH') {
 5620:                     $privileged{$dom}{$role} = $result;
 5621:                 }
 5622:             } else {
 5623:                 $needroles = 1;
 5624:             }
 5625:         }
 5626:         if ($needroles) {
 5627:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5628:             $privileged{$dom} = {};
 5629:             foreach my $server (keys(%dompersonnel)) {
 5630:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5631:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5632:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5633:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5634:                         next if ($end && $end < $now);
 5635:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
 5636:                             $dompersonnel{$server}{$item};
 5637:                     }
 5638:                 }
 5639:             }
 5640:             if (ref($privileged{$dom}) eq 'HASH') {
 5641:                 foreach my $role (@{$roles}) {
 5642:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5643:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5644:                     } else {
 5645:                         my %hash = ();
 5646:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5647:                     }
 5648:                 }
 5649:             }
 5650:         }
 5651:     }
 5652:     return %privileged;
 5653: }
 5654: 
 5655: # -------------------------------------------------------- Get user privileges
 5656: 
 5657: sub rolesinit {
 5658:     my ($domain, $username) = @_;
 5659:     my %userroles = ('user.login.time' => time);
 5660:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5661: 
 5662:     # firstaccess and timerinterval are related to timed maps/resources. 
 5663:     # also, blocking can be triggered by an activating timer
 5664:     # it's saved in the user's %env.
 5665:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5666:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5667:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5668:         %timerintchk, %timerintenv);
 5669: 
 5670:     foreach my $key (keys(%firstaccess)) {
 5671:         my ($cid, $rest) = split(/\0/, $key);
 5672:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5673:     }
 5674: 
 5675:     foreach my $key (keys(%timerinterval)) {
 5676:         my ($cid,$rest) = split(/\0/,$key);
 5677:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5678:     }
 5679: 
 5680:     my %allroles=();
 5681:     my %allgroups=();
 5682: 
 5683:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5684:         my $role = $rolesdump{$area};
 5685:         $area =~ s/\_\w\w$//;
 5686: 
 5687:         my ($trole, $tend, $tstart, $group_privs);
 5688: 
 5689:         if ($role =~ /^cr/) {
 5690:         # Custom role, defined by a user 
 5691:         # e.g., user.role.cr/msu/smith/mynewrole
 5692:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5693:                 $trole = $1;
 5694:                 ($tend, $tstart) = split('_', $2);
 5695:             } else {
 5696:                 $trole = $role;
 5697:             }
 5698:         } elsif ($role =~ m|^gr/|) {
 5699:         # Role of member in a group, defined within a course/community
 5700:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5701:             ($trole, $tend, $tstart) = split(/_/, $role);
 5702:             next if $tstart eq '-1';
 5703:             ($trole, $group_privs) = split(/\//, $trole);
 5704:             $group_privs = &unescape($group_privs);
 5705:         } else {
 5706:         # Just a normal role, defined in roles.tab
 5707:             ($trole, $tend, $tstart) = split(/_/,$role);
 5708:         }
 5709: 
 5710:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5711:                  $username);
 5712:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5713: 
 5714:         # role expired or not available yet?
 5715:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5716:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5717: 
 5718:         next if $area eq '' or $trole eq '';
 5719: 
 5720:         my $spec = "$trole.$area";
 5721:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5722: 
 5723:         if ($trole =~ /^cr\//) {
 5724:         # Custom role, defined by a user
 5725:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5726:         } elsif ($trole eq 'gr') {
 5727:         # Role of a member in a group, defined within a course/community
 5728:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5729:             next;
 5730:         } else {
 5731:         # Normal role, defined in roles.tab
 5732:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5733:         }
 5734: 
 5735:         my $cid = $tdomain.'_'.$trest;
 5736:         unless ($firstaccchk{$cid}) {
 5737:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5738:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5739:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5740:                         $coursetimerstarts{$cid}{$item}; 
 5741:                 }
 5742:             }
 5743:             $firstaccchk{$cid} = 1;
 5744:         }
 5745:         unless ($timerintchk{$cid}) {
 5746:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5747:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5748:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5749:                        $coursetimerintervals{$cid}{$item};
 5750:                 }
 5751:             }
 5752:             $timerintchk{$cid} = 1;
 5753:         }
 5754:     }
 5755: 
 5756:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 5757:                                                           \%allroles, \%allgroups);
 5758:     $env{'user.adv'} = $userroles{'user.adv'};
 5759:     $env{'user.rar'} = $userroles{'user.rar'};
 5760: 
 5761:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5762: }
 5763: 
 5764: sub set_arearole {
 5765:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5766:     unless ($nolog) {
 5767: # log the associated role with the area
 5768:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5769:     }
 5770:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5771: }
 5772: 
 5773: sub custom_roleprivs {
 5774:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5775:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5776:     my $homsvr = &homeserver($rauthor,$rdomain);
 5777:     if (&hostname($homsvr) ne '') {
 5778:         my ($rdummy,$roledef)=
 5779:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5780:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5781:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5782:             if (defined($syspriv)) {
 5783:                 if ($trest =~ /^$match_community$/) {
 5784:                     $syspriv =~ s/bre\&S//; 
 5785:                 }
 5786:                 $$allroles{'cm./'}.=':'.$syspriv;
 5787:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5788:             }
 5789:             if ($tdomain ne '') {
 5790:                 if (defined($dompriv)) {
 5791:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5792:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5793:                 }
 5794:                 if (($trest ne '') && (defined($coursepriv))) {
 5795:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 5796:                         my $rolename = $1;
 5797:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 5798:                     }
 5799:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5800:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5801:                 }
 5802:             }
 5803:         }
 5804:     }
 5805: }
 5806: 
 5807: sub course_adhocrole_privs {
 5808:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 5809:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 5810:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 5811:         my (%currprivs,%storeprivs);
 5812:         foreach my $item (split(/:/,$coursepriv)) {
 5813:             my ($priv,$restrict) = split(/\&/,$item);
 5814:             $currprivs{$priv} = $restrict;
 5815:         }
 5816:         my (%possadd,%possremove,%full);
 5817:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 5818:             my ($priv,$restrict)=split(/\&/,$item);
 5819:             $full{$priv} = $restrict;
 5820:         }
 5821:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 5822:              next if ($item eq '');
 5823:              my ($rule,$rest) = split(/=/,$item);
 5824:              next unless (($rule eq 'off') || ($rule eq 'on'));
 5825:              foreach my $priv (split(/:/,$rest)) {
 5826:                  if ($priv ne '') {
 5827:                      if ($rule eq 'off') {
 5828:                          $possremove{$priv} = 1;
 5829:                      } else {
 5830:                          $possadd{$priv} = 1;
 5831:                      }
 5832:                  }
 5833:              }
 5834:          }
 5835:          foreach my $priv (sort(keys(%full))) {
 5836:              if (exists($currprivs{$priv})) {
 5837:                  unless (exists($possremove{$priv})) {
 5838:                      $storeprivs{$priv} = $currprivs{$priv};
 5839:                  }
 5840:              } elsif (exists($possadd{$priv})) {
 5841:                  $storeprivs{$priv} = $full{$priv};
 5842:              }
 5843:          }
 5844:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 5845:      }
 5846:      return $coursepriv;
 5847: }
 5848: 
 5849: sub group_roleprivs {
 5850:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5851:     my $access = 1;
 5852:     my $now = time;
 5853:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5854:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5855:     if ($access) {
 5856:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5857:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5858:     }
 5859: }
 5860: 
 5861: sub standard_roleprivs {
 5862:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5863:     if (defined($pr{$trole.':s'})) {
 5864:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5865:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5866:     }
 5867:     if ($tdomain ne '') {
 5868:         if (defined($pr{$trole.':d'})) {
 5869:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5870:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5871:         }
 5872:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5873:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5874:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5875:         }
 5876:     }
 5877: }
 5878: 
 5879: sub set_userprivs {
 5880:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5881:     my $author=0;
 5882:     my $adv=0;
 5883:     my $rar=0;
 5884:     my %grouproles = ();
 5885:     if (keys(%{$allgroups}) > 0) {
 5886:         my @groupkeys; 
 5887:         foreach my $role (keys(%{$allroles})) {
 5888:             push(@groupkeys,$role);
 5889:         }
 5890:         if (ref($groups_roles) eq 'HASH') {
 5891:             foreach my $key (keys(%{$groups_roles})) {
 5892:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5893:                     push(@groupkeys,$key);
 5894:                 }
 5895:             }
 5896:         }
 5897:         if (@groupkeys > 0) {
 5898:             foreach my $role (@groupkeys) {
 5899:                 my ($trole,$area,$sec,$extendedarea);
 5900:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5901:                     $trole = $1;
 5902:                     $area = $2;
 5903:                     $sec = $3;
 5904:                     $extendedarea = $area.$sec;
 5905:                     if (exists($$allgroups{$area})) {
 5906:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5907:                             my $spec = $trole.'.'.$extendedarea;
 5908:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5909:                                                 $$allgroups{$area}{$group};
 5910:                         }
 5911:                     }
 5912:                 }
 5913:             }
 5914:         }
 5915:     }
 5916:     foreach my $group (keys(%grouproles)) {
 5917:         $$allroles{$group} = $grouproles{$group};
 5918:     }
 5919:     foreach my $role (keys(%{$allroles})) {
 5920:         my %thesepriv;
 5921:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5922:         foreach my $item (split(/:/,$$allroles{$role})) {
 5923:             if ($item ne '') {
 5924:                 my ($privilege,$restrictions)=split(/&/,$item);
 5925:                 if ($restrictions eq '') {
 5926:                     $thesepriv{$privilege}='F';
 5927:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5928:                     $thesepriv{$privilege}.=$restrictions;
 5929:                 }
 5930:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5931:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 5932:             }
 5933:         }
 5934:         my $thesestr='';
 5935:         foreach my $priv (sort(keys(%thesepriv))) {
 5936: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5937: 	}
 5938:         $userroles->{'user.priv.'.$role} = $thesestr;
 5939:     }
 5940:     return ($author,$adv,$rar);
 5941: }
 5942: 
 5943: sub role_status {
 5944:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5945:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5946:         my ($one,$two) = split(m{\./},$rolekey,2);
 5947:         (undef,undef,$$role) = split(/\./,$one,3);
 5948:         unless (!defined($$role) || $$role eq '') {
 5949:             $$where = '/'.$two;
 5950:             $$trolecode=$$role.'.'.$$where;
 5951:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5952:             $$tstatus='is';
 5953:             if ($$tstart && $$tstart>$update) {
 5954:                 $$tstatus='future';
 5955:                 if ($$tstart<$now) {
 5956:                     if ($$tstart && $$tstart>$refresh) {
 5957:                         if (($$where ne '') && ($$role ne '')) {
 5958:                             my (%allroles,%allgroups,$group_privs,
 5959:                                 %groups_roles,@rolecodes);
 5960:                             my %userroles = (
 5961:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5962:                             );
 5963:                             @rolecodes = ('cm'); 
 5964:                             my $spec=$$role.'.'.$$where;
 5965:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5966:                             if ($$role =~ /^cr\//) {
 5967:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5968:                                 push(@rolecodes,'cr');
 5969:                             } elsif ($$role eq 'gr') {
 5970:                                 push(@rolecodes,$$role);
 5971:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5972:                                                     $env{'user.name'});
 5973:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5974:                                 (undef,my $group_privs) = split(/\//,$trole);
 5975:                                 $group_privs = &unescape($group_privs);
 5976:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5977:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5978:                                 &get_groups_roles($tdomain,$trest,
 5979:                                                   \%course_roles,\@rolecodes,
 5980:                                                   \%groups_roles);
 5981:                             } else {
 5982:                                 push(@rolecodes,$$role);
 5983:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5984:                             }
 5985:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 5986:                                                                    \%groups_roles);
 5987:                             &appenv(\%userroles,\@rolecodes);
 5988:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 5989:                         }
 5990:                     }
 5991:                     $$tstatus = 'is';
 5992:                 }
 5993:             }
 5994:             if ($$tend) {
 5995:                 if ($$tend<$update) {
 5996:                     $$tstatus='expired';
 5997:                 } elsif ($$tend<$now) {
 5998:                     $$tstatus='will_not';
 5999:                 }
 6000:             }
 6001:         }
 6002:     }
 6003: }
 6004: 
 6005: sub get_groups_roles {
 6006:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6007:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6008:                   (ref($rolecodes) eq 'ARRAY') && 
 6009:                   (ref($groups_roles) eq 'HASH')); 
 6010:     if (keys(%{$cdom_courseroles}) > 0) {
 6011:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6012:         if ($cdom ne '' && $cnum ne '') {
 6013:             foreach my $key (keys(%{$cdom_courseroles})) {
 6014:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6015:                     my $crsrole = $1;
 6016:                     my $crssec = $2;
 6017:                     if ($crsrole =~ /^cr/) {
 6018:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6019:                             push(@{$rolecodes},'cr');
 6020:                         }
 6021:                     } else {
 6022:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6023:                             push(@{$rolecodes},$crsrole);
 6024:                         }
 6025:                     }
 6026:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6027:                     if ($crssec ne '') {
 6028:                         $rolekey .= "/$crssec";
 6029:                     }
 6030:                     $rolekey .= './';
 6031:                     $groups_roles->{$rolekey} = $rolecodes;
 6032:                 }
 6033:             }
 6034:         }
 6035:     }
 6036:     return;
 6037: }
 6038: 
 6039: sub delete_env_groupprivs {
 6040:     my ($where,$courseroles,$possroles) = @_;
 6041:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6042:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6043:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6044:         %{$courseroles->{$udom}} =
 6045:             &get_my_roles('','','userroles',['active'],
 6046:                           $possroles,[$udom],1);
 6047:     }
 6048:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6049:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6050:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6051:             my $area = '/'.$cdom.'/'.$cnum;
 6052:             my $privkey = "user.priv.$crsrole.$area";
 6053:             if ($crssec ne '') {
 6054:                 $privkey .= '/'.$crssec;
 6055:             }
 6056:             $privkey .= ".$area/$group";
 6057:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6058:         }
 6059:     }
 6060:     return;
 6061: }
 6062: 
 6063: sub check_adhoc_privs {
 6064:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6065:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6066:     if ($sec) {
 6067:         $cckey .= '/'.$sec;
 6068:     }
 6069:     my $setprivs;
 6070:     if ($env{$cckey}) {
 6071:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6072:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6073:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6074:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6075:             $setprivs = 1;
 6076:         }
 6077:     } else {
 6078:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6079:         $setprivs = 1;
 6080:     }
 6081:     return $setprivs;
 6082: }
 6083: 
 6084: sub set_adhoc_privileges {
 6085: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6086:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6087:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6088:     if ($sec ne '') {
 6089:         $area .= '/'.$sec;
 6090:     }
 6091:     my $spec = $role.'.'.$area;
 6092:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6093:                                   $env{'user.name'},1);
 6094:     my %rolehash = ();
 6095:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6096:         my $rolename = $1;
 6097:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6098:         my %domdef = &get_domain_defaults($dcdom);
 6099:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6100:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6101:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6102:             }
 6103:         }
 6104:     } else {
 6105:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6106:     }
 6107:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6108:     &appenv(\%userroles,[$role,'cm']);
 6109:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6110:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6111:         &appenv( {'request.role'        => $spec,
 6112:                   'request.role.domain' => $dcdom,
 6113:                   'request.course.sec'  => $sec, 
 6114:                  }
 6115:                );
 6116:         my $tadv=0;
 6117:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6118:         &appenv({'request.role.adv'    => $tadv});
 6119:     }
 6120: }
 6121: 
 6122: # --------------------------------------------------------------- get interface
 6123: 
 6124: sub get {
 6125:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6126:    my $items='';
 6127:    foreach my $item (@$storearr) {
 6128:        $items.=&escape($item).'&';
 6129:    }
 6130:    $items=~s/\&$//;
 6131:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6132:    if (!$uname) { $uname=$env{'user.name'}; }
 6133:    my $uhome=&homeserver($uname,$udomain);
 6134: 
 6135:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6136:    my @pairs=split(/\&/,$rep);
 6137:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6138:      return @pairs;
 6139:    }
 6140:    my %returnhash=();
 6141:    my $i=0;
 6142:    foreach my $item (@$storearr) {
 6143:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6144:       $i++;
 6145:    }
 6146:    return %returnhash;
 6147: }
 6148: 
 6149: # --------------------------------------------------------------- del interface
 6150: 
 6151: sub del {
 6152:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6153:    my $items='';
 6154:    foreach my $item (@$storearr) {
 6155:        $items.=&escape($item).'&';
 6156:    }
 6157: 
 6158:    $items=~s/\&$//;
 6159:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6160:    if (!$uname) { $uname=$env{'user.name'}; }
 6161:    my $uhome=&homeserver($uname,$udomain);
 6162:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6163: }
 6164: 
 6165: # -------------------------------------------------------------- dump interface
 6166: 
 6167: sub unserialize {
 6168:     my ($rep, $escapedkeys) = @_;
 6169: 
 6170:     return {} if $rep =~ /^error/;
 6171: 
 6172:     my %returnhash=();
 6173:     foreach my $item (split(/\&/,$rep)) {
 6174:         my ($key, $value) = split(/=/, $item, 2);
 6175:         $key = unescape($key) unless $escapedkeys;
 6176:         next if $key =~ /^error: 2 /;
 6177:         $returnhash{$key} = &thaw_unescape($value);
 6178:     }
 6179:     return \%returnhash;
 6180: }
 6181: 
 6182: # see Lond::dump_with_regexp
 6183: # if $escapedkeys hash keys won't get unescaped.
 6184: sub dump {
 6185:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6186:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6187:     if (!$uname) { $uname=$env{'user.name'}; }
 6188:     my $uhome=&homeserver($uname,$udomain);
 6189: 
 6190:     if ($regexp) {
 6191:         $regexp=&escape($regexp);
 6192:     } else {
 6193:         $regexp='.';
 6194:     }
 6195:     if (grep { $_ eq $uhome } &current_machine_ids()) {
 6196:         # user is hosted on this machine
 6197:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
 6198:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6199:         return %{&unserialize($reply, $escapedkeys)};
 6200:     }
 6201:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6202:     my @pairs=split(/\&/,$rep);
 6203:     my %returnhash=();
 6204:     if (!($rep =~ /^error/ )) {
 6205: 	foreach my $item (@pairs) {
 6206: 	    my ($key,$value)=split(/=/,$item,2);
 6207:             $key = &unescape($key) unless ($escapedkeys);
 6208: 	    next if ($key =~ /^error: 2 /);
 6209: 	    $returnhash{$key}=&thaw_unescape($value);
 6210: 	}
 6211:     }
 6212:     return %returnhash;
 6213: }
 6214: 
 6215: 
 6216: # --------------------------------------------------------- dumpstore interface
 6217: 
 6218: sub dumpstore {
 6219:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6220:    # same as dump but keys must be escaped. They may contain colon separated
 6221:    # lists of values that may themself contain colons (e.g. symbs).
 6222:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6223: }
 6224: 
 6225: # -------------------------------------------------------------- keys interface
 6226: 
 6227: sub getkeys {
 6228:    my ($namespace,$udomain,$uname)=@_;
 6229:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6230:    if (!$uname) { $uname=$env{'user.name'}; }
 6231:    my $uhome=&homeserver($uname,$udomain);
 6232:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6233:    my @keyarray=();
 6234:    foreach my $key (split(/\&/,$rep)) {
 6235:       next if ($key =~ /^error: 2 /);
 6236:       push(@keyarray,&unescape($key));
 6237:    }
 6238:    return @keyarray;
 6239: }
 6240: 
 6241: # --------------------------------------------------------------- currentdump
 6242: sub currentdump {
 6243:    my ($courseid,$sdom,$sname)=@_;
 6244:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6245:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6246:    $sname    = $env{'user.name'}         if (! defined($sname));
 6247:    my $uhome = &homeserver($sname,$sdom);
 6248:    my $rep;
 6249: 
 6250:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6251:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
 6252:                    $courseid)));
 6253:    } else {
 6254:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6255:    }
 6256: 
 6257:    return if ($rep =~ /^(error:|no_such_host)/);
 6258:    #
 6259:    my %returnhash=();
 6260:    #
 6261:    if ($rep eq 'unknown_cmd') { 
 6262:        # an old lond will not know currentdump
 6263:        # Do a dump and make it look like a currentdump
 6264:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6265:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6266:        my %hash = @tmp;
 6267:        @tmp=();
 6268:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6269:    } else {
 6270:        my @pairs=split(/\&/,$rep);
 6271:        foreach my $pair (@pairs) {
 6272:            my ($key,$value)=split(/=/,$pair,2);
 6273:            my ($symb,$param) = split(/:/,$key);
 6274:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6275:                                                         &thaw_unescape($value);
 6276:        }
 6277:    }
 6278:    return %returnhash;
 6279: }
 6280: 
 6281: sub convert_dump_to_currentdump{
 6282:     my %hash = %{shift()};
 6283:     my %returnhash;
 6284:     # Code ripped from lond, essentially.  The only difference
 6285:     # here is the unescaping done by lonnet::dump().  Conceivably
 6286:     # we might run in to problems with parameter names =~ /^v\./
 6287:     while (my ($key,$value) = each(%hash)) {
 6288:         my ($v,$symb,$param) = split(/:/,$key);
 6289: 	$symb  = &unescape($symb);
 6290: 	$param = &unescape($param);
 6291:         next if ($v eq 'version' || $symb eq 'keys');
 6292:         next if (exists($returnhash{$symb}) &&
 6293:                  exists($returnhash{$symb}->{$param}) &&
 6294:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6295:         $returnhash{$symb}->{$param}=$value;
 6296:         $returnhash{$symb}->{'v.'.$param}=$v;
 6297:     }
 6298:     #
 6299:     # Remove all of the keys in the hashes which keep track of
 6300:     # the version of the parameter.
 6301:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6302:         # use a foreach because we are going to delete from the hash.
 6303:         foreach my $key (keys(%$param_hash)) {
 6304:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6305:         }
 6306:     }
 6307:     return \%returnhash;
 6308: }
 6309: 
 6310: # ------------------------------------------------------ critical inc interface
 6311: 
 6312: sub cinc {
 6313:     return &inc(@_,'critical');
 6314: }
 6315: 
 6316: # --------------------------------------------------------------- inc interface
 6317: 
 6318: sub inc {
 6319:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6320:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6321:     if (!$uname) { $uname=$env{'user.name'}; }
 6322:     my $uhome=&homeserver($uname,$udomain);
 6323:     my $items='';
 6324:     if (! ref($store)) {
 6325:         # got a single value, so use that instead
 6326:         $items = &escape($store).'=&';
 6327:     } elsif (ref($store) eq 'SCALAR') {
 6328:         $items = &escape($$store).'=&';        
 6329:     } elsif (ref($store) eq 'ARRAY') {
 6330:         $items = join('=&',map {&escape($_);} @{$store});
 6331:     } elsif (ref($store) eq 'HASH') {
 6332:         while (my($key,$value) = each(%{$store})) {
 6333:             $items.= &escape($key).'='.&escape($value).'&';
 6334:         }
 6335:     }
 6336:     $items=~s/\&$//;
 6337:     if ($critical) {
 6338: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6339:     } else {
 6340: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6341:     }
 6342: }
 6343: 
 6344: # --------------------------------------------------------------- put interface
 6345: 
 6346: sub put {
 6347:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6348:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6349:    if (!$uname) { $uname=$env{'user.name'}; }
 6350:    my $uhome=&homeserver($uname,$udomain);
 6351:    my $items='';
 6352:    foreach my $item (keys(%$storehash)) {
 6353:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6354:    }
 6355:    $items=~s/\&$//;
 6356:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6357: }
 6358: 
 6359: # ------------------------------------------------------------ newput interface
 6360: 
 6361: sub newput {
 6362:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6363:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6364:    if (!$uname) { $uname=$env{'user.name'}; }
 6365:    my $uhome=&homeserver($uname,$udomain);
 6366:    my $items='';
 6367:    foreach my $key (keys(%$storehash)) {
 6368:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6369:    }
 6370:    $items=~s/\&$//;
 6371:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6372: }
 6373: 
 6374: # ---------------------------------------------------------  putstore interface
 6375: 
 6376: sub putstore {
 6377:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6378:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6379:    if (!$uname) { $uname=$env{'user.name'}; }
 6380:    my $uhome=&homeserver($uname,$udomain);
 6381:    my $items='';
 6382:    foreach my $key (keys(%$storehash)) {
 6383:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6384:    }
 6385:    $items=~s/\&$//;
 6386:    my $esc_symb=&escape($symb);
 6387:    my $esc_v=&escape($version);
 6388:    my $reply =
 6389:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6390: 	      $uhome);
 6391:    if (($tolog) && ($reply eq 'ok')) {
 6392:        my $namevalue='';
 6393:        foreach my $key (keys(%{$storehash})) {
 6394:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6395:        }
 6396:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6397:                      '&host='.&escape($perlvar{'lonHostID'}).
 6398:                      '&version='.$esc_v.
 6399:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6400:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6401:    }
 6402:    if ($reply eq 'unknown_cmd') {
 6403:        # gfall back to way things use to be done
 6404:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6405: 			    $uname);
 6406:    }
 6407:    return $reply;
 6408: }
 6409: 
 6410: sub old_putstore {
 6411:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6412:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6413:     if (!$uname) { $uname=$env{'user.name'}; }
 6414:     my $uhome=&homeserver($uname,$udomain);
 6415:     my %newstorehash;
 6416:     foreach my $item (keys(%$storehash)) {
 6417: 	my $key = $version.':'.&escape($symb).':'.$item;
 6418: 	$newstorehash{$key} = $storehash->{$item};
 6419:     }
 6420:     my $items='';
 6421:     my %allitems = ();
 6422:     foreach my $item (keys(%newstorehash)) {
 6423: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6424: 	    my $key = $1.':keys:'.$2;
 6425: 	    $allitems{$key} .= $3.':';
 6426: 	}
 6427: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6428:     }
 6429:     foreach my $item (keys(%allitems)) {
 6430: 	$allitems{$item} =~ s/\:$//;
 6431: 	$items.= $item.'='.$allitems{$item}.'&';
 6432:     }
 6433:     $items=~s/\&$//;
 6434:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6435: }
 6436: 
 6437: # ------------------------------------------------------ critical put interface
 6438: 
 6439: sub cput {
 6440:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6441:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6442:    if (!$uname) { $uname=$env{'user.name'}; }
 6443:    my $uhome=&homeserver($uname,$udomain);
 6444:    my $items='';
 6445:    foreach my $item (keys(%$storehash)) {
 6446:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6447:    }
 6448:    $items=~s/\&$//;
 6449:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6450: }
 6451: 
 6452: # -------------------------------------------------------------- eget interface
 6453: 
 6454: sub eget {
 6455:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6456:    my $items='';
 6457:    foreach my $item (@$storearr) {
 6458:        $items.=&escape($item).'&';
 6459:    }
 6460:    $items=~s/\&$//;
 6461:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6462:    if (!$uname) { $uname=$env{'user.name'}; }
 6463:    my $uhome=&homeserver($uname,$udomain);
 6464:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6465:    my @pairs=split(/\&/,$rep);
 6466:    my %returnhash=();
 6467:    my $i=0;
 6468:    foreach my $item (@$storearr) {
 6469:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6470:       $i++;
 6471:    }
 6472:    return %returnhash;
 6473: }
 6474: 
 6475: # ------------------------------------------------------------ tmpput interface
 6476: sub tmpput {
 6477:     my ($storehash,$server,$context)=@_;
 6478:     my $items='';
 6479:     foreach my $item (keys(%$storehash)) {
 6480: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6481:     }
 6482:     $items=~s/\&$//;
 6483:     if (defined($context)) {
 6484:         $items .= ':'.&escape($context);
 6485:     }
 6486:     return &reply("tmpput:$items",$server);
 6487: }
 6488: 
 6489: # ------------------------------------------------------------ tmpget interface
 6490: sub tmpget {
 6491:     my ($token,$server)=@_;
 6492:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6493:     my $rep=&reply("tmpget:$token",$server);
 6494:     my %returnhash;
 6495:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6496:         return %returnhash;
 6497:     }
 6498:     foreach my $item (split(/\&/,$rep)) {
 6499: 	my ($key,$value)=split(/=/,$item);
 6500: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6501:     }
 6502:     return %returnhash;
 6503: }
 6504: 
 6505: # ------------------------------------------------------------ tmpdel interface
 6506: sub tmpdel {
 6507:     my ($token,$server)=@_;
 6508:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6509:     return &reply("tmpdel:$token",$server);
 6510: }
 6511: 
 6512: # ------------------------------------------------------------ get_timebased_id
 6513: 
 6514: sub get_timebased_id {
 6515:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6516:         $maxtries) = @_;
 6517:     my ($newid,$error,$dellock);
 6518:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
 6519:         return ('','ok','invalid call to get suffix');
 6520:     }
 6521: 
 6522: # set defaults for any optional args for which values were not supplied
 6523:     if ($who eq '') {
 6524:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6525:     }
 6526:     if (!$locktries) {
 6527:         $locktries = 3;
 6528:     }
 6529:     if (!$maxtries) {
 6530:         $maxtries = 10;
 6531:     }
 6532: 
 6533:     if (($cdom eq '') || ($cnum eq '')) {
 6534:         if ($env{'request.course.id'}) {
 6535:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6536:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6537:         }
 6538:         if (($cdom eq '') || ($cnum eq '')) {
 6539:             return ('','ok','call to get suffix not in course context');
 6540:         }
 6541:     }
 6542: 
 6543: # construct locking item
 6544:     my $lockhash = {
 6545:                       $prefix."\0".'locked_'.$keyid => $who,
 6546:                    };
 6547:     my $tries = 0;
 6548: 
 6549: # attempt to get lock on nohist_$namespace file
 6550:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6551:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6552:         $tries ++;
 6553:         sleep 1;
 6554:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6555:     }
 6556: 
 6557: # attempt to get unique identifier, based on current timestamp
 6558:     if ($gotlock eq 'ok') {
 6559:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6560:         my $id = time;
 6561:         $newid = $id;
 6562:         if ($idtype eq 'addcode') {
 6563:             $newid .= &sixnum_code();
 6564:         }
 6565:         my $idtries = 0;
 6566:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6567:             if ($idtype eq 'concat') {
 6568:                 $newid = $id.$idtries;
 6569:             } elsif ($idtype eq 'addcode') {
 6570:                 $newid = $newid.&sixnum_code();
 6571:             } else {
 6572:                 $newid ++;
 6573:             }
 6574:             $idtries ++;
 6575:         }
 6576:         if (!exists($inuse{$prefix."\0".$newid})) {
 6577:             my %new_item =  (
 6578:                               $prefix."\0".$newid => $who,
 6579:                             );
 6580:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6581:                                                  $cdom,$cnum);
 6582:             if ($putresult ne 'ok') {
 6583:                 undef($newid);
 6584:                 $error = 'error saving new item: '.$putresult;
 6585:             }
 6586:         } else {
 6587:              undef($newid);
 6588:              $error = ('error: no unique suffix available for the new item ');
 6589:         }
 6590: #  remove lock
 6591:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6592:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6593:     } else {
 6594:         $error = "error: could not obtain lockfile\n";
 6595:         $dellock = 'ok';
 6596:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6597:             $dellock = 'nolock';
 6598:         }
 6599:     }
 6600:     return ($newid,$dellock,$error);
 6601: }
 6602: 
 6603: sub sixnum_code {
 6604:     my $code;
 6605:     for (0..6) {
 6606:         $code .= int( rand(9) );
 6607:     }
 6608:     return $code;
 6609: }
 6610: 
 6611: # -------------------------------------------------- portfolio access checking
 6612: 
 6613: sub portfolio_access {
 6614:     my ($requrl,$clientip) = @_;
 6615:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6616:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6617:     if ($result) {
 6618:         my %setters;
 6619:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6620:             my ($startblock,$endblock) =
 6621:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6622:             if ($startblock && $endblock) {
 6623:                 return 'B';
 6624:             }
 6625:         } else {
 6626:             my ($startblock,$endblock) =
 6627:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6628:             if ($startblock && $endblock) {
 6629:                 return 'B';
 6630:             }
 6631:         }
 6632:     }
 6633:     if ($result eq 'ok') {
 6634:        return 'F';
 6635:     } elsif ($result =~ /^[^:]+:guest_/) {
 6636:        return 'A';
 6637:     }
 6638:     return '';
 6639: }
 6640: 
 6641: sub get_portfolio_access {
 6642:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6643: 
 6644:     if (!ref($access_hash)) {
 6645: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6646: 	my %access_controls = &get_access_controls($current_perms,$group,
 6647: 						   $file_name);
 6648: 	$access_hash = $access_controls{$file_name};
 6649:     }
 6650: 
 6651:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6652:     my $now = time;
 6653:     if (ref($access_hash) eq 'HASH') {
 6654:         foreach my $key (keys(%{$access_hash})) {
 6655:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6656:             if ($start > $now) {
 6657:                 next;
 6658:             }
 6659:             if ($end && $end<$now) {
 6660:                 next;
 6661:             }
 6662:             if ($scope eq 'public') {
 6663:                 $public = $key;
 6664:                 last;
 6665:             } elsif ($scope eq 'guest') {
 6666:                 $guest = $key;
 6667:             } elsif ($scope eq 'domains') {
 6668:                 push(@domains,$key);
 6669:             } elsif ($scope eq 'users') {
 6670:                 push(@users,$key);
 6671:             } elsif ($scope eq 'course') {
 6672:                 push(@courses,$key);
 6673:             } elsif ($scope eq 'group') {
 6674:                 push(@groups,$key);
 6675:             } elsif ($scope eq 'ip') {
 6676:                 push(@ips,$key);
 6677:             }
 6678:         }
 6679:         if ($public) {
 6680:             return 'ok';
 6681:         } elsif (@ips > 0) {
 6682:             my $allowed;
 6683:             foreach my $ipkey (@ips) {
 6684:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6685:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6686:                         $allowed = 1;
 6687:                         last;
 6688:                     }
 6689:                 }
 6690:             }
 6691:             if ($allowed) {
 6692:                 return 'ok';
 6693:             }
 6694:         }
 6695:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6696:             if ($guest) {
 6697:                 return $guest;
 6698:             }
 6699:         } else {
 6700:             if (@domains > 0) {
 6701:                 foreach my $domkey (@domains) {
 6702:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6703:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6704:                             return 'ok';
 6705:                         }
 6706:                     }
 6707:                 }
 6708:             }
 6709:             if (@users > 0) {
 6710:                 foreach my $userkey (@users) {
 6711:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6712:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6713:                             if (ref($item) eq 'HASH') {
 6714:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6715:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6716:                                     return 'ok';
 6717:                                 }
 6718:                             }
 6719:                         }
 6720:                     } 
 6721:                 }
 6722:             }
 6723:             my %roleshash;
 6724:             my @courses_and_groups = @courses;
 6725:             push(@courses_and_groups,@groups); 
 6726:             if (@courses_and_groups > 0) {
 6727:                 my (%allgroups,%allroles); 
 6728:                 my ($start,$end,$role,$sec,$group);
 6729:                 foreach my $envkey (%env) {
 6730:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6731:                         my $cid = $2.'_'.$3; 
 6732:                         if ($1 eq 'gr') {
 6733:                             $group = $4;
 6734:                             $allgroups{$cid}{$group} = $env{$envkey};
 6735:                         } else {
 6736:                             if ($4 eq '') {
 6737:                                 $sec = 'none';
 6738:                             } else {
 6739:                                 $sec = $4;
 6740:                             }
 6741:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6742:                         }
 6743:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6744:                         my $cid = $2.'_'.$3;
 6745:                         if ($4 eq '') {
 6746:                             $sec = 'none';
 6747:                         } else {
 6748:                             $sec = $4;
 6749:                         }
 6750:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6751:                     }
 6752:                 }
 6753:                 if (keys(%allroles) == 0) {
 6754:                     return;
 6755:                 }
 6756:                 foreach my $key (@courses_and_groups) {
 6757:                     my %content = %{$$access_hash{$key}};
 6758:                     my $cnum = $content{'number'};
 6759:                     my $cdom = $content{'domain'};
 6760:                     my $cid = $cdom.'_'.$cnum;
 6761:                     if (!exists($allroles{$cid})) {
 6762:                         next;
 6763:                     }    
 6764:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6765:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6766:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6767:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6768:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6769:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6770:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6771:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6772:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6773:                                         if (grep/^all$/,@sections) {
 6774:                                             return 'ok';
 6775:                                         } else {
 6776:                                             if (grep/^$sec$/,@sections) {
 6777:                                                 return 'ok';
 6778:                                             }
 6779:                                         }
 6780:                                     }
 6781:                                 }
 6782:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6783:                                     if (grep/^none$/,@groups) {
 6784:                                         return 'ok';
 6785:                                     }
 6786:                                 } else {
 6787:                                     if (grep/^all$/,@groups) {
 6788:                                         return 'ok';
 6789:                                     } 
 6790:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6791:                                         if (grep/^$group$/,@groups) {
 6792:                                             return 'ok';
 6793:                                         }
 6794:                                     }
 6795:                                 } 
 6796:                             }
 6797:                         }
 6798:                     }
 6799:                 }
 6800:             }
 6801:             if ($guest) {
 6802:                 return $guest;
 6803:             }
 6804:         }
 6805:     }
 6806:     return;
 6807: }
 6808: 
 6809: sub course_group_datechecker {
 6810:     my ($dates,$now,$status) = @_;
 6811:     my ($start,$end) = split(/\./,$dates);
 6812:     if (!$start && !$end) {
 6813:         return 'ok';
 6814:     }
 6815:     if (grep/^active$/,@{$status}) {
 6816:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6817:             return 'ok';
 6818:         }
 6819:     }
 6820:     if (grep/^previous$/,@{$status}) {
 6821:         if ($end > $now ) {
 6822:             return 'ok';
 6823:         }
 6824:     }
 6825:     if (grep/^future$/,@{$status}) {
 6826:         if ($start > $now) {
 6827:             return 'ok';
 6828:         }
 6829:     }
 6830:     return; 
 6831: }
 6832: 
 6833: sub parse_portfolio_url {
 6834:     my ($url) = @_;
 6835: 
 6836:     my ($type,$udom,$unum,$group,$file_name);
 6837:     
 6838:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6839: 	$type = 1;
 6840:         $udom = $1;
 6841:         $unum = $2;
 6842:         $file_name = $3;
 6843:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6844: 	$type = 2;
 6845:         $udom = $1;
 6846:         $unum = $2;
 6847:         $group = $3;
 6848:         $file_name = $3.'/'.$4;
 6849:     }
 6850:     if (wantarray) {
 6851: 	return ($type,$udom,$unum,$file_name,$group);
 6852:     }
 6853:     return $type;
 6854: }
 6855: 
 6856: sub is_portfolio_url {
 6857:     my ($url) = @_;
 6858:     return scalar(&parse_portfolio_url($url));
 6859: }
 6860: 
 6861: sub is_portfolio_file {
 6862:     my ($file) = @_;
 6863:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6864:         return 1;
 6865:     }
 6866:     return;
 6867: }
 6868: 
 6869: sub usertools_access {
 6870:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6871:     my ($access,%tools);
 6872:     if ($context eq '') {
 6873:         $context = 'tools';
 6874:     }
 6875:     if ($context eq 'requestcourses') {
 6876:         %tools = (
 6877:                       official   => 1,
 6878:                       unofficial => 1,
 6879:                       community  => 1,
 6880:                       textbook   => 1,
 6881:                  );
 6882:     } elsif ($context eq 'requestauthor') {
 6883:         %tools = (
 6884:                       requestauthor => 1,
 6885:                  );
 6886:     } else {
 6887:         %tools = (
 6888:                       aboutme   => 1,
 6889:                       blog      => 1,
 6890:                       webdav    => 1,
 6891:                       portfolio => 1,
 6892:                  );
 6893:     }
 6894:     return if (!defined($tools{$tool}));
 6895: 
 6896:     if (($udom eq '') || ($uname eq '')) {
 6897:         $udom = $env{'user.domain'};
 6898:         $uname = $env{'user.name'};
 6899:     }
 6900: 
 6901:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6902:         if ($action ne 'reload') {
 6903:             if ($context eq 'requestcourses') {
 6904:                 return $env{'environment.canrequest.'.$tool};
 6905:             } elsif ($context eq 'requestauthor') {
 6906:                 return $env{'environment.canrequest.author'};
 6907:             } else {
 6908:                 return $env{'environment.availabletools.'.$tool};
 6909:             }
 6910:         }
 6911:     }
 6912: 
 6913:     my ($toolstatus,$inststatus,$envkey);
 6914:     if ($context eq 'requestauthor') {
 6915:         $envkey = $context;
 6916:     } else {
 6917:         $envkey = $context.'.'.$tool;
 6918:     }
 6919: 
 6920:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6921:          ($action ne 'reload')) {
 6922:         $toolstatus = $env{'environment.'.$envkey};
 6923:         $inststatus = $env{'environment.inststatus'};
 6924:     } else {
 6925:         if (ref($userenvref) eq 'HASH') {
 6926:             $toolstatus = $userenvref->{$envkey};
 6927:             $inststatus = $userenvref->{'inststatus'};
 6928:         } else {
 6929:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6930:             $toolstatus = $userenv{$envkey};
 6931:             $inststatus = $userenv{'inststatus'};
 6932:         }
 6933:     }
 6934: 
 6935:     if ($toolstatus ne '') {
 6936:         if ($toolstatus) {
 6937:             $access = 1;
 6938:         } else {
 6939:             $access = 0;
 6940:         }
 6941:         return $access;
 6942:     }
 6943: 
 6944:     my ($is_adv,%domdef);
 6945:     if (ref($is_advref) eq 'HASH') {
 6946:         $is_adv = $is_advref->{'is_adv'};
 6947:     } else {
 6948:         $is_adv = &is_advanced_user($udom,$uname);
 6949:     }
 6950:     if (ref($domdefref) eq 'HASH') {
 6951:         %domdef = %{$domdefref};
 6952:     } else {
 6953:         %domdef = &get_domain_defaults($udom);
 6954:     }
 6955:     if (ref($domdef{$tool}) eq 'HASH') {
 6956:         if ($is_adv) {
 6957:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6958:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6959:                     $access = 1;
 6960:                 } else {
 6961:                     $access = 0;
 6962:                 }
 6963:                 return $access;
 6964:             }
 6965:         }
 6966:         if ($inststatus ne '') {
 6967:             my ($hasaccess,$hasnoaccess);
 6968:             foreach my $affiliation (split(/:/,$inststatus)) {
 6969:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6970:                     if ($domdef{$tool}{$affiliation}) {
 6971:                         $hasaccess = 1;
 6972:                     } else {
 6973:                         $hasnoaccess = 1;
 6974:                     }
 6975:                 }
 6976:             }
 6977:             if ($hasaccess || $hasnoaccess) {
 6978:                 if ($hasaccess) {
 6979:                     $access = 1;
 6980:                 } elsif ($hasnoaccess) {
 6981:                     $access = 0; 
 6982:                 }
 6983:                 return $access;
 6984:             }
 6985:         } else {
 6986:             if ($domdef{$tool}{'default'} ne '') {
 6987:                 if ($domdef{$tool}{'default'}) {
 6988:                     $access = 1;
 6989:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6990:                     $access = 0;
 6991:                 }
 6992:                 return $access;
 6993:             }
 6994:         }
 6995:     } else {
 6996:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6997:             $access = 1;
 6998:         } else {
 6999:             $access = 0;
 7000:         }
 7001:         return $access;
 7002:     }
 7003: }
 7004: 
 7005: sub is_course_owner {
 7006:     my ($cdom,$cnum,$udom,$uname) = @_;
 7007:     if (($udom eq '') || ($uname eq '')) {
 7008:         $udom = $env{'user.domain'};
 7009:         $uname = $env{'user.name'};
 7010:     }
 7011:     unless (($udom eq '') || ($uname eq '')) {
 7012:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7013:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7014:                 return 1;
 7015:             } else {
 7016:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7017:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7018:                     return 1;
 7019:                 }
 7020:             }
 7021:         }
 7022:     }
 7023:     return;
 7024: }
 7025: 
 7026: sub is_advanced_user {
 7027:     my ($udom,$uname) = @_;
 7028:     if ($udom ne '' && $uname ne '') {
 7029:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7030:             if (wantarray) {
 7031:                 return ($env{'user.adv'},$env{'user.author'});
 7032:             } else {
 7033:                 return $env{'user.adv'};
 7034:             }
 7035:         }
 7036:     }
 7037:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7038:     my %allroles;
 7039:     my ($is_adv,$is_author);
 7040:     foreach my $role (keys(%roleshash)) {
 7041:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7042:         my $area = '/'.$tdomain.'/'.$trest;
 7043:         if ($sec ne '') {
 7044:             $area .= '/'.$sec;
 7045:         }
 7046:         if (($area ne '') && ($trole ne '')) {
 7047:             my $spec=$trole.'.'.$area;
 7048:             if ($trole =~ /^cr\//) {
 7049:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7050:             } elsif ($trole ne 'gr') {
 7051:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7052:             }
 7053:             if ($trole eq 'au') {
 7054:                 $is_author = 1;
 7055:             }
 7056:         }
 7057:     }
 7058:     foreach my $role (keys(%allroles)) {
 7059:         last if ($is_adv);
 7060:         foreach my $item (split(/:/,$allroles{$role})) {
 7061:             if ($item ne '') {
 7062:                 my ($privilege,$restrictions)=split(/&/,$item);
 7063:                 if ($privilege eq 'adv') {
 7064:                     $is_adv = 1;
 7065:                     last;
 7066:                 }
 7067:             }
 7068:         }
 7069:     }
 7070:     if (wantarray) {
 7071:         return ($is_adv,$is_author);
 7072:     }
 7073:     return $is_adv;
 7074: }
 7075: 
 7076: sub check_can_request {
 7077:     my ($dom,$can_request,$request_domains) = @_;
 7078:     my $canreq = 0;
 7079:     my ($types,$typename) = &Apache::loncommon::course_types();
 7080:     my @options = ('approval','validate','autolimit');
 7081:     my $optregex = join('|',@options);
 7082:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7083:         foreach my $type (@{$types}) {
 7084:             if (&usertools_access($env{'user.name'},
 7085:                                   $env{'user.domain'},
 7086:                                   $type,undef,'requestcourses')) {
 7087:                 $canreq ++;
 7088:                 if (ref($request_domains) eq 'HASH') {
 7089:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 7090:                 }
 7091:                 if ($dom eq $env{'user.domain'}) {
 7092:                     $can_request->{$type} = 1;
 7093:                 }
 7094:             }
 7095:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 7096:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7097:                 if (@curr > 0) {
 7098:                     foreach my $item (@curr) {
 7099:                         if (ref($request_domains) eq 'HASH') {
 7100:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7101:                             if ($otherdom ne '') {
 7102:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7103:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7104:                                         push(@{$request_domains->{$type}},$otherdom);
 7105:                                     }
 7106:                                 } else {
 7107:                                     push(@{$request_domains->{$type}},$otherdom);
 7108:                                 }
 7109:                             }
 7110:                         }
 7111:                     }
 7112:                     unless($dom eq $env{'user.domain'}) {
 7113:                         $canreq ++;
 7114:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7115:                             $can_request->{$type} = 1;
 7116:                         }
 7117:                     }
 7118:                 }
 7119:             }
 7120:         }
 7121:     }
 7122:     return $canreq;
 7123: }
 7124: 
 7125: # ---------------------------------------------- Custom access rule evaluation
 7126: 
 7127: sub customaccess {
 7128:     my ($priv,$uri)=@_;
 7129:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7130:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7131:     $udom = &LONCAPA::clean_domain($udom);
 7132:     $ucrs = &LONCAPA::clean_username($ucrs);
 7133:     my $access=0;
 7134:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7135: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7136: 	if ($type eq 'user') {
 7137: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7138: 		my ($tdom,$tuname)=split(m{/},$scope);
 7139: 		if ($tdom) {
 7140: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7141: 		}
 7142: 		if ($tuname) {
 7143: 		    if ($tuname ne $env{'user.name'}) { next; }
 7144: 		}
 7145: 		$access=($effect eq 'allow');
 7146: 		last;
 7147: 	    }
 7148: 	} else {
 7149: 	    if ($role) {
 7150: 		if ($role ne $urole) { next; }
 7151: 	    }
 7152: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7153: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7154: 		if ($tdom) {
 7155: 		    if ($tdom ne $udom) { next; }
 7156: 		}
 7157: 		if ($tcrs) {
 7158: 		    if ($tcrs ne $ucrs) { next; }
 7159: 		}
 7160: 		if ($tsec) {
 7161: 		    if ($tsec ne $usec) { next; }
 7162: 		}
 7163: 		$access=($effect eq 'allow');
 7164: 		last;
 7165: 	    }
 7166: 	    if ($realm eq '' && $role eq '') {
 7167: 		$access=($effect eq 'allow');
 7168: 	    }
 7169: 	}
 7170:     }
 7171:     return $access;
 7172: }
 7173: 
 7174: # ------------------------------------------------- Check for a user privilege
 7175: 
 7176: sub allowed {
 7177:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7178:     my $ver_orguri=$uri;
 7179:     $uri=&deversion($uri);
 7180:     my $orguri=$uri;
 7181:     $uri=&declutter($uri);
 7182: 
 7183:     if ($priv eq 'evb') {
 7184: # Evade communication block restrictions for specified role in a course
 7185:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7186:             return $1;
 7187:         } else {
 7188:             return;
 7189:         }
 7190:     }
 7191: 
 7192:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7193: # Free bre access to adm and meta resources
 7194:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7195: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7196: 	&& ($priv eq 'bre')) {
 7197: 	return 'F';
 7198:     }
 7199: 
 7200: # Free bre access to user's own portfolio contents
 7201:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7202:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7203: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7204:         my %setters;
 7205:         my ($startblock,$endblock) = 
 7206:             &Apache::loncommon::blockcheck(\%setters,'port');
 7207:         if ($startblock && $endblock) {
 7208:             return 'B';
 7209:         } else {
 7210:             return 'F';
 7211:         }
 7212:     }
 7213: 
 7214: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7215:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7216:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7217:         if (exists($env{'request.course.id'})) {
 7218:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7219:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7220:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7221:                 my $courseprivid=$env{'request.course.id'};
 7222:                 $courseprivid=~s/\_/\//;
 7223:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7224:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7225:                     return $1; 
 7226:                 } else {
 7227:                     if ($env{'request.course.sec'}) {
 7228:                         $courseprivid.='/'.$env{'request.course.sec'};
 7229:                     }
 7230:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7231:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7232:                         return $2;
 7233:                     }
 7234:                 }
 7235:             }
 7236:         }
 7237:     }
 7238: 
 7239: # Free bre to public access
 7240: 
 7241:     if ($priv eq 'bre') {
 7242:         my $copyright=&metadata($uri,'copyright');
 7243: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7244:            return 'F'; 
 7245:         }
 7246:         if ($copyright eq 'priv') {
 7247:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7248: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7249: 		return '';
 7250:             }
 7251:         }
 7252:         if ($copyright eq 'domain') {
 7253:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7254: 	    unless (($env{'user.domain'} eq $1) ||
 7255:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7256: 		return '';
 7257:             }
 7258:         }
 7259:         if ($env{'request.role'}=~ /li\.\//) {
 7260:             # Library role, so allow browsing of resources in this domain.
 7261:             return 'F';
 7262:         }
 7263:         if ($copyright eq 'custom') {
 7264: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7265:         }
 7266:     }
 7267:     # Domain coordinator is trying to create a course
 7268:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7269:         # uri is the requested domain in this case.
 7270:         # comparison to 'request.role.domain' shows if the user has selected
 7271:         # a role of dc for the domain in question.
 7272:         return 'F' if ($uri eq $env{'request.role.domain'});
 7273:     }
 7274: 
 7275:     my $thisallowed='';
 7276:     my $statecond=0;
 7277:     my $courseprivid='';
 7278: 
 7279:     my $ownaccess;
 7280:     # Community Coordinator or Assistant Co-author browsing resource space.
 7281:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7282:         if ($uri eq '') {
 7283:             $ownaccess = 1;
 7284:         } else {
 7285:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7286:                 my $udom = $env{'user.domain'};
 7287:                 my $uname = $env{'user.name'};
 7288:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7289:                     $ownaccess = 1;
 7290:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7291:                     unless ($uri =~ m{\.\./}) {
 7292:                         $ownaccess = 1;
 7293:                     }
 7294:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7295:                     my $now = time;
 7296:                     if ($uri =~ m{^([^/]+)/?$}) {
 7297:                         my $adom = $1;
 7298:                         foreach my $key (keys(%env)) {
 7299:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7300:                                 my ($start,$end) = split('.',$env{$key});
 7301:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7302:                                     $ownaccess = 1;
 7303:                                     last;
 7304:                                 }
 7305:                             }
 7306:                         }
 7307:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7308:                         my $adom = $1;
 7309:                         my $aname = $2;
 7310:                         foreach my $role ('ca','aa') { 
 7311:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7312:                                 my ($start,$end) =
 7313:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7314:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7315:                                     $ownaccess = 1;
 7316:                                     last;
 7317:                                 }
 7318:                             }
 7319:                         }
 7320:                     }
 7321:                 }
 7322:             }
 7323:         }
 7324:     }
 7325: 
 7326: # Course
 7327: 
 7328:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7329:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7330:             $thisallowed.=$1;
 7331:         }
 7332:     }
 7333: 
 7334: # Domain
 7335: 
 7336:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7337:        =~/\Q$priv\E\&([^\:]*)/) {
 7338:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7339:             $thisallowed.=$1;
 7340:         }
 7341:     }
 7342: 
 7343: # User who is not author or co-author might still be able to edit
 7344: # resource of an author in the domain (e.g., if Domain Coordinator).
 7345:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7346:         (&allowed('mdc',$env{'request.course.id'}))) {
 7347:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7348:             $thisallowed.=$1;
 7349:         }
 7350:     }
 7351: 
 7352: # Course: uri itself is a course
 7353:     my $courseuri=$uri;
 7354:     $courseuri=~s/\_(\d)/\/$1/;
 7355:     $courseuri=~s/^([^\/])/\/$1/;
 7356: 
 7357:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7358:        =~/\Q$priv\E\&([^\:]*)/) {
 7359:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7360:             $thisallowed.=$1;
 7361:         }
 7362:     }
 7363: 
 7364: # URI is an uploaded document for this course, default permissions don't matter
 7365: # not allowing 'edit' access (editupload) to uploaded course docs
 7366:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7367: 	$thisallowed='';
 7368:         my ($match)=&is_on_map($uri);
 7369:         if ($match) {
 7370:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7371:                   =~/\Q$priv\E\&([^\:]*)/) {
 7372:                 my $value = $1;
 7373:                 if ($noblockcheck) {
 7374:                     $thisallowed.=$value;
 7375:                 } else {
 7376:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7377:                     if (@blockers > 0) {
 7378:                         $thisallowed = 'B';
 7379:                     } else {
 7380:                         $thisallowed.=$value;
 7381:                     }
 7382:                 }
 7383:             }
 7384:         } else {
 7385:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7386:             if ($refuri) {
 7387:                 if ($refuri =~ m|^/adm/|) {
 7388:                     $thisallowed='F';
 7389:                 } else {
 7390:                     $refuri=&declutter($refuri);
 7391:                     my ($match) = &is_on_map($refuri);
 7392:                     if ($match) {
 7393:                         if ($noblockcheck) {
 7394:                             $thisallowed='F';
 7395:                         } else {
 7396:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7397:                             if (@blockers > 0) {
 7398:                                 $thisallowed = 'B';
 7399:                             } else {
 7400:                                 $thisallowed='F';
 7401:                             }
 7402:                         }
 7403:                     }
 7404:                 }
 7405:             }
 7406:         }
 7407:     }
 7408: 
 7409:     if ($priv eq 'bre'
 7410: 	&& $thisallowed ne 'F' 
 7411: 	&& $thisallowed ne '2'
 7412: 	&& &is_portfolio_url($uri)) {
 7413: 	$thisallowed = &portfolio_access($uri,$clientip);
 7414:     }
 7415:     
 7416: # Full access at system, domain or course-wide level? Exit.
 7417:     if ($thisallowed=~/F/) {
 7418: 	return 'F';
 7419:     }
 7420: 
 7421: # If this is generating or modifying users, exit with special codes
 7422: 
 7423:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7424: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7425: 	    my ($audom,$auname)=split('/',$uri);
 7426: # no author name given, so this just checks on the general right to make a co-author in this domain
 7427: 	    unless ($auname) { return $thisallowed; }
 7428: # an author name is given, so we are about to actually make a co-author for a certain account
 7429: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7430: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7431: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7432: 	}
 7433: 	return $thisallowed;
 7434:     }
 7435: #
 7436: # Gathered so far: system, domain and course wide privileges
 7437: #
 7438: # Course: See if uri or referer is an individual resource that is part of 
 7439: # the course
 7440: 
 7441:     if ($env{'request.course.id'}) {
 7442: 
 7443:        $courseprivid=$env{'request.course.id'};
 7444:        if ($env{'request.course.sec'}) {
 7445:           $courseprivid.='/'.$env{'request.course.sec'};
 7446:        }
 7447:        $courseprivid=~s/\_/\//;
 7448:        my $checkreferer=1;
 7449:        my ($match,$cond)=&is_on_map($uri);
 7450:        if ($match) {
 7451:            $statecond=$cond;
 7452:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7453:                =~/\Q$priv\E\&([^\:]*)/) {
 7454:                my $value = $1;
 7455:                if ($priv eq 'bre') {
 7456:                    if ($noblockcheck) {
 7457:                        $thisallowed.=$value;
 7458:                    } else {
 7459:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7460:                        if (@blockers > 0) {
 7461:                            $thisallowed = 'B';
 7462:                        } else {
 7463:                            $thisallowed.=$value;
 7464:                        }
 7465:                    }
 7466:                } else {
 7467:                    $thisallowed.=$value;
 7468:                }
 7469:                $checkreferer=0;
 7470:            }
 7471:        }
 7472:        
 7473:        if ($checkreferer) {
 7474: 	  my $refuri=$env{'httpref.'.$orguri};
 7475:             unless ($refuri) {
 7476:                 foreach my $key (keys(%env)) {
 7477: 		    if ($key=~/^httpref\..*\*/) {
 7478: 			my $pattern=$key;
 7479:                         $pattern=~s/^httpref\.\/res\///;
 7480:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7481:                         $pattern=~s/\//\\\//g;
 7482:                         if ($orguri=~/$pattern/) {
 7483: 			    $refuri=$env{$key};
 7484:                         }
 7485:                     }
 7486:                 }
 7487:             }
 7488: 
 7489:          if ($refuri) { 
 7490: 	  $refuri=&declutter($refuri);
 7491:           my ($match,$cond)=&is_on_map($refuri);
 7492:             if ($match) {
 7493:               my $refstatecond=$cond;
 7494:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7495:                   =~/\Q$priv\E\&([^\:]*)/) {
 7496:                   my $value = $1;
 7497:                   if ($priv eq 'bre') {
 7498:                       if ($noblockcheck) {
 7499:                           $thisallowed.=$value;
 7500:                       } else {
 7501:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7502:                           if (@blockers > 0) {
 7503:                               $thisallowed = 'B';
 7504:                           } else {
 7505:                               $thisallowed.=$value;
 7506:                           }
 7507:                       }
 7508:                   } else {
 7509:                       $thisallowed.=$value;
 7510:                   }
 7511:                   $uri=$refuri;
 7512:                   $statecond=$refstatecond;
 7513:               }
 7514:           }
 7515:         }
 7516:        }
 7517:    }
 7518: 
 7519: #
 7520: # Gathered now: all privileges that could apply, and condition number
 7521: # 
 7522: #
 7523: # Full or no access?
 7524: #
 7525: 
 7526:     if ($thisallowed=~/F/) {
 7527: 	return 'F';
 7528:     }
 7529: 
 7530:     unless ($thisallowed) {
 7531:         return '';
 7532:     }
 7533: 
 7534: # Restrictions exist, deal with them
 7535: #
 7536: #   C:according to course preferences
 7537: #   R:according to resource settings
 7538: #   L:unless locked
 7539: #   X:according to user session state
 7540: #
 7541: 
 7542: # Possibly locked functionality, check all courses
 7543: # Locks might take effect only after 10 minutes cache expiration for other
 7544: # courses, and 2 minutes for current course
 7545: 
 7546:     my $envkey;
 7547:     if ($thisallowed=~/L/) {
 7548:         foreach $envkey (keys(%env)) {
 7549:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7550:                my $courseid=$2;
 7551:                my $roleid=$1.'.'.$2;
 7552:                $courseid=~s/^\///;
 7553:                my $expiretime=600;
 7554:                if ($env{'request.role'} eq $roleid) {
 7555: 		  $expiretime=120;
 7556:                }
 7557: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7558:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7559:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7560: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7561:                }
 7562:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7563:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7564: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7565:                        &log($env{'user.domain'},$env{'user.name'},
 7566:                             $env{'user.home'},
 7567:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7568:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7569:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7570: 		       return '';
 7571:                    }
 7572:                }
 7573:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7574:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7575: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7576:                        &log($env{'user.domain'},$env{'user.name'},
 7577:                             $env{'user.home'},
 7578:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7579:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7580:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7581: 		       return '';
 7582:                    }
 7583:                }
 7584: 	   }
 7585:        }
 7586:     }
 7587:    
 7588: #
 7589: # Rest of the restrictions depend on selected course
 7590: #
 7591: 
 7592:     unless ($env{'request.course.id'}) {
 7593: 	if ($thisallowed eq 'A') {
 7594: 	    return 'A';
 7595:         } elsif ($thisallowed eq 'B') {
 7596:             return 'B';
 7597: 	} else {
 7598: 	    return '1';
 7599: 	}
 7600:     }
 7601: 
 7602: #
 7603: # Now user is definitely in a course
 7604: #
 7605: 
 7606: 
 7607: # Course preferences
 7608: 
 7609:    if ($thisallowed=~/C/) {
 7610:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7611:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7612:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7613: 	   =~/\Q$rolecode\E/) {
 7614: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7615: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7616: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7617: 			$env{'request.course.id'});
 7618: 	   }
 7619:            return '';
 7620:        }
 7621: 
 7622:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7623: 	   =~/\Q$unamedom\E/) {
 7624: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7625: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7626: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7627: 			$env{'request.course.id'});
 7628: 	   }
 7629:            return '';
 7630:        }
 7631:    }
 7632: 
 7633: # Resource preferences
 7634: 
 7635:    if ($thisallowed=~/R/) {
 7636:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7637:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7638: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7639: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7640: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7641: 	   }
 7642: 	   return '';
 7643:        }
 7644:    }
 7645: 
 7646: # Restricted by state or randomout?
 7647: 
 7648:    if ($thisallowed=~/X/) {
 7649:       if ($env{'acc.randomout'}) {
 7650: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7651:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7652:             return ''; 
 7653:          }
 7654:       }
 7655:       if (&condval($statecond)) {
 7656: 	 return '2';
 7657:       } else {
 7658:          return '';
 7659:       }
 7660:    }
 7661: 
 7662:     if ($thisallowed eq 'A') {
 7663: 	return 'A';
 7664:     } elsif ($thisallowed eq 'B') {
 7665:         return 'B';
 7666:     }
 7667:    return 'F';
 7668: }
 7669: 
 7670: # ------------------------------------------- Check construction space access
 7671: 
 7672: sub constructaccess {
 7673:     my ($url,$setpriv)=@_;
 7674: 
 7675: # We do not allow editing of previous versions of files
 7676:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7677: 
 7678: # Get username and domain from URL
 7679:     my ($ownername,$ownerdomain,$ownerhome);
 7680: 
 7681:     ($ownerdomain,$ownername) =
 7682:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
 7683: 
 7684: # The URL does not really point to any authorspace, forget it
 7685:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7686: 
 7687: # Now we need to see if the user has access to the authorspace of
 7688: # $ownername at $ownerdomain
 7689: 
 7690:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7691: # Real author for this?
 7692:        $ownerhome = $env{'user.home'};
 7693:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7694:           return ($ownername,$ownerdomain,$ownerhome);
 7695:        }
 7696:     } else {
 7697: # Co-author for this?
 7698:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7699:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7700:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7701:             return ($ownername,$ownerdomain,$ownerhome);
 7702:         }
 7703:     }
 7704: 
 7705: # We don't have any access right now. If we are not possibly going to do anything about this,
 7706: # we might as well leave
 7707:    unless ($setpriv) { return ''; }
 7708: 
 7709: # Backdoor access?
 7710:     my $allowed=&allowed('eco',$ownerdomain);
 7711: # Nope
 7712:     unless ($allowed) { return ''; }
 7713: # Looks like we may have access, but could be locked by the owner of the construction space
 7714:     if ($allowed eq 'U') {
 7715:         my %blocked=&get('environment',['domcoord.author'],
 7716:                          $ownerdomain,$ownername);
 7717: # Is blocked by owner
 7718:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7719:     }
 7720:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7721: # Grant temporary access
 7722:         my $then=$env{'user.login.time'};
 7723:         my $update=$env{'user.update.time'};
 7724:         if (!$update) { $update = $then; }
 7725:         my $refresh=$env{'user.refresh.time'};
 7726:         if (!$refresh) { $refresh = $update; }
 7727:         my $now = time;
 7728:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7729:                            $now,'ca','constructaccess');
 7730:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7731:         return($ownername,$ownerdomain,$ownerhome);
 7732:     }
 7733: # No business here
 7734:     return '';
 7735: }
 7736: 
 7737: # ----------------------------------------------------------- Content Blocking
 7738: 
 7739: {
 7740: # Caches for faster Course Contents display where content blocking
 7741: # is in operation (i.e., interval param set) for timed quiz.
 7742: #
 7743: # User for whom data are being temporarily cached.
 7744: my $cacheduser='';
 7745: # Cached blockers for this user (a hash of blocking items).
 7746: my %cachedblockers=();
 7747: # When the data were last cached.
 7748: my $cachedlast='';
 7749: 
 7750: sub load_all_blockers {
 7751:     my ($uname,$udom,$blocks)=@_;
 7752:     if (($uname ne '') && ($udom ne '')) {
 7753:         if (($cacheduser eq $uname.':'.$udom) &&
 7754:             (abs($cachedlast-time)<5)) {
 7755:             return;
 7756:         }
 7757:     }
 7758:     $cachedlast=time;
 7759:     $cacheduser=$uname.':'.$udom;
 7760:     %cachedblockers = &get_commblock_resources($blocks);
 7761: }
 7762: 
 7763: sub get_comm_blocks {
 7764:     my ($cdom,$cnum) = @_;
 7765:     if ($cdom eq '' || $cnum eq '') {
 7766:         return unless ($env{'request.course.id'});
 7767:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7768:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7769:     }
 7770:     my %commblocks;
 7771:     my $hashid=$cdom.'_'.$cnum;
 7772:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7773:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7774:         %commblocks = %{$blocksref};
 7775:     } else {
 7776:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7777:         my $cachetime = 600;
 7778:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7779:     }
 7780:     return %commblocks;
 7781: }
 7782: 
 7783: sub get_commblock_resources {
 7784:     my ($blocks) = @_;
 7785:     my %blockers = ();
 7786:     return %blockers unless ($env{'request.course.id'});
 7787:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7788:     my %commblocks;
 7789:     if (ref($blocks) eq 'HASH') {
 7790:         %commblocks = %{$blocks};
 7791:     } else {
 7792:         %commblocks = &get_comm_blocks();
 7793:     }
 7794:     return %blockers unless (keys(%commblocks) > 0);
 7795:     my $navmap = Apache::lonnavmaps::navmap->new();
 7796:     return %blockers unless (ref($navmap));
 7797:     my $now = time;
 7798:     foreach my $block (keys(%commblocks)) {
 7799:         if ($block =~ /^(\d+)____(\d+)$/) {
 7800:             my ($start,$end) = ($1,$2);
 7801:             if ($start <= $now && $end >= $now) {
 7802:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7803:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7804:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7805:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 7806:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 7807:                             }
 7808:                         }
 7809:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7810:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 7811:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 7812:                             }
 7813:                         }
 7814:                     }
 7815:                 }
 7816:             }
 7817:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7818:             my $item = $1;
 7819:             my @to_test;
 7820:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7821:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7822:                     my @interval;
 7823:                     my $type = 'map';
 7824:                     if ($item eq 'course') {
 7825:                         $type = 'course';
 7826:                         @interval=&EXT("resource.0.interval");
 7827:                     } else {
 7828:                         if ($item =~ /___\d+___/) {
 7829:                             $type = 'resource';
 7830:                             @interval=&EXT("resource.0.interval",$item);
 7831:                             if (ref($navmap)) {
 7832:                                 my $res = $navmap->getBySymb($item);
 7833:                                 push(@to_test,$res);
 7834:                             }
 7835:                         } else {
 7836:                             my $mapsymb = &symbread($item,1);
 7837:                             if ($mapsymb) {
 7838:                                 if (ref($navmap)) {
 7839:                                     my $mapres = $navmap->getBySymb($mapsymb);
 7840:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 7841:                                     foreach my $res (@to_test) {
 7842:                                         my $symb = $res->symb();
 7843:                                         next if ($symb eq $mapsymb);
 7844:                                         if ($symb ne '') {
 7845:                                             @interval=&EXT("resource.0.interval",$symb);
 7846:                                             if ($interval[1] eq 'map') {
 7847:                                                 last;
 7848:                                             }
 7849:                                         }
 7850:                                     }
 7851:                                 }
 7852:                             }
 7853:                         }
 7854:                     }
 7855:                     if ($interval[0] =~ /^(\d+)/) {
 7856:                         my $timelimit = $1;
 7857:                         my $first_access;
 7858:                         if ($type eq 'resource') {
 7859:                             $first_access=&get_first_access($interval[1],$item);
 7860:                         } elsif ($type eq 'map') {
 7861:                             $first_access=&get_first_access($interval[1],undef,$item);
 7862:                         } else {
 7863:                             $first_access=&get_first_access($interval[1]);
 7864:                         }
 7865:                         if ($first_access) {
 7866:                             my $timesup = $first_access+$timelimit;
 7867:                             if ($timesup > $now) {
 7868:                                 my $activeblock;
 7869:                                 foreach my $res (@to_test) {
 7870:                                     if ($res->answerable()) {
 7871:                                         $activeblock = 1;
 7872:                                         last;
 7873:                                     }
 7874:                                 }
 7875:                                 if ($activeblock) {
 7876:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7877:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 7878:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 7879:                                          }
 7880:                                     }
 7881:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7882:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 7883:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 7884:                                         }
 7885:                                     }
 7886:                                 }
 7887:                             }
 7888:                         }
 7889:                     }
 7890:                 }
 7891:             }
 7892:         }
 7893:     }
 7894:     return %blockers;
 7895: }
 7896: 
 7897: sub has_comm_blocking {
 7898:     my ($priv,$symb,$uri,$blocks) = @_;
 7899:     my @blockers;
 7900:     return unless ($env{'request.course.id'});
 7901:     return unless ($priv eq 'bre');
 7902:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7903:     return if ($env{'request.state'} eq 'construct');
 7904:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 7905:     return unless (keys(%cachedblockers) > 0);
 7906:     my (%possibles,@symbs);
 7907:     if (!$symb) {
 7908:         $symb = &symbread($uri,1,1,1,\%possibles);
 7909:     }
 7910:     if ($symb) {
 7911:         @symbs = ($symb);
 7912:     } elsif (keys(%possibles)) {
 7913:         @symbs = keys(%possibles);
 7914:     }
 7915:     my $noblock;
 7916:     foreach my $symb (@symbs) {
 7917:         last if ($noblock);
 7918:         my ($map,$resid,$resurl)=&decode_symb($symb);
 7919:         foreach my $block (keys(%cachedblockers)) {
 7920:             if ($block =~ /^firstaccess____(.+)$/) {
 7921:                 my $item = $1;
 7922:                 if (($item eq $map) || ($item eq $symb)) {
 7923:                     $noblock = 1;
 7924:                     last;
 7925:                 }
 7926:             }
 7927:             if (ref($cachedblockers{$block}) eq 'HASH') {
 7928:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 7929:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 7930:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 7931:                             push(@blockers,$block);
 7932:                         }
 7933:                     }
 7934:                 }
 7935:             }
 7936:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 7937:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 7938:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 7939:                         push(@blockers,$block);
 7940:                     }
 7941:                 }
 7942:             }
 7943:         }
 7944:     }
 7945:     return if ($noblock);
 7946:     return @blockers;
 7947: }
 7948: }
 7949: 
 7950: # -------------------------------- Deversion and split uri into path an filename
 7951: 
 7952: #
 7953: #   Removes the version from a URI and
 7954: #   splits it in to its filename and path to the filename.
 7955: #   Seems like File::Basename could have done this more clearly.
 7956: #   Parameters:
 7957: #      $uri   - input URI
 7958: #   Returns:
 7959: #     Two element list consisting of 
 7960: #     $pathname  - the URI up to and excluding the trailing /
 7961: #     $filename  - The part of the URI following the last /
 7962: #  NOTE:
 7963: #    Another realization of this is simply:
 7964: #    use File::Basename;
 7965: #    ...
 7966: #    $uri = shift;
 7967: #    $filename = basename($uri);
 7968: #    $path     = dirname($uri);
 7969: #    return ($filename, $path);
 7970: #
 7971: #     The implementation below is probably faster however.
 7972: #
 7973: sub split_uri_for_cond {
 7974:     my $uri=&deversion(&declutter(shift));
 7975:     my @uriparts=split(/\//,$uri);
 7976:     my $filename=pop(@uriparts);
 7977:     my $pathname=join('/',@uriparts);
 7978:     return ($pathname,$filename);
 7979: }
 7980: # --------------------------------------------------- Is a resource on the map?
 7981: 
 7982: sub is_on_map {
 7983:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7984:     #Trying to find the conditional for the file
 7985:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7986: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7987:     if ($match) {
 7988: 	return (1,$1);
 7989:     } else {
 7990: 	return (0,0);
 7991:     }
 7992: }
 7993: 
 7994: # --------------------------------------------------------- Get symb from alias
 7995: 
 7996: sub get_symb_from_alias {
 7997:     my $symb=shift;
 7998:     my ($map,$resid,$url)=&decode_symb($symb);
 7999: # Already is a symb
 8000:     if ($url) { return $symb; }
 8001: # Must be an alias
 8002:     my $aliassymb='';
 8003:     my %bighash;
 8004:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8005:                             &GDBM_READER(),0640)) {
 8006:         my $rid=$bighash{'mapalias_'.$symb};
 8007: 	if ($rid) {
 8008: 	    my ($mapid,$resid)=split(/\./,$rid);
 8009: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8010: 				    $resid,$bighash{'src_'.$rid});
 8011: 	}
 8012:         untie %bighash;
 8013:     }
 8014:     return $aliassymb;
 8015: }
 8016: 
 8017: # ----------------------------------------------------------------- Define Role
 8018: 
 8019: sub definerole {
 8020:   if (allowed('mcr','/')) {
 8021:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8022:     foreach my $role (split(':',$sysrole)) {
 8023: 	my ($crole,$cqual)=split(/\&/,$role);
 8024:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8025:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8026: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8027:                return "refused:s:$crole&$cqual"; 
 8028:             }
 8029:         }
 8030:     }
 8031:     foreach my $role (split(':',$domrole)) {
 8032: 	my ($crole,$cqual)=split(/\&/,$role);
 8033:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8034:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8035: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8036:                return "refused:d:$crole&$cqual"; 
 8037:             }
 8038:         }
 8039:     }
 8040:     foreach my $role (split(':',$courole)) {
 8041: 	my ($crole,$cqual)=split(/\&/,$role);
 8042:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8043:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8044: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8045:                return "refused:c:$crole&$cqual"; 
 8046:             }
 8047:         }
 8048:     }
 8049:     my $uhome;
 8050:     if (($uname ne '') && ($udom ne '')) {
 8051:         $uhome = &homeserver($uname,$udom);
 8052:         return $uhome if ($uhome eq 'no_host');
 8053:     } else {
 8054:         $uname = $env{'user.name'};
 8055:         $udom = $env{'user.domain'};
 8056:         $uhome = $env{'user.home'};
 8057:     }
 8058:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8059:                 "$udom:$uname:rolesdef_$rolename=".
 8060:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8061:     return reply($command,$uhome);
 8062:   } else {
 8063:     return 'refused';
 8064:   }
 8065: }
 8066: 
 8067: # ---------------- Make a metadata query against the network of library servers
 8068: 
 8069: sub metadata_query {
 8070:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8071:     my %rhash;
 8072:     my %libserv = &all_library();
 8073:     my @server_list = (defined($server_array) ? @$server_array
 8074:                                               : keys(%libserv) );
 8075:     for my $server (@server_list) {
 8076:         my $domains = '';
 8077:         if (ref($domains_hash) eq 'HASH') {
 8078:             $domains = $domains_hash->{$server};    
 8079:         }
 8080: 	unless ($custom or $customshow) {
 8081: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8082: 	    $rhash{$server}=$reply;
 8083: 	}
 8084: 	else {
 8085: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8086: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8087: 			     $server);
 8088: 	    $rhash{$server}=$reply;
 8089: 	}
 8090:     }
 8091:     return \%rhash;
 8092: }
 8093: 
 8094: # ----------------------------------------- Send log queries and wait for reply
 8095: 
 8096: sub log_query {
 8097:     my ($uname,$udom,$query,%filters)=@_;
 8098:     my $uhome=&homeserver($uname,$udom);
 8099:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8100:     my $uhost=&hostname($uhome);
 8101:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8102:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8103:                        $uhome);
 8104:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8105:     return get_query_reply($queryid);
 8106: }
 8107: 
 8108: # -------------------------- Update MySQL table for portfolio file
 8109: 
 8110: sub update_portfolio_table {
 8111:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8112:     if ($group ne '') {
 8113:         $file_name =~s /^\Q$group\E//;
 8114:     }
 8115:     my $homeserver = &homeserver($uname,$udom);
 8116:     my $queryid=
 8117:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8118:                ':'.&escape($file_name).':'.$action,$homeserver);
 8119:     my $reply = &get_query_reply($queryid);
 8120:     return $reply;
 8121: }
 8122: 
 8123: # -------------------------- Update MySQL allusers table
 8124: 
 8125: sub update_allusers_table {
 8126:     my ($uname,$udom,$names) = @_;
 8127:     my $homeserver = &homeserver($uname,$udom);
 8128:     my $queryid=
 8129:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8130:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8131:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8132:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8133:                'generation='.&escape($names->{'generation'}).'%%'.
 8134:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8135:                'id='.&escape($names->{'id'}),$homeserver);
 8136:     return;
 8137: }
 8138: 
 8139: # ------- Request retrieval of institutional classlists for course(s)
 8140: 
 8141: sub fetch_enrollment_query {
 8142:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8143:     my ($homeserver,$sleep,$loopmax);
 8144:     my $maxtries = 1;
 8145:     if ($context eq 'automated') {
 8146:         $homeserver = $perlvar{'lonHostID'};
 8147:         $sleep = 2;
 8148:         $loopmax = 100;
 8149:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8150:     } else {
 8151:         $homeserver = &homeserver($cnum,$dom);
 8152:     }
 8153:     my $host=&hostname($homeserver);
 8154:     my $cmd = '';
 8155:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8156:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8157:     }
 8158:     $cmd =~ s/%%$//;
 8159:     $cmd = &escape($cmd);
 8160:     my $query = 'fetchenrollment';
 8161:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8162:     unless ($queryid=~/^\Q$host\E\_/) { 
 8163:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8164:         return 'error: '.$queryid;
 8165:     }
 8166:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8167:     my $tries = 1;
 8168:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8169:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8170:         $tries ++;
 8171:     }
 8172:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8173:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8174:     } else {
 8175:         my @responses = split(/:/,$reply);
 8176:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8177:             foreach my $line (@responses) {
 8178:                 my ($key,$value) = split(/=/,$line,2);
 8179:                 $$replyref{$key} = $value;
 8180:             }
 8181:         } else {
 8182:             my $pathname = LONCAPA::tempdir();
 8183:             foreach my $line (@responses) {
 8184:                 my ($key,$value) = split(/=/,$line);
 8185:                 $$replyref{$key} = $value;
 8186:                 if ($value > 0) {
 8187:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8188:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8189:                         my $destname = $pathname.'/'.$filename;
 8190:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8191:                         if ($xml_classlist =~ /^error/) {
 8192:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8193:                         } else {
 8194:                             if ( open(FILE,">",$destname) ) {
 8195:                                 print FILE &unescape($xml_classlist);
 8196:                                 close(FILE);
 8197:                             } else {
 8198:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8199:                             }
 8200:                         }
 8201:                     }
 8202:                 }
 8203:             }
 8204:         }
 8205:         return 'ok';
 8206:     }
 8207:     return 'error';
 8208: }
 8209: 
 8210: sub get_query_reply {
 8211:     my ($queryid,$sleep,$loopmax) = @_;
 8212:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8213:         $sleep = 0.2;
 8214:     }
 8215:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8216:         $loopmax = 100;
 8217:     }
 8218:     my $replyfile=LONCAPA::tempdir().$queryid;
 8219:     my $reply='';
 8220:     for (1..$loopmax) {
 8221: 	sleep($sleep);
 8222:         if (-e $replyfile.'.end') {
 8223: 	    if (open(my $fh,"<",$replyfile)) {
 8224: 		$reply = join('',<$fh>);
 8225: 		close($fh);
 8226: 	   } else { return 'error: reply_file_error'; }
 8227:            return &unescape($reply);
 8228: 	}
 8229:     }
 8230:     return 'timeout:'.$queryid;
 8231: }
 8232: 
 8233: sub courselog_query {
 8234: #
 8235: # possible filters:
 8236: # url: url or symb
 8237: # username
 8238: # domain
 8239: # action: view, submit, grade
 8240: # start: timestamp
 8241: # end: timestamp
 8242: #
 8243:     my (%filters)=@_;
 8244:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8245:     if ($filters{'url'}) {
 8246: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8247:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8248:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8249:     }
 8250:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8251:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8252:     return &log_query($cname,$cdom,'courselog',%filters);
 8253: }
 8254: 
 8255: sub userlog_query {
 8256: #
 8257: # possible filters:
 8258: # action: log check role
 8259: # start: timestamp
 8260: # end: timestamp
 8261: #
 8262:     my ($uname,$udom,%filters)=@_;
 8263:     return &log_query($uname,$udom,'userlog',%filters);
 8264: }
 8265: 
 8266: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8267: 
 8268: sub auto_run {
 8269:     my ($cnum,$cdom) = @_;
 8270:     my $response = 0;
 8271:     my $settings;
 8272:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8273:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8274:         $settings = $domconfig{'autoenroll'};
 8275:         if ($settings->{'run'} eq '1') {
 8276:             $response = 1;
 8277:         }
 8278:     } else {
 8279:         my $homeserver;
 8280:         if (&is_course($cdom,$cnum)) {
 8281:             $homeserver = &homeserver($cnum,$cdom);
 8282:         } else {
 8283:             $homeserver = &domain($cdom,'primary');
 8284:         }
 8285:         if ($homeserver ne 'no_host') {
 8286:             $response = &reply('autorun:'.$cdom,$homeserver);
 8287:         }
 8288:     }
 8289:     return $response;
 8290: }
 8291: 
 8292: sub auto_get_sections {
 8293:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8294:     my $homeserver;
 8295:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8296:         $homeserver = &homeserver($cnum,$cdom);
 8297:     }
 8298:     if (!defined($homeserver)) { 
 8299:         if ($cdom =~ /^$match_domain$/) {
 8300:             $homeserver = &domain($cdom,'primary');
 8301:         }
 8302:     }
 8303:     my @secs;
 8304:     if (defined($homeserver)) {
 8305:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8306:         unless ($response eq 'refused') {
 8307:             @secs = split(/:/,$response);
 8308:         }
 8309:     }
 8310:     return @secs;
 8311: }
 8312: 
 8313: sub auto_new_course {
 8314:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8315:     my $homeserver = &homeserver($cnum,$cdom);
 8316:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8317:     return $response;
 8318: }
 8319: 
 8320: sub auto_validate_courseID {
 8321:     my ($cnum,$cdom,$inst_course_id) = @_;
 8322:     my $homeserver = &homeserver($cnum,$cdom);
 8323:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8324:     return $response;
 8325: }
 8326: 
 8327: sub auto_validate_instcode {
 8328:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8329:     my ($homeserver,$response);
 8330:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8331:         $homeserver = &homeserver($cnum,$cdom);
 8332:     }
 8333:     if (!defined($homeserver)) {
 8334:         if ($cdom =~ /^$match_domain$/) {
 8335:             $homeserver = &domain($cdom,'primary');
 8336:         }
 8337:     }
 8338:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8339:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8340:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8341:     return ($outcome,$description,$defaultcredits);
 8342: }
 8343: 
 8344: sub auto_create_password {
 8345:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8346:     my ($homeserver,$response);
 8347:     my $create_passwd = 0;
 8348:     my $authchk = '';
 8349:     if ($udom =~ /^$match_domain$/) {
 8350:         $homeserver = &domain($udom,'primary');
 8351:     }
 8352:     if ($homeserver eq '') {
 8353:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8354:             $homeserver = &homeserver($cnum,$cdom);
 8355:         }
 8356:     }
 8357:     if ($homeserver eq '') {
 8358:         $authchk = 'nodomain';
 8359:     } else {
 8360:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8361:         if ($response eq 'refused') {
 8362:             $authchk = 'refused';
 8363:         } else {
 8364:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8365:         }
 8366:     }
 8367:     return ($authparam,$create_passwd,$authchk);
 8368: }
 8369: 
 8370: sub auto_photo_permission {
 8371:     my ($cnum,$cdom,$students) = @_;
 8372:     my $homeserver = &homeserver($cnum,$cdom);
 8373:     my ($outcome,$perm_reqd,$conditions) = 
 8374: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8375:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8376: 	return (undef,undef);
 8377:     }
 8378:     return ($outcome,$perm_reqd,$conditions);
 8379: }
 8380: 
 8381: sub auto_checkphotos {
 8382:     my ($uname,$udom,$pid) = @_;
 8383:     my $homeserver = &homeserver($uname,$udom);
 8384:     my ($result,$resulttype);
 8385:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8386: 				   &escape($uname).':'.&escape($pid),
 8387: 				   $homeserver));
 8388:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8389: 	return (undef,undef);
 8390:     }
 8391:     if ($outcome) {
 8392:         ($result,$resulttype) = split(/:/,$outcome);
 8393:     } 
 8394:     return ($result,$resulttype);
 8395: }
 8396: 
 8397: sub auto_photochoice {
 8398:     my ($cnum,$cdom) = @_;
 8399:     my $homeserver = &homeserver($cnum,$cdom);
 8400:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8401: 						       &escape($cdom),
 8402: 						       $homeserver)));
 8403:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8404: 	return (undef,undef);
 8405:     }
 8406:     return ($update,$comment);
 8407: }
 8408: 
 8409: sub auto_photoupdate {
 8410:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8411:     my $homeserver = &homeserver($cnum,$dom);
 8412:     my $host=&hostname($homeserver);
 8413:     my $cmd = '';
 8414:     my $maxtries = 1;
 8415:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8416:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8417:     }
 8418:     $cmd =~ s/%%$//;
 8419:     $cmd = &escape($cmd);
 8420:     my $query = 'institutionalphotos';
 8421:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8422:     unless ($queryid=~/^\Q$host\E\_/) {
 8423:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8424:         return 'error: '.$queryid;
 8425:     }
 8426:     my $reply = &get_query_reply($queryid);
 8427:     my $tries = 1;
 8428:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8429:         $reply = &get_query_reply($queryid);
 8430:         $tries ++;
 8431:     }
 8432:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8433:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8434:     } else {
 8435:         my @responses = split(/:/,$reply);
 8436:         my $outcome = shift(@responses); 
 8437:         foreach my $item (@responses) {
 8438:             my ($key,$value) = split(/=/,$item);
 8439:             $$photo{$key} = $value;
 8440:         }
 8441:         return $outcome;
 8442:     }
 8443:     return 'error';
 8444: }
 8445: 
 8446: sub auto_instcode_format {
 8447:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8448: 	$cat_order) = @_;
 8449:     my $courses = '';
 8450:     my @homeservers;
 8451:     if ($caller eq 'global') {
 8452: 	my %servers = &get_servers($codedom,'library');
 8453: 	foreach my $tryserver (keys(%servers)) {
 8454: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8455: 		push(@homeservers,$tryserver);
 8456: 	    }
 8457:         }
 8458:     } elsif ($caller eq 'requests') {
 8459:         if ($codedom =~ /^$match_domain$/) {
 8460:             my $chome = &domain($codedom,'primary');
 8461:             unless ($chome eq 'no_host') {
 8462:                 push(@homeservers,$chome);
 8463:             }
 8464:         }
 8465:     } else {
 8466:         push(@homeservers,&homeserver($caller,$codedom));
 8467:     }
 8468:     foreach my $code (keys(%{$instcodes})) {
 8469:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8470:     }
 8471:     chop($courses);
 8472:     my $ok_response = 0;
 8473:     my $response;
 8474:     while (@homeservers > 0 && $ok_response == 0) {
 8475:         my $server = shift(@homeservers); 
 8476:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8477:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8478:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8479: 		split(/:/,$response);
 8480:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8481:             push(@{$codetitles},&str2array($codetitles_str));
 8482:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8483:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8484:             $ok_response = 1;
 8485:         }
 8486:     }
 8487:     if ($ok_response) {
 8488:         return 'ok';
 8489:     } else {
 8490:         return $response;
 8491:     }
 8492: }
 8493: 
 8494: sub auto_instcode_defaults {
 8495:     my ($domain,$returnhash,$code_order) = @_;
 8496:     my @homeservers;
 8497: 
 8498:     my %servers = &get_servers($domain,'library');
 8499:     foreach my $tryserver (keys(%servers)) {
 8500: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8501: 	    push(@homeservers,$tryserver);
 8502: 	}
 8503:     }
 8504: 
 8505:     my $response;
 8506:     foreach my $server (@homeservers) {
 8507:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8508:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8509: 	
 8510: 	foreach my $pair (split(/\&/,$response)) {
 8511: 	    my ($name,$value)=split(/\=/,$pair);
 8512: 	    if ($name eq 'code_order') {
 8513: 		@{$code_order} = split(/\&/,&unescape($value));
 8514: 	    } else {
 8515: 		$returnhash->{&unescape($name)}=&unescape($value);
 8516: 	    }
 8517: 	}
 8518: 	return 'ok';
 8519:     }
 8520: 
 8521:     return $response;
 8522: }
 8523: 
 8524: sub auto_possible_instcodes {
 8525:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8526:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8527:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8528:         return;
 8529:     }
 8530:     my (@homeservers,$uhome);
 8531:     if (defined(&domain($domain,'primary'))) {
 8532:         $uhome=&domain($domain,'primary');
 8533:         push(@homeservers,&domain($domain,'primary'));
 8534:     } else {
 8535:         my %servers = &get_servers($domain,'library');
 8536:         foreach my $tryserver (keys(%servers)) {
 8537:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8538:                 push(@homeservers,$tryserver);
 8539:             }
 8540:         }
 8541:     }
 8542:     my $response;
 8543:     foreach my $server (@homeservers) {
 8544:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8545:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8546:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8547:             split(':',$response);
 8548:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8549:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8550:         foreach my $item (split('&',$cat_title)) {   
 8551:             my ($name,$value)=split('=',$item);
 8552:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8553:         }
 8554:         foreach my $item (split('&',$cat_order)) {
 8555:             my ($name,$value)=split('=',$item);
 8556:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8557:         }
 8558:         return 'ok';
 8559:     }
 8560:     return $response;
 8561: }
 8562: 
 8563: sub auto_courserequest_checks {
 8564:     my ($dom) = @_;
 8565:     my ($homeserver,%validations);
 8566:     if ($dom =~ /^$match_domain$/) {
 8567:         $homeserver = &domain($dom,'primary');
 8568:     }
 8569:     unless ($homeserver eq 'no_host') {
 8570:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8571:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8572:             my @items = split(/&/,$response);
 8573:             foreach my $item (@items) {
 8574:                 my ($key,$value) = split('=',$item);
 8575:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8576:             }
 8577:         }
 8578:     }
 8579:     return %validations; 
 8580: }
 8581: 
 8582: sub auto_courserequest_validation {
 8583:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8584:     my ($homeserver,$response);
 8585:     if ($dom =~ /^$match_domain$/) {
 8586:         $homeserver = &domain($dom,'primary');
 8587:     }
 8588:     unless ($homeserver eq 'no_host') {
 8589:         my $customdata;
 8590:         if (ref($custominfo) eq 'HASH') {
 8591:             $customdata = &freeze_escape($custominfo);
 8592:         }
 8593:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8594:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8595:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8596:                                     $customdata,$homeserver));
 8597:     }
 8598:     return $response;
 8599: }
 8600: 
 8601: sub auto_validate_class_sec {
 8602:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8603:     my $homeserver = &homeserver($cnum,$cdom);
 8604:     my $ownerlist;
 8605:     if (ref($owners) eq 'ARRAY') {
 8606:         $ownerlist = join(',',@{$owners});
 8607:     } else {
 8608:         $ownerlist = $owners;
 8609:     }
 8610:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8611:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8612:     return $response;
 8613: }
 8614: 
 8615: sub auto_crsreq_update {
 8616:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8617:         $code,$accessstart,$accessend,$inbound) = @_;
 8618:     my ($homeserver,%crsreqresponse);
 8619:     if ($cdom =~ /^$match_domain$/) {
 8620:         $homeserver = &domain($cdom,'primary');
 8621:     }
 8622:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8623:         my $info;
 8624:         if (ref($inbound) eq 'HASH') {
 8625:             $info = &freeze_escape($inbound);
 8626:         }
 8627:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8628:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8629:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8630:                             &escape($title).':'.&escape($code).':'.
 8631:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
 8632:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8633:             my @items = split(/&/,$response);
 8634:             foreach my $item (@items) {
 8635:                 my ($key,$value) = split('=',$item);
 8636:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8637:             }
 8638:         }
 8639:     }
 8640:     return \%crsreqresponse;
 8641: }
 8642: 
 8643: sub auto_export_grades {
 8644:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 8645:     my ($homeserver,%exportresponse);
 8646:     if ($cdom =~ /^$match_domain$/) {
 8647:         $homeserver = &domain($cdom,'primary');
 8648:     }
 8649:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8650:         my $info;
 8651:         if (ref($inforef) eq 'HASH') {
 8652:             $info = &freeze_escape($inforef);
 8653:         }
 8654:         if (ref($gradesref) eq 'HASH') {
 8655:             my $grades = &freeze_escape($gradesref);
 8656:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 8657:                                 $info.':'.$grades,$homeserver);
 8658:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 8659:                 my @items = split(/&/,$response);
 8660:                 foreach my $item (@items) {
 8661:                     my ($key,$value) = split('=',$item);
 8662:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 8663:                 }
 8664:             }
 8665:         }
 8666:     }
 8667:     return \%exportresponse;
 8668: }
 8669: 
 8670: sub check_instcode_cloning {
 8671:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 8672:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8673:         return;
 8674:     }
 8675:     my $canclone;
 8676:     if (@{$code_order} > 0) {
 8677:         my $instcoderegexp ='^';
 8678:         my @clonecodes = split(/\&/,$cloner);
 8679:         foreach my $item (@{$code_order}) {
 8680:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 8681:                 foreach my $pair (@clonecodes) {
 8682:                     my ($key,$val) = split(/\=/,$pair,2);
 8683:                     $val = &unescape($val);
 8684:                     if ($key eq $item) {
 8685:                         $instcoderegexp .= '('.$val.')';
 8686:                         last;
 8687:                     }
 8688:                 }
 8689:             } else {
 8690:                 $instcoderegexp .= $codedefaults->{$item};
 8691:             }
 8692:         }
 8693:         $instcoderegexp .= '$';
 8694:         my (@from,@to);
 8695:         eval {
 8696:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8697:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 8698:         };
 8699:         if ((@from > 0) && (@to > 0)) {
 8700:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8701:             if (!@diffs) {
 8702:                 $canclone = 1;
 8703:             }
 8704:         }
 8705:     }
 8706:     return $canclone;
 8707: }
 8708: 
 8709: sub default_instcode_cloning {
 8710:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 8711:     my (%codedefaults,@code_order,$canclone);
 8712:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 8713:         %codedefaults = %{$codedefaultsref};
 8714:         @code_order = @{$codeorderref};
 8715:     } elsif ($clonedom) {
 8716:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 8717:     }
 8718:     if (($domdefclone) && (@code_order)) {
 8719:         my @clonecodes = split(/\+/,$domdefclone);
 8720:         my $instcoderegexp ='^';
 8721:         foreach my $item (@code_order) {
 8722:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 8723:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 8724:             } else {
 8725:                 $instcoderegexp .= $codedefaults{$item};
 8726:             }
 8727:         }
 8728:         $instcoderegexp .= '$';
 8729:         my (@from,@to);
 8730:         eval {
 8731:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8732:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 8733:         };
 8734:         if ((@from > 0) && (@to > 0)) {
 8735:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8736:             if (!@diffs) {
 8737:                 $canclone = 1;
 8738:             }
 8739:         }
 8740:     }
 8741:     return $canclone;
 8742: }
 8743: 
 8744: # ------------------------------------------------------- Course Group routines
 8745: 
 8746: sub get_coursegroups {
 8747:     my ($cdom,$cnum,$group,$namespace) = @_;
 8748:     return(&dump($namespace,$cdom,$cnum,$group));
 8749: }
 8750: 
 8751: sub modify_coursegroup {
 8752:     my ($cdom,$cnum,$groupsettings) = @_;
 8753:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 8754: }
 8755: 
 8756: sub toggle_coursegroup_status {
 8757:     my ($cdom,$cnum,$group,$action) = @_;
 8758:     my ($from_namespace,$to_namespace);
 8759:     if ($action eq 'delete') {
 8760:         $from_namespace = 'coursegroups';
 8761:         $to_namespace = 'deleted_groups';
 8762:     } else {
 8763:         $from_namespace = 'deleted_groups';
 8764:         $to_namespace = 'coursegroups';
 8765:     }
 8766:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 8767:     if (my $tmp = &error(%curr_group)) {
 8768:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 8769:         return ('read error',$tmp);
 8770:     } else {
 8771:         my %savedsettings = %curr_group; 
 8772:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 8773:         my $deloutcome;
 8774:         if ($result eq 'ok') {
 8775:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 8776:         } else {
 8777:             return ('write error',$result);
 8778:         }
 8779:         if ($deloutcome eq 'ok') {
 8780:             return 'ok';
 8781:         } else {
 8782:             return ('delete error',$deloutcome);
 8783:         }
 8784:     }
 8785: }
 8786: 
 8787: sub modify_group_roles {
 8788:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 8789:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 8790:     my $role = 'gr/'.&escape($userprivs);
 8791:     my ($uname,$udom) = split(/:/,$user);
 8792:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 8793:     if ($result eq 'ok') {
 8794:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 8795:     }
 8796:     return $result;
 8797: }
 8798: 
 8799: sub modify_coursegroup_membership {
 8800:     my ($cdom,$cnum,$membership) = @_;
 8801:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 8802:     return $result;
 8803: }
 8804: 
 8805: sub get_active_groups {
 8806:     my ($udom,$uname,$cdom,$cnum) = @_;
 8807:     my $now = time;
 8808:     my %groups = ();
 8809:     foreach my $key (keys(%env)) {
 8810:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 8811:             my ($start,$end) = split(/\./,$env{$key});
 8812:             if (($end!=0) && ($end<$now)) { next; }
 8813:             if (($start!=0) && ($start>$now)) { next; }
 8814:             if ($1 eq $cdom && $2 eq $cnum) {
 8815:                 $groups{$3} = $env{$key} ;
 8816:             }
 8817:         }
 8818:     }
 8819:     return %groups;
 8820: }
 8821: 
 8822: sub get_group_membership {
 8823:     my ($cdom,$cnum,$group) = @_;
 8824:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8825: }
 8826: 
 8827: sub get_users_groups {
 8828:     my ($udom,$uname,$courseid) = @_;
 8829:     my @usersgroups;
 8830:     my $cachetime=1800;
 8831: 
 8832:     my $hashid="$udom:$uname:$courseid";
 8833:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8834:     if (defined($cached)) {
 8835:         @usersgroups = split(/:/,$grouplist);
 8836:     } else {  
 8837:         $grouplist = '';
 8838:         my $courseurl = &courseid_to_courseurl($courseid);
 8839:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8840:         my $access_end = $env{'course.'.$courseid.
 8841:                               '.default_enrollment_end_date'};
 8842:         my $now = time;
 8843:         foreach my $key (keys(%roleshash)) {
 8844:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8845:                 my $group = $1;
 8846:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8847:                     my $start = $2;
 8848:                     my $end = $1;
 8849:                     if ($start == -1) { next; } # deleted from group
 8850:                     if (($start!=0) && ($start>$now)) { next; }
 8851:                     if (($end!=0) && ($end<$now)) {
 8852:                         if ($access_end && $access_end < $now) {
 8853:                             if ($access_end - $end < 86400) {
 8854:                                 push(@usersgroups,$group);
 8855:                             }
 8856:                         }
 8857:                         next;
 8858:                     }
 8859:                     push(@usersgroups,$group);
 8860:                 }
 8861:             }
 8862:         }
 8863:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8864:         $grouplist = join(':',@usersgroups);
 8865:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8866:     }
 8867:     return @usersgroups;
 8868: }
 8869: 
 8870: sub devalidate_getgroups_cache {
 8871:     my ($udom,$uname,$cdom,$cnum)=@_;
 8872:     my $courseid = $cdom.'_'.$cnum;
 8873: 
 8874:     my $hashid="$udom:$uname:$courseid";
 8875:     &devalidate_cache_new('getgroups',$hashid);
 8876: }
 8877: 
 8878: # ------------------------------------------------------------------ Plain Text
 8879: 
 8880: sub plaintext {
 8881:     my ($short,$type,$cid,$forcedefault) = @_;
 8882:     if ($short =~ m{^cr/}) {
 8883: 	return (split('/',$short))[-1];
 8884:     }
 8885:     if (!defined($cid)) {
 8886:         $cid = $env{'request.course.id'};
 8887:     }
 8888:     my %rolenames = (
 8889:                       Course    => 'std',
 8890:                       Community => 'alt1',
 8891:                     );
 8892:     if ($cid ne '') {
 8893:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8894:             unless ($forcedefault) {
 8895:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8896:                 &Apache::lonlocal::mt_escape(\$roletext);
 8897:                 return &Apache::lonlocal::mt($roletext);
 8898:             }
 8899:         }
 8900:     }
 8901:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8902:         (defined($rolenames{$type})) && 
 8903:         (defined($prp{$short}{$rolenames{$type}}))) {
 8904:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8905:     } elsif ($cid ne '') {
 8906:         my $crstype = $env{'course.'.$cid.'.type'};
 8907:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8908:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8909:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8910:         }
 8911:     }
 8912:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8913: }
 8914: 
 8915: # ----------------------------------------------------------------- Assign Role
 8916: 
 8917: sub assignrole {
 8918:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8919:         $context)=@_;
 8920:     my $mrole;
 8921:     if ($role =~ /^cr\//) {
 8922:         my $cwosec=$url;
 8923:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8924: 	unless (&allowed('ccr',$cwosec)) {
 8925:            my $refused = 1;
 8926:            if ($context eq 'requestcourses') {
 8927:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8928:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8929:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8930:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8931:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8932:                            if ($crsenv{'internal.courseowner'} eq
 8933:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8934:                                $refused = '';
 8935:                            }
 8936:                        }
 8937:                    }
 8938:                }
 8939:            }
 8940:            if ($refused) {
 8941:                &logthis('Refused custom assignrole: '.
 8942:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8943:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8944:                return 'refused';
 8945:            }
 8946:         }
 8947:         $mrole='cr';
 8948:     } elsif ($role =~ /^gr\//) {
 8949:         my $cwogrp=$url;
 8950:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8951:         unless (&allowed('mdg',$cwogrp)) {
 8952:             &logthis('Refused group assignrole: '.
 8953:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8954:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8955:             return 'refused';
 8956:         }
 8957:         $mrole='gr';
 8958:     } else {
 8959:         my $cwosec=$url;
 8960:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8961:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8962:             my $refused;
 8963:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8964:                 if (!(&allowed('c'.$role,$url))) {
 8965:                     $refused = 1;
 8966:                 }
 8967:             } else {
 8968:                 $refused = 1;
 8969:             }
 8970:             if ($refused) {
 8971:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8972:                 if (!$selfenroll && $context eq 'course') {
 8973:                     my %crsenv;
 8974:                     if ($role eq 'cc' || $role eq 'co') {
 8975:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8976:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8977:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8978:                                 if ($crsenv{'internal.courseowner'} eq 
 8979:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8980:                                     $refused = '';
 8981:                                 }
 8982:                             }
 8983:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8984:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8985:                                 if ($crsenv{'internal.courseowner'} eq 
 8986:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8987:                                     $refused = '';
 8988:                                 }
 8989:                             }
 8990:                         }
 8991:                     }
 8992:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8993:                     $refused = '';
 8994:                 } elsif ($context eq 'requestcourses') {
 8995:                     my @possroles = ('st','ta','ep','in','cc','co');
 8996:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8997:                         my $wrongcc;
 8998:                         if ($cnum =~ /^$match_community$/) {
 8999:                             $wrongcc = 1 if ($role eq 'cc');
 9000:                         } else {
 9001:                             $wrongcc = 1 if ($role eq 'co');
 9002:                         }
 9003:                         unless ($wrongcc) {
 9004:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9005:                             if ($crsenv{'internal.courseowner'} eq 
 9006:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9007:                                 $refused = '';
 9008:                             }
 9009:                         }
 9010:                     }
 9011:                 } elsif ($context eq 'requestauthor') {
 9012:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 9013:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9014:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9015:                             $refused = '';
 9016:                         } else {
 9017:                             my %domdefaults = &get_domain_defaults($udom);
 9018:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9019:                                 my $checkbystatus;
 9020:                                 if ($env{'user.adv'}) {
 9021:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9022:                                     if ($disposition eq 'automatic') {
 9023:                                         $refused = '';
 9024:                                     } elsif ($disposition eq '') {
 9025:                                         $checkbystatus = 1;
 9026:                                     }
 9027:                                 } else {
 9028:                                     $checkbystatus = 1;
 9029:                                 }
 9030:                                 if ($checkbystatus) {
 9031:                                     if ($env{'environment.inststatus'}) {
 9032:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9033:                                         foreach my $type (@inststatuses) {
 9034:                                             if (($type ne '') &&
 9035:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9036:                                                 $refused = '';
 9037:                                             }
 9038:                                         }
 9039:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9040:                                         $refused = '';
 9041:                                     }
 9042:                                 }
 9043:                             }
 9044:                         }
 9045:                     }
 9046:                 }
 9047:                 if ($refused) {
 9048:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9049:                              ' '.$role.' '.$end.' '.$start.' by '.
 9050: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9051:                     return 'refused';
 9052:                 }
 9053:             }
 9054:         } elsif ($role eq 'au') {
 9055:             if ($url ne '/'.$udom.'/') {
 9056:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9057:                          ' to assign author role for '.$uname.':'.$udom.
 9058:                          ' in domain: '.$url.' refused (wrong domain).');
 9059:                 return 'refused';
 9060:             }
 9061:         }
 9062:         $mrole=$role;
 9063:     }
 9064:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9065:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9066:     if ($end) { $command.='_'.$end; }
 9067:     if ($start) {
 9068: 	if ($end) { 
 9069:            $command.='_'.$start; 
 9070:         } else {
 9071:            $command.='_0_'.$start;
 9072:         }
 9073:     }
 9074:     my $origstart = $start;
 9075:     my $origend = $end;
 9076:     my $delflag;
 9077: # actually delete
 9078:     if ($deleteflag) {
 9079: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9080: # modify command to delete the role
 9081:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9082:                 "$udom:$uname:$url".'_'."$mrole";
 9083: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9084: # set start and finish to negative values for userrolelog
 9085:            $start=-1;
 9086:            $end=-1;
 9087:            $delflag = 1;
 9088:         }
 9089:     }
 9090: # send command
 9091:     my $answer=&reply($command,&homeserver($uname,$udom));
 9092: # log new user role if status is ok
 9093:     if ($answer eq 'ok') {
 9094: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9095:         if (($role eq 'cc') || ($role eq 'in') ||
 9096:             ($role eq 'ep') || ($role eq 'ad') ||
 9097:             ($role eq 'ta') || ($role eq 'st') ||
 9098:             ($role=~/^cr/) || ($role eq 'gr') ||
 9099:             ($role eq 'co')) {
 9100: # for course roles, perform group memberships changes triggered by role change.
 9101:             unless ($role =~ /^gr/) {
 9102:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9103:                                                  $origstart,$selfenroll,$context);
 9104:             }
 9105:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9106:                            $selfenroll,$context);
 9107:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9108:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9109:                  ($role eq 'da')) {
 9110:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9111:                            $context);
 9112:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9113:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9114:                              $context);
 9115:         }
 9116:         if ($role eq 'cc') {
 9117:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9118:         }
 9119:     }
 9120:     return $answer;
 9121: }
 9122: 
 9123: sub autoupdate_coowners {
 9124:     my ($url,$end,$start,$uname,$udom) = @_;
 9125:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9126:     if (($cdom ne '') && ($cnum ne '')) {
 9127:         my $now = time;
 9128:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9129:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9130:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9131:             my $instcode = $coursehash{'internal.coursecode'};
 9132:             if ($instcode ne '') {
 9133:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9134:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9135:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9136:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9137:                         if ($result eq 'valid') {
 9138:                             if ($coursehash{'internal.co-owners'}) {
 9139:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9140:                                     push(@newcoowners,$coowner);
 9141:                                 }
 9142:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9143:                                     push(@newcoowners,$uname.':'.$udom);
 9144:                                 }
 9145:                                 @newcoowners = sort(@newcoowners);
 9146:                             } else {
 9147:                                 push(@newcoowners,$uname.':'.$udom);
 9148:                             }
 9149:                         } else {
 9150:                             if ($coursehash{'internal.co-owners'}) {
 9151:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9152:                                     unless ($coowner eq $uname.':'.$udom) {
 9153:                                         push(@newcoowners,$coowner);
 9154:                                     }
 9155:                                 }
 9156:                                 unless (@newcoowners > 0) {
 9157:                                     $delcoowners = 1;
 9158:                                     $coowners = '';
 9159:                                 }
 9160:                             }
 9161:                         }
 9162:                         if (@newcoowners || $delcoowners) {
 9163:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9164:                                             $delcoowners,@newcoowners);
 9165:                         }
 9166:                     }
 9167:                 }
 9168:             }
 9169:         }
 9170:     }
 9171: }
 9172: 
 9173: sub store_coowners {
 9174:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9175:     my $cid = $cdom.'_'.$cnum;
 9176:     my ($coowners,$delresult,$putresult);
 9177:     if (@newcoowners) {
 9178:         $coowners = join(',',@newcoowners);
 9179:         my %coownershash = (
 9180:                             'internal.co-owners' => $coowners,
 9181:                            );
 9182:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9183:         if ($putresult eq 'ok') {
 9184:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9185:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9186:             }
 9187:         }
 9188:     }
 9189:     if ($delcoowners) {
 9190:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9191:         if ($delresult eq 'ok') {
 9192:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9193:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9194:             }
 9195:         }
 9196:     }
 9197:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9198:         my %crsinfo =
 9199:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9200:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9201:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9202:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9203:         }
 9204:     }
 9205: }
 9206: 
 9207: # -------------------------------------------------- Modify user authentication
 9208: # Overrides without validation
 9209: 
 9210: sub modifyuserauth {
 9211:     my ($udom,$uname,$umode,$upass)=@_;
 9212:     my $uhome=&homeserver($uname,$udom);
 9213:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9214:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9215:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9216:              ' in domain '.$env{'request.role.domain'});  
 9217:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9218: 		     &escape($upass),$uhome);
 9219:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9220:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9221:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9222:     &log($udom,,$uname,$uhome,
 9223:         'Authentication changed by '.$env{'user.domain'}.', '.
 9224:                                      $env{'user.name'}.', '.$umode.
 9225:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9226:     unless ($reply eq 'ok') {
 9227:         &logthis('Authentication mode error: '.$reply);
 9228: 	return 'error: '.$reply;
 9229:     }   
 9230:     return 'ok';
 9231: }
 9232: 
 9233: # --------------------------------------------------------------- Modify a user
 9234: 
 9235: sub modifyuser {
 9236:     my ($udom,    $uname, $uid,
 9237:         $umode,   $upass, $first,
 9238:         $middle,  $last,  $gene,
 9239:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9240:     $udom= &LONCAPA::clean_domain($udom);
 9241:     $uname=&LONCAPA::clean_username($uname);
 9242:     my $showcandelete = 'none';
 9243:     if (ref($candelete) eq 'ARRAY') {
 9244:         if (@{$candelete} > 0) {
 9245:             $showcandelete = join(', ',@{$candelete});
 9246:         }
 9247:     }
 9248:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9249:              $umode.', '.$first.', '.$middle.', '.
 9250: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9251:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9252:                                      ' desiredhome not specified'). 
 9253:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9254:              ' in domain '.$env{'request.role.domain'});
 9255:     my $uhome=&homeserver($uname,$udom,'true');
 9256:     my $newuser;
 9257:     if ($uhome eq 'no_host') {
 9258:         $newuser = 1;
 9259:     }
 9260: # ----------------------------------------------------------------- Create User
 9261:     if (($uhome eq 'no_host') && 
 9262: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 9263:         my $unhome='';
 9264:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9265:             $unhome = $desiredhome;
 9266: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9267: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9268:         } else { # load balancing routine for determining $unhome
 9269:             my $loadm=10000000;
 9270: 	    my %servers = &get_servers($udom,'library');
 9271: 	    foreach my $tryserver (keys(%servers)) {
 9272: 		my $answer=reply('load',$tryserver);
 9273: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9274: 		    $loadm=$answer;
 9275: 		    $unhome=$tryserver;
 9276: 		}
 9277: 	    }
 9278:         }
 9279:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9280: 	    return 'error: unable to find a home server for '.$uname.
 9281:                    ' in domain '.$udom;
 9282:         }
 9283:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9284:                          &escape($upass),$unhome);
 9285: 	unless ($reply eq 'ok') {
 9286:             return 'error: '.$reply;
 9287:         }   
 9288:         $uhome=&homeserver($uname,$udom,'true');
 9289:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9290: 	    return 'error: unable verify users home machine.';
 9291:         }
 9292:     }   # End of creation of new user
 9293: # ---------------------------------------------------------------------- Add ID
 9294:     if ($uid) {
 9295:        $uid=~tr/A-Z/a-z/;
 9296:        my %uidhash=&idrget($udom,$uname);
 9297:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9298:          && (!$forceid)) {
 9299: 	  unless ($uid eq $uidhash{$uname}) {
 9300: 	      return 'error: user id "'.$uid.'" does not match '.
 9301:                   'current user id "'.$uidhash{$uname}.'".';
 9302:           }
 9303:        } else {
 9304: 	  &idput($udom,($uname => $uid));
 9305:        }
 9306:     }
 9307: # -------------------------------------------------------------- Add names, etc
 9308:     my @tmp=&get('environment',
 9309: 		   ['firstname','middlename','lastname','generation','id',
 9310:                     'permanentemail','inststatus'],
 9311: 		   $udom,$uname);
 9312:     my (%names,%oldnames);
 9313:     if ($tmp[0] =~ m/^error:.*/) { 
 9314:         %names=(); 
 9315:     } else {
 9316:         %names = @tmp;
 9317:         %oldnames = %names;
 9318:     }
 9319: #
 9320: # If name, email and/or uid are blank (e.g., because an uploaded file
 9321: # of users did not contain them), do not overwrite existing values
 9322: # unless field is in $candelete array ref.  
 9323: #
 9324: 
 9325:     my @fields = ('firstname','middlename','lastname','generation',
 9326:                   'permanentemail','id');
 9327:     my %newvalues;
 9328:     if (ref($candelete) eq 'ARRAY') {
 9329:         foreach my $field (@fields) {
 9330:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9331:                 if ($field eq 'firstname') {
 9332:                     $names{$field} = $first;
 9333:                 } elsif ($field eq 'middlename') {
 9334:                     $names{$field} = $middle;
 9335:                 } elsif ($field eq 'lastname') {
 9336:                     $names{$field} = $last;
 9337:                 } elsif ($field eq 'generation') { 
 9338:                     $names{$field} = $gene;
 9339:                 } elsif ($field eq 'permanentemail') {
 9340:                     $names{$field} = $email;
 9341:                 } elsif ($field eq 'id') {
 9342:                     $names{$field}  = $uid;
 9343:                 }
 9344:             }
 9345:         }
 9346:     }
 9347:     if ($first)  { $names{'firstname'}  = $first; }
 9348:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9349:     if ($last)   { $names{'lastname'}   = $last; }
 9350:     if (defined($gene))   { $names{'generation'} = $gene; }
 9351:     if ($email) {
 9352:        $email=~s/[^\w\@\.\-\,]//gs;
 9353:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9354:     }
 9355:     if ($uid) { $names{'id'}  = $uid; }
 9356:     if (defined($inststatus)) {
 9357:         $names{'inststatus'} = '';
 9358:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9359:         if (ref($usertypes) eq 'HASH') {
 9360:             my @okstatuses; 
 9361:             foreach my $item (split(/:/,$inststatus)) {
 9362:                 if (defined($usertypes->{$item})) {
 9363:                     push(@okstatuses,$item);  
 9364:                 }
 9365:             }
 9366:             if (@okstatuses) {
 9367:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9368:             }
 9369:         }
 9370:     }
 9371:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9372:                  $umode.', '.$first.', '.$middle.', '.
 9373:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9374:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9375:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9376:     } else {
 9377:         $logmsg .= ' during self creation';
 9378:     }
 9379:     my $changed;
 9380:     if ($newuser) {
 9381:         $changed = 1;
 9382:     } else {
 9383:         foreach my $field (@fields) {
 9384:             if ($names{$field} ne $oldnames{$field}) {
 9385:                 $changed = 1;
 9386:                 last;
 9387:             }
 9388:         }
 9389:     }
 9390:     unless ($changed) {
 9391:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9392:         &logthis($logmsg);
 9393:         return 'ok';
 9394:     }
 9395:     my $reply = &put('environment', \%names, $udom,$uname);
 9396:     if ($reply ne 'ok') { 
 9397:         return 'error: '.$reply;
 9398:     }
 9399:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9400:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9401:     }
 9402:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9403:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9404:     $logmsg = 'Success modifying user '.$logmsg;
 9405:     &logthis($logmsg);
 9406:     return 'ok';
 9407: }
 9408: 
 9409: # -------------------------------------------------------------- Modify student
 9410: 
 9411: sub modifystudent {
 9412:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9413:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9414:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9415:     if (!$cid) {
 9416: 	unless ($cid=$env{'request.course.id'}) {
 9417: 	    return 'not_in_class';
 9418: 	}
 9419:     }
 9420: # --------------------------------------------------------------- Make the user
 9421:     my $reply=&modifyuser
 9422: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9423:          $desiredhome,$email,$inststatus);
 9424:     unless ($reply eq 'ok') { return $reply; }
 9425:     # This will cause &modify_student_enrollment to get the uid from the
 9426:     # student's environment
 9427:     $uid = undef if (!$forceid);
 9428:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9429: 					$gene,$usec,$end,$start,$type,$locktype,
 9430:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9431:     return $reply;
 9432: }
 9433: 
 9434: sub modify_student_enrollment {
 9435:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9436:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9437:     my ($cdom,$cnum,$chome);
 9438:     if (!$cid) {
 9439: 	unless ($cid=$env{'request.course.id'}) {
 9440: 	    return 'not_in_class';
 9441: 	}
 9442: 	$cdom=$env{'course.'.$cid.'.domain'};
 9443: 	$cnum=$env{'course.'.$cid.'.num'};
 9444:     } else {
 9445: 	($cdom,$cnum)=split(/_/,$cid);
 9446:     }
 9447:     $chome=$env{'course.'.$cid.'.home'};
 9448:     if (!$chome) {
 9449: 	$chome=&homeserver($cnum,$cdom);
 9450:     }
 9451:     if (!$chome) { return 'unknown_course'; }
 9452:     # Make sure the user exists
 9453:     my $uhome=&homeserver($uname,$udom);
 9454:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9455: 	return 'error: no such user';
 9456:     }
 9457:     # Get student data if we were not given enough information
 9458:     if (!defined($first)  || $first  eq '' || 
 9459:         !defined($last)   || $last   eq '' || 
 9460:         !defined($uid)    || $uid    eq '' || 
 9461:         !defined($middle) || $middle eq '' || 
 9462:         !defined($gene)   || $gene   eq '') {
 9463:         # They did not supply us with enough data to enroll the student, so
 9464:         # we need to pick up more information.
 9465:         my %tmp = &get('environment',
 9466:                        ['firstname','middlename','lastname', 'generation','id']
 9467:                        ,$udom,$uname);
 9468: 
 9469:         #foreach my $key (keys(%tmp)) {
 9470:         #    &logthis("key $key = ".$tmp{$key});
 9471:         #}
 9472:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9473:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9474:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9475:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9476:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9477:     }
 9478:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9479:     my $user = "$uname:$udom";
 9480:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9481:     my $reply=cput('classlist',
 9482: 		   {$user => 
 9483: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9484: 		   $cdom,$cnum);
 9485:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9486:         &devalidate_getsection_cache($udom,$uname,$cid);
 9487:     } else { 
 9488: 	return 'error: '.$reply;
 9489:     }
 9490:     # Add student role to user
 9491:     my $uurl='/'.$cid;
 9492:     $uurl=~s/\_/\//g;
 9493:     if ($usec) {
 9494: 	$uurl.='/'.$usec;
 9495:     }
 9496:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9497:                              $selfenroll,$context);
 9498:     if ($result ne 'ok') {
 9499:         if ($old_entry{$user} ne '') {
 9500:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9501:         } else {
 9502:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9503:         }
 9504:     }
 9505:     return $result; 
 9506: }
 9507: 
 9508: sub format_name {
 9509:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9510:     my $name;
 9511:     if ($first ne 'lastname') {
 9512: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9513:     } else {
 9514: 	if ($lastname=~/\S/) {
 9515: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9516: 	    $name=~s/\s+,/,/;
 9517: 	} else {
 9518: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9519: 	}
 9520:     }
 9521:     $name=~s/^\s+//;
 9522:     $name=~s/\s+$//;
 9523:     $name=~s/\s+/ /g;
 9524:     return $name;
 9525: }
 9526: 
 9527: # ------------------------------------------------- Write to course preferences
 9528: 
 9529: sub writecoursepref {
 9530:     my ($courseid,%prefs)=@_;
 9531:     $courseid=~s/^\///;
 9532:     $courseid=~s/\_/\//g;
 9533:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9534:     my $chome=homeserver($cnum,$cdomain);
 9535:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9536: 	return 'error: no such course';
 9537:     }
 9538:     my $cstring='';
 9539:     foreach my $pref (keys(%prefs)) {
 9540: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9541:     }
 9542:     $cstring=~s/\&$//;
 9543:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9544: }
 9545: 
 9546: # ---------------------------------------------------------- Make/modify course
 9547: 
 9548: sub createcourse {
 9549:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9550:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9551:     $url=&declutter($url);
 9552:     my $cid='';
 9553:     if ($context eq 'requestcourses') {
 9554:         my $can_create = 0;
 9555:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9556:         if ($udom eq $ownerdom) {
 9557:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9558:                                   $context)) {
 9559:                 $can_create = 1;
 9560:             }
 9561:         } else {
 9562:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9563:                                            $category);
 9564:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9565:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9566:                 if (@curr > 0) {
 9567:                     my @options = qw(approval validate autolimit);
 9568:                     my $optregex = join('|',@options);
 9569:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9570:                         $can_create = 1;
 9571:                     }
 9572:                 }
 9573:             }
 9574:         }
 9575:         if ($can_create) {
 9576:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 9577:                 unless (&allowed('ccc',$udom)) {
 9578:                     return 'refused'; 
 9579:                 }
 9580:             }
 9581:         } else {
 9582:             return 'refused';
 9583:         }
 9584:     } elsif (!&allowed('ccc',$udom)) {
 9585:         return 'refused';
 9586:     }
 9587: # --------------------------------------------------------------- Get Unique ID
 9588:     my $uname;
 9589:     if ($cnum =~ /^$match_courseid$/) {
 9590:         my $chome=&homeserver($cnum,$udom,'true');
 9591:         if (($chome eq '') || ($chome eq 'no_host')) {
 9592:             $uname = $cnum;
 9593:         } else {
 9594:             $uname = &generate_coursenum($udom,$crstype);
 9595:         }
 9596:     } else {
 9597:         $uname = &generate_coursenum($udom,$crstype);
 9598:     }
 9599:     return $uname if ($uname =~ /^error/);
 9600: # -------------------------------------------------- Check supplied server name
 9601:     if (!defined($course_server)) {
 9602:         if (defined(&domain($udom,'primary'))) {
 9603:             $course_server = &domain($udom,'primary');
 9604:         } else {
 9605:             $course_server = $env{'user.home'}; 
 9606:         }
 9607:     }
 9608:     my %host_servers =
 9609:         &Apache::lonnet::get_servers($udom,'library');
 9610:     unless ($host_servers{$course_server}) {
 9611:         return 'error: invalid home server for course: '.$course_server;
 9612:     }
 9613: # ------------------------------------------------------------- Make the course
 9614:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 9615:                       $course_server);
 9616:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 9617:     my $uhome=&homeserver($uname,$udom,'true');
 9618:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9619: 	return 'error: no such course';
 9620:     }
 9621: # ----------------------------------------------------------------- Course made
 9622: # log existence
 9623:     my $now = time;
 9624:     my $newcourse = {
 9625:                     $udom.'_'.$uname => {
 9626:                                      description => $description,
 9627:                                      inst_code   => $inst_code,
 9628:                                      owner       => $course_owner,
 9629:                                      type        => $crstype,
 9630:                                      creator     => $env{'user.name'}.':'.
 9631:                                                     $env{'user.domain'},
 9632:                                      created     => $now,
 9633:                                      context     => $context,
 9634:                                                 },
 9635:                     };
 9636:     &courseidput($udom,$newcourse,$uhome,'notime');
 9637: # set toplevel url
 9638:     my $topurl=$url;
 9639:     unless ($nonstandard) {
 9640: # ------------------------------------------ For standard courses, make top url
 9641:         my $mapurl=&clutter($url);
 9642:         if ($mapurl eq '/res/') { $mapurl=''; }
 9643:         $env{'form.initmap'}=(<<ENDINITMAP);
 9644: <map>
 9645: <resource id="1" type="start"></resource>
 9646: <resource id="2" src="$mapurl"></resource>
 9647: <resource id="3" type="finish"></resource>
 9648: <link index="1" from="1" to="2"></link>
 9649: <link index="2" from="2" to="3"></link>
 9650: </map>
 9651: ENDINITMAP
 9652:         $topurl=&declutter(
 9653:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 9654:                           );
 9655:     }
 9656: # ----------------------------------------------------------- Write preferences
 9657:     &writecoursepref($udom.'_'.$uname,
 9658:                      ('description'              => $description,
 9659:                       'url'                      => $topurl,
 9660:                       'internal.creator'         => $env{'user.name'}.':'.
 9661:                                                     $env{'user.domain'},
 9662:                       'internal.created'         => $now,
 9663:                       'internal.creationcontext' => $context)
 9664:                     );
 9665:     return '/'.$udom.'/'.$uname;
 9666: }
 9667: 
 9668: # ------------------------------------------------------------------- Create ID
 9669: sub generate_coursenum {
 9670:     my ($udom,$crstype) = @_;
 9671:     my $domdesc = &domain($udom);
 9672:     return 'error: invalid domain' if ($domdesc eq '');
 9673:     my $first;
 9674:     if ($crstype eq 'Community') {
 9675:         $first = '0';
 9676:     } else {
 9677:         $first = int(1+rand(9)); 
 9678:     } 
 9679:     my $uname=$first.
 9680:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9681:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9682:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9683: # ----------------------------------------------- Make sure that does not exist
 9684:     my $uhome=&homeserver($uname,$udom,'true');
 9685:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9686:         if ($crstype eq 'Community') {
 9687:             $first = '0';
 9688:         } else {
 9689:             $first = int(1+rand(9));
 9690:         }
 9691:         $uname=$first.
 9692:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9693:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9694:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9695:         $uhome=&homeserver($uname,$udom,'true');
 9696:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9697:             return 'error: unable to generate unique course-ID';
 9698:         }
 9699:     }
 9700:     return $uname;
 9701: }
 9702: 
 9703: sub is_course {
 9704:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 9705:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 9706: 
 9707:     return unless $cdom and $cnum;
 9708: 
 9709:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 9710:         '.');
 9711: 
 9712:     return unless(exists($courses{$cdom.'_'.$cnum}));
 9713:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 9714: }
 9715: 
 9716: sub store_userdata {
 9717:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 9718:     my $result;
 9719:     if ($datakey ne '') {
 9720:         if (ref($storehash) eq 'HASH') {
 9721:             if ($udom eq '' || $uname eq '') {
 9722:                 $udom = $env{'user.domain'};
 9723:                 $uname = $env{'user.name'};
 9724:             }
 9725:             my $uhome=&homeserver($uname,$udom);
 9726:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 9727:                 $result = 'error: no_host';
 9728:             } else {
 9729:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 9730:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 9731: 
 9732:                 my $namevalue='';
 9733:                 foreach my $key (keys(%{$storehash})) {
 9734:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 9735:                 }
 9736:                 $namevalue=~s/\&$//;
 9737:                 unless ($namespace eq 'courserequests') {
 9738:                     $datakey = &escape($datakey);
 9739:                 }
 9740:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 9741:                                   $namevalue,$uhome);
 9742:             }
 9743:         } else {
 9744:             $result = 'error: data to store was not a hash reference'; 
 9745:         }
 9746:     } else {
 9747:         $result= 'error: invalid requestkey'; 
 9748:     }
 9749:     return $result;
 9750: }
 9751: 
 9752: # ---------------------------------------------------------- Assign Custom Role
 9753: 
 9754: sub assigncustomrole {
 9755:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 9756:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 9757:                        $end,$start,$deleteflag,$selfenroll,$context);
 9758: }
 9759: 
 9760: # ----------------------------------------------------------------- Revoke Role
 9761: 
 9762: sub revokerole {
 9763:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 9764:     my $now=time;
 9765:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 9766: }
 9767: 
 9768: # ---------------------------------------------------------- Revoke Custom Role
 9769: 
 9770: sub revokecustomrole {
 9771:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 9772:     my $now=time;
 9773:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 9774:            $deleteflag,$selfenroll,$context);
 9775: }
 9776: 
 9777: # ------------------------------------------------------------ Disk usage
 9778: sub diskusage {
 9779:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 9780:     $directorypath =~ s/\/$//;
 9781:     my $listing=&reply('du2:'.&escape($directorypath).':'
 9782:                        .&escape($getpropath).':'.&escape($uname).':'
 9783:                        .&escape($udom),homeserver($uname,$udom));
 9784:     if ($listing eq 'unknown_cmd') {
 9785:         if ($getpropath) {
 9786:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 9787:         }
 9788:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 9789:     }
 9790:     return $listing;
 9791: }
 9792: 
 9793: sub is_locked {
 9794:     my ($file_name, $domain, $user, $which) = @_;
 9795:     my @check;
 9796:     my $is_locked;
 9797:     push (@check,$file_name);
 9798:     my %locked = &get('file_permissions',\@check,
 9799: 		      $env{'user.domain'},$env{'user.name'});
 9800:     my ($tmp)=keys(%locked);
 9801:     if ($tmp=~/^error:/) { undef(%locked); }
 9802:     
 9803:     if (ref($locked{$file_name}) eq 'ARRAY') {
 9804:         $is_locked = 'false';
 9805:         foreach my $entry (@{$locked{$file_name}}) {
 9806:            if (ref($entry) eq 'ARRAY') {
 9807:                $is_locked = 'true';
 9808:                if (ref($which) eq 'ARRAY') {
 9809:                    push(@{$which},$entry);
 9810:                } else {
 9811:                    last;
 9812:                }
 9813:            }
 9814:        }
 9815:     } else {
 9816:         $is_locked = 'false';
 9817:     }
 9818:     return $is_locked;
 9819: }
 9820: 
 9821: sub declutter_portfile {
 9822:     my ($file) = @_;
 9823:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9824:     return $file;
 9825: }
 9826: 
 9827: # ------------------------------------------------------------- Mark as Read Only
 9828: 
 9829: sub mark_as_readonly {
 9830:     my ($domain,$user,$files,$what) = @_;
 9831:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9832:     my ($tmp)=keys(%current_permissions);
 9833:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9834:     foreach my $file (@{$files}) {
 9835: 	$file = &declutter_portfile($file);
 9836:         push(@{$current_permissions{$file}},$what);
 9837:     }
 9838:     &put('file_permissions',\%current_permissions,$domain,$user);
 9839:     return;
 9840: }
 9841: 
 9842: # ------------------------------------------------------------Save Selected Files
 9843: 
 9844: sub save_selected_files {
 9845:     my ($user, $path, @files) = @_;
 9846:     my $filename = $user."savedfiles";
 9847:     my @other_files = &files_not_in_path($user, $path);
 9848:     open (OUT,'>',LONCAPA::tempdir().$filename);
 9849:     foreach my $file (@files) {
 9850:         print (OUT $env{'form.currentpath'}.$file."\n");
 9851:     }
 9852:     foreach my $file (@other_files) {
 9853:         print (OUT $file."\n");
 9854:     }
 9855:     close (OUT);
 9856:     return 'ok';
 9857: }
 9858: 
 9859: sub clear_selected_files {
 9860:     my ($user) = @_;
 9861:     my $filename = $user."savedfiles";
 9862:     open (OUT,'>',LONCAPA::tempdir().$filename);
 9863:     print (OUT undef);
 9864:     close (OUT);
 9865:     return ("ok");    
 9866: }
 9867: 
 9868: sub files_in_path {
 9869:     my ($user, $path) = @_;
 9870:     my $filename = $user."savedfiles";
 9871:     my %return_files;
 9872:     open (IN,'<',LONCAPA::tempdir().$filename);
 9873:     while (my $line_in = <IN>) {
 9874:         chomp ($line_in);
 9875:         my @paths_and_file = split (m!/!, $line_in);
 9876:         my $file_part = pop (@paths_and_file);
 9877:         my $path_part = join ('/', @paths_and_file);
 9878:         $path_part.='/';
 9879:         my $path_and_file = $path_part.$file_part;
 9880:         if ($path_part eq $path) {
 9881:             $return_files{$file_part}= 'selected';
 9882:         }
 9883:     }
 9884:     close (IN);
 9885:     return (\%return_files);
 9886: }
 9887: 
 9888: # called in portfolio select mode, to show files selected NOT in current directory
 9889: sub files_not_in_path {
 9890:     my ($user, $path) = @_;
 9891:     my $filename = $user."savedfiles";
 9892:     my @return_files;
 9893:     my $path_part;
 9894:     open(IN,'<',LONCAPA::tempdir().$filename);
 9895:     while (my $line = <IN>) {
 9896:         #ok, I know it's clunky, but I want it to work
 9897:         my @paths_and_file = split(m|/|, $line);
 9898:         my $file_part = pop(@paths_and_file);
 9899:         chomp($file_part);
 9900:         my $path_part = join('/', @paths_and_file);
 9901:         $path_part .= '/';
 9902:         my $path_and_file = $path_part.$file_part;
 9903:         if ($path_part ne $path) {
 9904:             push(@return_files, ($path_and_file));
 9905:         }
 9906:     }
 9907:     close(OUT);
 9908:     return (@return_files);
 9909: }
 9910: 
 9911: #----------------------------------------------Get portfolio file permissions
 9912: 
 9913: sub get_portfile_permissions {
 9914:     my ($domain,$user) = @_;
 9915:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9916:     my ($tmp)=keys(%current_permissions);
 9917:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9918:     return \%current_permissions;
 9919: }
 9920: 
 9921: #---------------------------------------------Get portfolio file access controls
 9922: 
 9923: sub get_access_controls {
 9924:     my ($current_permissions,$group,$file) = @_;
 9925:     my %access;
 9926:     my $real_file = $file;
 9927:     $file =~ s/\.meta$//;
 9928:     if (defined($file)) {
 9929:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9930:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9931:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9932:             }
 9933:         }
 9934:     } else {
 9935:         foreach my $key (keys(%{$current_permissions})) {
 9936:             if ($key =~ /\0accesscontrol$/) {
 9937:                 if (defined($group)) {
 9938:                     if ($key !~ m-^\Q$group\E/-) {
 9939:                         next;
 9940:                     }
 9941:                 }
 9942:                 my ($fullpath) = split(/\0/,$key);
 9943:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9944:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9945:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9946:                     }
 9947:                 }
 9948:             }
 9949:         }
 9950:     }
 9951:     return %access;
 9952: }
 9953: 
 9954: sub modify_access_controls {
 9955:     my ($file_name,$changes,$domain,$user)=@_;
 9956:     my ($outcome,$deloutcome);
 9957:     my %store_permissions;
 9958:     my %new_values;
 9959:     my %new_control;
 9960:     my %translation;
 9961:     my @deletions = ();
 9962:     my $now = time;
 9963:     if (exists($$changes{'activate'})) {
 9964:         if (ref($$changes{'activate'}) eq 'HASH') {
 9965:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9966:             my $numnew = scalar(@newitems);
 9967:             for (my $i=0; $i<$numnew; $i++) {
 9968:                 my $newkey = $newitems[$i];
 9969:                 my $newid = &Apache::loncommon::get_cgi_id();
 9970:                 if ($newkey =~ /^\d+:/) { 
 9971:                     $newkey =~ s/^(\d+)/$newid/;
 9972:                     $translation{$1} = $newid;
 9973:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9974:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9975:                     $translation{$1} = $newid;
 9976:                 }
 9977:                 $new_values{$file_name."\0".$newkey} = 
 9978:                                           $$changes{'activate'}{$newitems[$i]};
 9979:                 $new_control{$newkey} = $now;
 9980:             }
 9981:         }
 9982:     }
 9983:     my %todelete;
 9984:     my %changed_items;
 9985:     foreach my $action ('delete','update') {
 9986:         if (exists($$changes{$action})) {
 9987:             if (ref($$changes{$action}) eq 'HASH') {
 9988:                 foreach my $key (keys(%{$$changes{$action}})) {
 9989:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9990:                     if ($action eq 'delete') { 
 9991:                         $todelete{$itemnum} = 1;
 9992:                     } else {
 9993:                         $changed_items{$itemnum} = $key;
 9994:                     }
 9995:                 }
 9996:             }
 9997:         }
 9998:     }
 9999:     # get lock on access controls for file.
10000:     my $lockhash = {
10001:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10002:                                                        ':'.$env{'user.domain'},
10003:                    }; 
10004:     my $tries = 0;
10005:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10006:    
10007:     while (($gotlock ne 'ok') && $tries < 10) {
10008:         $tries ++;
10009:         sleep(0.1);
10010:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10011:     }
10012:     if ($gotlock eq 'ok') {
10013:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10014:         my ($tmp)=keys(%curr_permissions);
10015:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10016:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10017:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10018:             if (ref($curr_controls) eq 'HASH') {
10019:                 foreach my $control_item (keys(%{$curr_controls})) {
10020:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10021:                     if (defined($todelete{$itemnum})) {
10022:                         push(@deletions,$file_name."\0".$control_item);
10023:                     } else {
10024:                         if (defined($changed_items{$itemnum})) {
10025:                             $new_control{$changed_items{$itemnum}} = $now;
10026:                             push(@deletions,$file_name."\0".$control_item);
10027:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10028:                         } else {
10029:                             $new_control{$control_item} = $$curr_controls{$control_item};
10030:                         }
10031:                     }
10032:                 }
10033:             }
10034:         }
10035:         my ($group);
10036:         if (&is_course($domain,$user)) {
10037:             ($group,my $file) = split(/\//,$file_name,2);
10038:         }
10039:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10040:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10041:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10042:         #  remove lock
10043:         my @del_lock = ($file_name."\0".'locked_access_records');
10044:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10045:         my $sqlresult =
10046:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10047:                                     $group);
10048:     } else {
10049:         $outcome = "error: could not obtain lockfile\n";  
10050:     }
10051:     return ($outcome,$deloutcome,\%new_values,\%translation);
10052: }
10053: 
10054: sub make_public_indefinitely {
10055:     my ($requrl) = @_;
10056:     my $now = time;
10057:     my $action = 'activate';
10058:     my $aclnum = 0;
10059:     if (&is_portfolio_url($requrl)) {
10060:         my (undef,$udom,$unum,$file_name,$group) =
10061:             &parse_portfolio_url($requrl);
10062:         my $current_perms = &get_portfile_permissions($udom,$unum);
10063:         my %access_controls = &get_access_controls($current_perms,
10064:                                                    $group,$file_name);
10065:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10066:             my ($num,$scope,$end,$start) = 
10067:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10068:             if ($scope eq 'public') {
10069:                 if ($start <= $now && $end == 0) {
10070:                     $action = 'none';
10071:                 } else {
10072:                     $action = 'update';
10073:                     $aclnum = $num;
10074:                 }
10075:                 last;
10076:             }
10077:         }
10078:         if ($action eq 'none') {
10079:              return 'ok';
10080:         } else {
10081:             my %changes;
10082:             my $newend = 0;
10083:             my $newstart = $now;
10084:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10085:             $changes{$action}{$newkey} = {
10086:                 type => 'public',
10087:                 time => {
10088:                     start => $newstart,
10089:                     end   => $newend,
10090:                 },
10091:             };
10092:             my ($outcome,$deloutcome,$new_values,$translation) =
10093:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10094:             return $outcome;
10095:         }
10096:     } else {
10097:         return 'invalid';
10098:     }
10099: }
10100: 
10101: #------------------------------------------------------Get Marked as Read Only
10102: 
10103: sub get_marked_as_readonly {
10104:     my ($domain,$user,$what,$group) = @_;
10105:     my $current_permissions = &get_portfile_permissions($domain,$user);
10106:     my @readonly_files;
10107:     my $cmp1=$what;
10108:     if (ref($what)) { $cmp1=join('',@{$what}) };
10109:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10110:         if (defined($group)) {
10111:             if ($file_name !~ m-^\Q$group\E/-) {
10112:                 next;
10113:             }
10114:         }
10115:         if (ref($value) eq "ARRAY"){
10116:             foreach my $stored_what (@{$value}) {
10117:                 my $cmp2=$stored_what;
10118:                 if (ref($stored_what) eq 'ARRAY') {
10119:                     $cmp2=join('',@{$stored_what});
10120:                 }
10121:                 if ($cmp1 eq $cmp2) {
10122:                     push(@readonly_files, $file_name);
10123:                     last;
10124:                 } elsif (!defined($what)) {
10125:                     push(@readonly_files, $file_name);
10126:                     last;
10127:                 }
10128:             }
10129:         }
10130:     }
10131:     return @readonly_files;
10132: }
10133: #-----------------------------------------------------------Get Marked as Read Only Hash
10134: 
10135: sub get_marked_as_readonly_hash {
10136:     my ($current_permissions,$group,$what) = @_;
10137:     my %readonly_files;
10138:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10139:         if (defined($group)) {
10140:             if ($file_name !~ m-^\Q$group\E/-) {
10141:                 next;
10142:             }
10143:         }
10144:         if (ref($value) eq "ARRAY"){
10145:             foreach my $stored_what (@{$value}) {
10146:                 if (ref($stored_what) eq 'ARRAY') {
10147:                     foreach my $lock_descriptor(@{$stored_what}) {
10148:                         if ($lock_descriptor eq 'graded') {
10149:                             $readonly_files{$file_name} = 'graded';
10150:                         } elsif ($lock_descriptor eq 'handback') {
10151:                             $readonly_files{$file_name} = 'handback';
10152:                         } else {
10153:                             if (!exists($readonly_files{$file_name})) {
10154:                                 $readonly_files{$file_name} = 'locked';
10155:                             }
10156:                         }
10157:                     }
10158:                 } 
10159:             }
10160:         } 
10161:     }
10162:     return %readonly_files;
10163: }
10164: # ------------------------------------------------------------ Unmark as Read Only
10165: 
10166: sub unmark_as_readonly {
10167:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10168:     # for portfolio submissions, $what contains [$symb,$crsid] 
10169:     my ($domain,$user,$what,$file_name,$group) = @_;
10170:     $file_name = &declutter_portfile($file_name);
10171:     my $symb_crs = $what;
10172:     if (ref($what)) { $symb_crs=join('',@$what); }
10173:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10174:     my ($tmp)=keys(%current_permissions);
10175:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10176:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10177:     foreach my $file (@readonly_files) {
10178: 	my $clean_file = &declutter_portfile($file);
10179: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10180: 	my $current_locks = $current_permissions{$file};
10181:         my @new_locks;
10182:         my @del_keys;
10183:         if (ref($current_locks) eq "ARRAY"){
10184:             foreach my $locker (@{$current_locks}) {
10185:                 my $compare=$locker;
10186:                 if (ref($locker) eq 'ARRAY') {
10187:                     $compare=join('',@{$locker});
10188:                     if ($compare ne $symb_crs) {
10189:                         push(@new_locks, $locker);
10190:                     }
10191:                 }
10192:             }
10193:             if (scalar(@new_locks) > 0) {
10194:                 $current_permissions{$file} = \@new_locks;
10195:             } else {
10196:                 push(@del_keys, $file);
10197:                 &del('file_permissions',\@del_keys, $domain, $user);
10198:                 delete($current_permissions{$file});
10199:             }
10200:         }
10201:     }
10202:     &put('file_permissions',\%current_permissions,$domain,$user);
10203:     return;
10204: }
10205: 
10206: # ------------------------------------------------------------ Directory lister
10207: 
10208: sub dirlist {
10209:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10210:     $uri=~s/^\///;
10211:     $uri=~s/\/$//;
10212:     my ($udom, $uname);
10213:     if ($getuserdir) {
10214:         $udom = $userdomain;
10215:         $uname = $username;
10216:     } else {
10217:         (undef,$udom,$uname)=split(/\//,$uri);
10218:         if(defined($userdomain)) {
10219:             $udom = $userdomain;
10220:         }
10221:         if(defined($username)) {
10222:             $uname = $username;
10223:         }
10224:     }
10225:     my ($dirRoot,$listing,@listing_results);
10226: 
10227:     $dirRoot = $perlvar{'lonDocRoot'};
10228:     if (defined($getpropath)) {
10229:         $dirRoot = &propath($udom,$uname);
10230:         $dirRoot =~ s/\/$//;
10231:     } elsif (defined($getuserdir)) {
10232:         my $subdir=$uname.'__';
10233:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10234:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10235:                    ."/$udom/$subdir/$uname";
10236:     } elsif (defined($alternateRoot)) {
10237:         $dirRoot = $alternateRoot;
10238:     }
10239: 
10240:     if($udom) {
10241:         if($uname) {
10242:             my $uhome = &homeserver($uname,$udom);
10243:             if ($uhome eq 'no_host') {
10244:                 return ([],'no_host');
10245:             }
10246:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10247:                               .$getuserdir.':'.&escape($dirRoot)
10248:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10249:             if ($listing eq 'unknown_cmd') {
10250:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10251:             } else {
10252:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10253:             }
10254:             if ($listing eq 'unknown_cmd') {
10255:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10256:                 @listing_results = split(/:/,$listing);
10257:             } else {
10258:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10259:             }
10260:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10261:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10262:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10263:                 return ([],$listing);
10264:             } else {
10265:                 return (\@listing_results);
10266:             }
10267:         } elsif(!$alternateRoot) {
10268:             my (%allusers,%listerror);
10269: 	    my %servers = &get_servers($udom,'library');
10270:  	    foreach my $tryserver (keys(%servers)) {
10271:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10272:                                   &escape($udom),$tryserver);
10273:                 if ($listing eq 'unknown_cmd') {
10274: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10275: 				      $udom, $tryserver);
10276:                 } else {
10277:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10278:                 }
10279: 		if ($listing eq 'unknown_cmd') {
10280: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10281: 				      $udom, $tryserver);
10282: 		    @listing_results = split(/:/,$listing);
10283: 		} else {
10284: 		    @listing_results =
10285: 			map { &unescape($_); } split(/:/,$listing);
10286: 		}
10287:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10288:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10289:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10290:                     $listerror{$tryserver} = $listing;
10291:                 } else {
10292: 		    foreach my $line (@listing_results) {
10293: 			my ($entry) = split(/&/,$line,2);
10294: 			$allusers{$entry} = 1;
10295: 		    }
10296: 		}
10297:             }
10298:             my @alluserslist=();
10299:             foreach my $user (sort(keys(%allusers))) {
10300:                 push(@alluserslist,$user.'&user');
10301:             }
10302:             if (!%listerror) {
10303:                 # no errors
10304:                 return (\@alluserslist);
10305:             } elsif (scalar(keys(%servers)) == 1) {
10306:                 # one library server, one error
10307:                 my ($key) = keys(%listerror);
10308:                 return (\@alluserslist, $listerror{$key});
10309:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10310:                 # con_lost indicates that we might miss data from at least one
10311:                 # library server
10312:                 return (\@alluserslist, 'con_lost');
10313:             } else {
10314:                 # multiple library servers and no con_lost -> data should be
10315:                 # complete.
10316:                 return (\@alluserslist);
10317:             }
10318: 
10319:         } else {
10320:             return ([],'missing username');
10321:         }
10322:     } elsif(!defined($getpropath)) {
10323:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10324:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10325:         return (\@all_domains);
10326:     } else {
10327:         return ([],'missing domain');
10328:     }
10329: }
10330: 
10331: # --------------------------------------------- GetFileTimestamp
10332: # This function utilizes dirlist and returns the date stamp for
10333: # when it was last modified.  It will also return an error of -1
10334: # if an error occurs
10335: 
10336: sub GetFileTimestamp {
10337:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10338:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10339:     $studentName   = &LONCAPA::clean_username($studentName);
10340:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10341:                                     undef,$getuserdir);
10342:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10343:         return -1;
10344:     }
10345:     if (ref($fileref) eq 'ARRAY') {
10346:         my @stats = split('&',$fileref->[0]);
10347:         # @stats contains first the filename, then the stat output
10348:         return $stats[10]; # so this is 10 instead of 9.
10349:     } else {
10350:         return -1;
10351:     }
10352: }
10353: 
10354: sub stat_file {
10355:     my ($uri) = @_;
10356:     $uri = &clutter_with_no_wrapper($uri);
10357: 
10358:     my ($udom,$uname,$file);
10359:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10360: 	($udom,$uname,$file) =
10361: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10362: 	$file = 'userfiles/'.$file;
10363:     }
10364:     if ($uri =~ m-^/res/-) {
10365: 	($udom,$uname) = 
10366: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10367: 	$file = $uri;
10368:     }
10369: 
10370:     if (!$udom || !$uname || !$file) {
10371: 	# unable to handle the uri
10372: 	return ();
10373:     }
10374:     my $getpropath;
10375:     if ($file =~ /^userfiles\//) {
10376:         $getpropath = 1;
10377:     }
10378:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10379:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10380:         return ();
10381:     } else {
10382:         if (ref($listref) eq 'ARRAY') {
10383:             my @stats = split('&',$listref->[0]);
10384: 	    shift(@stats); #filename is first
10385: 	    return @stats;
10386:         }
10387:     }
10388:     return ();
10389: }
10390: 
10391: # -------------------------------------------------------- Value of a Condition
10392: 
10393: # gets the value of a specific preevaluated condition
10394: #    stored in the string  $env{user.state.<cid>}
10395: # or looks up a condition reference in the bighash and if if hasn't
10396: # already been evaluated recurses into docondval to get the value of
10397: # the condition, then memoizing it to 
10398: #   $env{user.state.<cid>.<condition>}
10399: sub directcondval {
10400:     my $number=shift;
10401:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
10402: 	&Apache::lonuserstate::evalstate();
10403:     }
10404:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10405: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10406:     } elsif ($number =~ /^_/) {
10407: 	my $sub_condition;
10408: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10409: 		&GDBM_READER(),0640)) {
10410: 	    $sub_condition=$bighash{'conditions'.$number};
10411: 	    untie(%bighash);
10412: 	}
10413: 	my $value = &docondval($sub_condition);
10414: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
10415: 	return $value;
10416:     }
10417:     if ($env{'user.state.'.$env{'request.course.id'}}) {
10418:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
10419:     } else {
10420:        return 2;
10421:     }
10422: }
10423: 
10424: # get the collection of conditions for this resource
10425: sub condval {
10426:     my $condidx=shift;
10427:     my $allpathcond='';
10428:     foreach my $cond (split(/\|/,$condidx)) {
10429: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10430: 	    $allpathcond.=
10431: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10432: 	}
10433:     }
10434:     $allpathcond=~s/\|$//;
10435:     return &docondval($allpathcond);
10436: }
10437: 
10438: #evaluates an expression of conditions
10439: sub docondval {
10440:     my ($allpathcond) = @_;
10441:     my $result=0;
10442:     if ($env{'request.course.id'}
10443: 	&& defined($allpathcond)) {
10444: 	my $operand='|';
10445: 	my @stack;
10446: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10447: 	    if ($chunk eq '(') {
10448: 		push @stack,($operand,$result);
10449: 	    } elsif ($chunk eq ')') {
10450: 		my $before=pop @stack;
10451: 		if (pop @stack eq '&') {
10452: 		    $result=$result>$before?$before:$result;
10453: 		} else {
10454: 		    $result=$result>$before?$result:$before;
10455: 		}
10456: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
10457: 		$operand=$chunk;
10458: 	    } else {
10459: 		my $new=directcondval($chunk);
10460: 		if ($operand eq '&') {
10461: 		    $result=$result>$new?$new:$result;
10462: 		} else {
10463: 		    $result=$result>$new?$result:$new;
10464: 		}
10465: 	    }
10466: 	}
10467:     }
10468:     return $result;
10469: }
10470: 
10471: # ---------------------------------------------------- Devalidate courseresdata
10472: 
10473: sub devalidatecourseresdata {
10474:     my ($coursenum,$coursedomain)=@_;
10475:     my $hashid=$coursenum.':'.$coursedomain;
10476:     &devalidate_cache_new('courseres',$hashid);
10477: }
10478: 
10479: 
10480: # --------------------------------------------------- Course Resourcedata Query
10481: #
10482: #  Parameters:
10483: #      $coursenum    - Number of the course.
10484: #      $coursedomain - Domain at which the course was created.
10485: #  Returns:
10486: #     A hash of the course parameters along (I think) with timestamps
10487: #     and version info.
10488: 
10489: sub get_courseresdata {
10490:     my ($coursenum,$coursedomain)=@_;
10491:     my $coursehom=&homeserver($coursenum,$coursedomain);
10492:     my $hashid=$coursenum.':'.$coursedomain;
10493:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
10494:     my %dumpreply;
10495:     unless (defined($cached)) {
10496: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
10497: 	$result=\%dumpreply;
10498: 	my ($tmp) = keys(%dumpreply);
10499: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10500: 	    &do_cache_new('courseres',$hashid,$result,600);
10501: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10502: 	    return $tmp;
10503: 	} elsif ($tmp =~ /^(error)/) {
10504: 	    $result=undef;
10505: 	    &do_cache_new('courseres',$hashid,$result,600);
10506: 	}
10507:     }
10508:     return $result;
10509: }
10510: 
10511: sub devalidateuserresdata {
10512:     my ($uname,$udom)=@_;
10513:     my $hashid="$udom:$uname";
10514:     &devalidate_cache_new('userres',$hashid);
10515: }
10516: 
10517: sub get_userresdata {
10518:     my ($uname,$udom)=@_;
10519:     #most student don\'t have any data set, check if there is some data
10520:     if (&EXT_cache_status($udom,$uname)) { return undef; }
10521: 
10522:     my $hashid="$udom:$uname";
10523:     my ($result,$cached)=&is_cached_new('userres',$hashid);
10524:     if (!defined($cached)) {
10525: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
10526: 	$result=\%resourcedata;
10527: 	&do_cache_new('userres',$hashid,$result,600);
10528:     }
10529:     my ($tmp)=keys(%$result);
10530:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10531: 	return $result;
10532:     }
10533:     #error 2 occurs when the .db doesn't exist
10534:     if ($tmp!~/error: 2 /) {
10535:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10536: 	    &logthis("<font color=\"blue\">WARNING:".
10537: 		     " Trying to get resource data for ".
10538: 		     $uname." at ".$udom.": ".
10539: 		     $tmp."</font>");
10540:         }
10541:     } elsif ($tmp=~/error: 2 /) {
10542: 	#&EXT_cache_set($udom,$uname);
10543: 	&do_cache_new('userres',$hashid,undef,600);
10544: 	undef($tmp); # not really an error so don't send it back
10545:     }
10546:     return $tmp;
10547: }
10548: #----------------------------------------------- resdata - return resource data
10549: #  Purpose:
10550: #    Return resource data for either users or for a course.
10551: #  Parameters:
10552: #     $name      - Course/user name.
10553: #     $domain    - Name of the domain the user/course is registered on.
10554: #     $type      - Type of thing $name is (must be 'course' or 'user')
10555: #     @which     - Array of names of resources desired.
10556: #  Returns:
10557: #     The value of the first reasource in @which that is found in the
10558: #     resource hash.
10559: #  Exceptional Conditions:
10560: #     If the $type passed in is not valid (not the string 'course' or 
10561: #     'user', an undefined  reference is returned.
10562: #     If none of the resources are found, an undef is returned
10563: sub resdata {
10564:     my ($name,$domain,$type,@which)=@_;
10565:     my $result;
10566:     if ($type eq 'course') {
10567: 	$result=&get_courseresdata($name,$domain);
10568:     } elsif ($type eq 'user') {
10569: 	$result=&get_userresdata($name,$domain);
10570:     }
10571:     if (!ref($result)) { return $result; }    
10572:     foreach my $item (@which) {
10573:         if (ref($item) eq 'ARRAY') {
10574: 	    if (defined($result->{$item->[0]})) {
10575: 	        return [$result->{$item->[0]},$item->[1]];
10576: 	    }
10577:         }
10578:     }
10579:     return undef;
10580: }
10581: 
10582: sub get_domain_ltitools {
10583:     my ($cdom) = @_;
10584:     my %ltitools;
10585:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10586:     if (defined($cached)) {
10587:         if (ref($result) eq 'HASH') {
10588:             %ltitools = %{$result};
10589:         }
10590:     } else {
10591:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10592:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
10593:             %ltitools = %{$domconfig{'ltitools'}};
10594:             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
10595:             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
10596:                 foreach my $id (keys(%ltitools)) {
10597:                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
10598:                         foreach my $item ('key','secret') {
10599:                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
10600:                         }
10601:                     }
10602:                 }
10603:             }
10604:         }
10605:         my $cachetime = 24*60*60;
10606:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10607:     }
10608:     return %ltitools;
10609: }
10610: 
10611: sub get_numsuppfiles {
10612:     my ($cnum,$cdom,$ignorecache)=@_;
10613:     my $hashid=$cnum.':'.$cdom;
10614:     my ($suppcount,$cached);
10615:     unless ($ignorecache) {
10616:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10617:     }
10618:     unless (defined($cached)) {
10619:         my $chome=&homeserver($cnum,$cdom);
10620:         unless ($chome eq 'no_host') {
10621:             ($suppcount,my $errors) = (0,0);
10622:             my $suppmap = 'supplemental.sequence';
10623:             ($suppcount,$errors) =
10624:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10625:         }
10626:         &do_cache_new('suppcount',$hashid,$suppcount,600);
10627:     }
10628:     return $suppcount;
10629: }
10630: 
10631: #
10632: # EXT resource caching routines
10633: #
10634: 
10635: sub clear_EXT_cache_status {
10636:     &delenv('cache.EXT.');
10637: }
10638: 
10639: sub EXT_cache_status {
10640:     my ($target_domain,$target_user) = @_;
10641:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10642:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
10643:         # We know already the user has no data
10644:         return 1;
10645:     } else {
10646:         return 0;
10647:     }
10648: }
10649: 
10650: sub EXT_cache_set {
10651:     my ($target_domain,$target_user) = @_;
10652:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10653:     #&appenv({$cachename => time});
10654: }
10655: 
10656: # --------------------------------------------------------- Value of a Variable
10657: sub EXT {
10658: 
10659:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
10660:     unless ($varname) { return ''; }
10661:     #get real user name/domain, courseid and symb
10662:     my $courseid;
10663:     my $publicuser;
10664:     if ($symbparm) {
10665: 	$symbparm=&get_symb_from_alias($symbparm);
10666:     }
10667:     if (!($uname && $udom)) {
10668:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
10669:       if (!$symbparm) {	$symbparm=$cursymb; }
10670:     } else {
10671: 	$courseid=$env{'request.course.id'};
10672:     }
10673:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10674:     my $rest;
10675:     if (defined($therest[0])) {
10676:        $rest=join('.',@therest);
10677:     } else {
10678:        $rest='';
10679:     }
10680: 
10681:     my $qualifierrest=$qualifier;
10682:     if ($rest) { $qualifierrest.='.'.$rest; }
10683:     my $spacequalifierrest=$space;
10684:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
10685:     if ($realm eq 'user') {
10686: # --------------------------------------------------------------- user.resource
10687: 	if ($space eq 'resource') {
10688: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
10689: 		  || defined($Apache::lonhomework::parsing_a_task))
10690: 		 &&
10691: 		 ($symbparm eq &symbread()) ) {	
10692: 		# if we are in the middle of processing the resource the
10693: 		# get the value we are planning on committing
10694:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
10695:                     return $Apache::lonhomework::results{$qualifierrest};
10696:                 } else {
10697:                     return $Apache::lonhomework::history{$qualifierrest};
10698:                 }
10699: 	    } else {
10700: 		my %restored;
10701: 		if ($publicuser || $env{'request.state'} eq 'construct') {
10702: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10703: 		} else {
10704: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
10705: 		}
10706: 		return $restored{$qualifierrest};
10707: 	    }
10708: # ----------------------------------------------------------------- user.access
10709:         } elsif ($space eq 'access') {
10710: 	    # FIXME - not supporting calls for a specific user
10711:             return &allowed($qualifier,$rest);
10712: # ------------------------------------------ user.preferences, user.environment
10713:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
10714: 	    if (($uname eq $env{'user.name'}) &&
10715: 		($udom eq $env{'user.domain'})) {
10716: 		return $env{join('.',('environment',$qualifierrest))};
10717: 	    } else {
10718: 		my %returnhash;
10719: 		if (!$publicuser) {
10720: 		    %returnhash=&userenvironment($udom,$uname,
10721: 						 $qualifierrest);
10722: 		}
10723: 		return $returnhash{$qualifierrest};
10724: 	    }
10725: # ----------------------------------------------------------------- user.course
10726:         } elsif ($space eq 'course') {
10727: 	    # FIXME - not supporting calls for a specific user
10728:             return $env{join('.',('request.course',$qualifier))};
10729: # ------------------------------------------------------------------- user.role
10730:         } elsif ($space eq 'role') {
10731: 	    # FIXME - not supporting calls for a specific user
10732:             my ($role,$where)=split(/\./,$env{'request.role'});
10733:             if ($qualifier eq 'value') {
10734: 		return $role;
10735:             } elsif ($qualifier eq 'extent') {
10736:                 return $where;
10737:             }
10738: # ----------------------------------------------------------------- user.domain
10739:         } elsif ($space eq 'domain') {
10740:             return $udom;
10741: # ------------------------------------------------------------------- user.name
10742:         } elsif ($space eq 'name') {
10743:             return $uname;
10744: # ---------------------------------------------------- Any other user namespace
10745:         } else {
10746: 	    my %reply;
10747: 	    if (!$publicuser) {
10748: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
10749: 	    }
10750: 	    return $reply{$qualifierrest};
10751:         }
10752:     } elsif ($realm eq 'query') {
10753: # ---------------------------------------------- pull stuff out of query string
10754:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10755: 						[$spacequalifierrest]);
10756: 	return $env{'form.'.$spacequalifierrest}; 
10757:    } elsif ($realm eq 'request') {
10758: # ------------------------------------------------------------- request.browser
10759:         if ($space eq 'browser') {
10760:             return $env{'browser.'.$qualifier};
10761: # ------------------------------------------------------------ request.filename
10762:         } else {
10763:             return $env{'request.'.$spacequalifierrest};
10764:         }
10765:     } elsif ($realm eq 'course') {
10766: # ---------------------------------------------------------- course.description
10767:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
10768:     } elsif ($realm eq 'resource') {
10769: 
10770: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
10771: 	    if (!$symbparm) { $symbparm=&symbread(); }
10772: 	}
10773: 
10774:         if ($qualifier eq '') {
10775: 	    if ($space eq 'title') {
10776: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10777: 	        return &gettitle($symbparm);
10778: 	    }
10779: 	
10780: 	    if ($space eq 'map') {
10781: 	        my ($map) = &decode_symb($symbparm);
10782: 	        return &symbread($map);
10783: 	    }
10784:             if ($space eq 'maptitle') {
10785:                 my ($map) = &decode_symb($symbparm);
10786:                 return &gettitle($map);
10787:             }
10788: 	    if ($space eq 'filename') {
10789: 	        if ($symbparm) {
10790: 		    return &clutter((&decode_symb($symbparm))[2]);
10791: 	        }
10792: 	        return &hreflocation('',$env{'request.filename'});
10793: 	    }
10794: 
10795:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10796:                 if ($space eq 'visibleparts') {
10797:                     my $navmap = Apache::lonnavmaps::navmap->new();
10798:                     my $item;
10799:                     if (ref($navmap)) {
10800:                         my $res = $navmap->getBySymb($symbparm);
10801:                         my $parts = $res->parts();
10802:                         if (ref($parts) eq 'ARRAY') {
10803:                             $item = join(',',@{$parts});
10804:                         }
10805:                         undef($navmap);
10806:                     }
10807:                     return $item;
10808:                 }
10809:             }
10810:         }
10811: 
10812: 	my ($section, $group, @groups);
10813: 	my ($courselevelm,$courselevel);
10814:         if (($courseid eq '') && ($cid)) {
10815:             $courseid = $cid;
10816:         }
10817: 	if (($symbparm && $courseid) && 
10818: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
10819: 
10820: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
10821: 
10822: # ----------------------------------------------------- Cascading lookup scheme
10823: 	    my $symbp=$symbparm;
10824: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
10825: 
10826: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
10827: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10828: 
10829: 	    if (($env{'user.name'} eq $uname) &&
10830: 		($env{'user.domain'} eq $udom)) {
10831: 		$section=$env{'request.course.sec'};
10832:                 @groups = split(/:/,$env{'request.course.groups'});  
10833:                 @groups=&sort_course_groups($courseid,@groups); 
10834: 	    } else {
10835: 		if (! defined($usection)) {
10836: 		    $section=&getsection($udom,$uname,$courseid);
10837: 		} else {
10838: 		    $section = $usection;
10839: 		}
10840:                 @groups = &get_users_groups($udom,$uname,$courseid);
10841: 	    }
10842: 
10843: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10844: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10845: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10846: 
10847: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
10848: 	    my $courselevelr=$courseid.'.'.$symbparm;
10849: 	    $courselevelm=$courseid.'.'.$mapparm;
10850: 
10851: # ----------------------------------------------------------- first, check user
10852: 
10853: 	    my $userreply=&resdata($uname,$udom,'user',
10854: 				       ([$courselevelr,'resource'],
10855: 					[$courselevelm,'map'     ],
10856: 					[$courselevel, 'course'  ]));
10857: 	    if (defined($userreply)) { return &get_reply($userreply); }
10858: 
10859: # ------------------------------------------------ second, check some of course
10860:             my $coursereply;
10861:             if (@groups > 0) {
10862:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10863:                                        $mapparm,$spacequalifierrest);
10864:                 if (defined($coursereply)) { return &get_reply($coursereply); }
10865:             }
10866: 
10867: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10868: 				  $env{'course.'.$courseid.'.domain'},
10869: 				  'course',
10870: 				  ([$seclevelr,   'resource'],
10871: 				   [$seclevelm,   'map'     ],
10872: 				   [$seclevel,    'course'  ],
10873: 				   [$courselevelr,'resource']));
10874: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10875: 
10876: # ------------------------------------------------------ third, check map parms
10877: 	    my %parmhash=();
10878: 	    my $thisparm='';
10879: 	    if (tie(%parmhash,'GDBM_File',
10880: 		    $env{'request.course.fn'}.'_parms.db',
10881: 		    &GDBM_READER(),0640)) {
10882: 		$thisparm=$parmhash{$symbparm};
10883: 		untie(%parmhash);
10884: 	    }
10885: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10886: 	}
10887: # ------------------------------------------ fourth, look in resource metadata
10888: 
10889: 	$spacequalifierrest=~s/\./\_/;
10890: 	my $filename;
10891: 	if (!$symbparm) { $symbparm=&symbread(); }
10892: 	if ($symbparm) {
10893: 	    $filename=(&decode_symb($symbparm))[2];
10894: 	} else {
10895: 	    $filename=$env{'request.filename'};
10896: 	}
10897: 	my $metadata=&metadata($filename,$spacequalifierrest);
10898: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10899: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10900: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10901: 
10902: # ---------------------------------------------- fourth, look in rest of course
10903: 	if ($symbparm && defined($courseid) && 
10904: 	    $courseid eq $env{'request.course.id'}) {
10905: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10906: 				     $env{'course.'.$courseid.'.domain'},
10907: 				     'course',
10908: 				     ([$courselevelm,'map'   ],
10909: 				      [$courselevel, 'course']));
10910: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10911: 	}
10912: # ------------------------------------------------------------------ Cascade up
10913: 	unless ($space eq '0') {
10914: 	    my @parts=split(/_/,$space);
10915: 	    my $id=pop(@parts);
10916: 	    my $part=join('_',@parts);
10917: 	    if ($part eq '') { $part='0'; }
10918: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10919: 				 $symbparm,$udom,$uname,$section,1);
10920: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10921: 	}
10922: 	if ($recurse) { return undef; }
10923: 	my $pack_def=&packages_tab_default($filename,$varname);
10924: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10925: # ---------------------------------------------------- Any other user namespace
10926:     } elsif ($realm eq 'environment') {
10927: # ----------------------------------------------------------------- environment
10928: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10929: 	    return $env{'environment.'.$spacequalifierrest};
10930: 	} else {
10931: 	    if ($uname eq 'anonymous' && $udom eq '') {
10932: 		return '';
10933: 	    }
10934: 	    my %returnhash=&userenvironment($udom,$uname,
10935: 					    $spacequalifierrest);
10936: 	    return $returnhash{$spacequalifierrest};
10937: 	}
10938:     } elsif ($realm eq 'system') {
10939: # ----------------------------------------------------------------- system.time
10940: 	if ($space eq 'time') {
10941: 	    return time;
10942:         }
10943:     } elsif ($realm eq 'server') {
10944: # ----------------------------------------------------------------- system.time
10945: 	if ($space eq 'name') {
10946: 	    return $ENV{'SERVER_NAME'};
10947:         }
10948:     }
10949:     return '';
10950: }
10951: 
10952: sub get_reply {
10953:     my ($reply_value) = @_;
10954:     if (ref($reply_value) eq 'ARRAY') {
10955:         if (wantarray) {
10956: 	    return @$reply_value;
10957:         }
10958:         return $reply_value->[0];
10959:     } else {
10960:         return $reply_value;
10961:     }
10962: }
10963: 
10964: sub check_group_parms {
10965:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10966:     my @groupitems = ();
10967:     my $resultitem;
10968:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10969:     foreach my $group (@{$groups}) {
10970:         foreach my $level (@levels) {
10971:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10972:              push(@groupitems,[$item,$level->[1]]);
10973:         }
10974:     }
10975:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10976:                             $env{'course.'.$courseid.'.domain'},
10977:                                      'course',@groupitems);
10978:     return $coursereply;
10979: }
10980: 
10981: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10982:     my ($courseid,@groups) = @_;
10983:     @groups = sort(@groups);
10984:     return @groups;
10985: }
10986: 
10987: sub packages_tab_default {
10988:     my ($uri,$varname)=@_;
10989:     my (undef,$part,$name)=split(/\./,$varname);
10990: 
10991:     my (@extension,@specifics,$do_default);
10992:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10993: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10994: 	if ($pack_type eq 'default') {
10995: 	    $do_default=1;
10996: 	} elsif ($pack_type eq 'extension') {
10997: 	    push(@extension,[$package,$pack_type,$pack_part]);
10998: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10999: 	    # only look at packages defaults for packages that this id is
11000: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11001: 	}
11002:     }
11003:     # first look for a package that matches the requested part id
11004:     foreach my $package (@specifics) {
11005: 	my (undef,$pack_type,$pack_part)=@{$package};
11006: 	next if ($pack_part ne $part);
11007: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11008: 	    return $packagetab{"$pack_type&$name&default"};
11009: 	}
11010:     }
11011:     # look for any possible matching non extension_ package
11012:     foreach my $package (@specifics) {
11013: 	my (undef,$pack_type,$pack_part)=@{$package};
11014: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11015: 	    return $packagetab{"$pack_type&$name&default"};
11016: 	}
11017: 	if ($pack_type eq 'part') { $pack_part='0'; }
11018: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11019: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11020: 	}
11021:     }
11022:     # look for any posible extension_ match
11023:     foreach my $package (@extension) {
11024: 	my ($package,$pack_type)=@{$package};
11025: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11026: 	    return $packagetab{"$pack_type&$name&default"};
11027: 	}
11028: 	if (defined($packagetab{$package."&$name&default"})) {
11029: 	    return $packagetab{$package."&$name&default"};
11030: 	}
11031:     }
11032:     # look for a global default setting
11033:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11034: 	return $packagetab{"default&$name&default"};
11035:     }
11036:     return undef;
11037: }
11038: 
11039: sub add_prefix_and_part {
11040:     my ($prefix,$part)=@_;
11041:     my $keyroot;
11042:     if (defined($prefix) && $prefix !~ /^__/) {
11043: 	# prefix that has a part already
11044: 	$keyroot=$prefix;
11045:     } elsif (defined($prefix)) {
11046: 	# prefix that is missing a part
11047: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11048:     } else {
11049: 	# no prefix at all
11050: 	if (defined($part)) { $keyroot='_'.$part; }
11051:     }
11052:     return $keyroot;
11053: }
11054: 
11055: # ---------------------------------------------------------------- Get metadata
11056: 
11057: my %metaentry;
11058: my %importedpartids;
11059: my %importedrespids;
11060: sub metadata {
11061:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11062:     $uri=&declutter($uri);
11063:     # if it is a non metadata possible uri return quickly
11064:     if (($uri eq '') || 
11065: 	(($uri =~ m|^/*adm/|) && 
11066: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11067:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11068: 	return undef;
11069:     }
11070:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11071: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11072: 	return undef;
11073:     }
11074:     my $filename=$uri;
11075:     $uri=~s/\.meta$//;
11076: #
11077: # Is the metadata already cached?
11078: # Look at timestamp of caching
11079: # Everything is cached by the main uri, libraries are never directly cached
11080: #
11081:     if (!defined($liburi)) {
11082: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11083: 	if (defined($cached)) { return $result->{':'.$what}; }
11084:     }
11085:     {
11086: # Imported parts would go here
11087:         my @origfiletagids=();
11088:         my $importedparts=0;
11089: 
11090: # Imported responseids would go here
11091:         my $importedresponses=0;
11092: #
11093: # Is this a recursive call for a library?
11094: #
11095: #	if (! exists($metacache{$uri})) {
11096: #	    $metacache{$uri}={};
11097: #	}
11098: 	my $cachetime = 60*60;
11099:         if ($liburi) {
11100: 	    $liburi=&declutter($liburi);
11101:             $filename=$liburi;
11102:         } else {
11103: 	    &devalidate_cache_new('meta',$uri);
11104: 	    undef(%metaentry);
11105: 	}
11106:         my %metathesekeys=();
11107:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11108: 	my $metastring;
11109: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11110: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11111: 	    $metastring = 
11112: 		&Apache::lonnet::ssi_body($which,
11113: 					  ('grade_target' => 'meta'));
11114: 	    $cachetime = 1; # only want this cached in the child not long term
11115: 	} elsif (($uri !~ m -^(editupload)/-) && 
11116:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11117: 	    my $file=&filelocation('',&clutter($filename));
11118: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11119: 	    $metastring=&getfile($file);
11120: 	}
11121:         my $parser=HTML::LCParser->new(\$metastring);
11122:         my $token;
11123:         undef %metathesekeys;
11124:         while ($token=$parser->get_token) {
11125: 	    if ($token->[0] eq 'S') {
11126: 		if (defined($token->[2]->{'package'})) {
11127: #
11128: # This is a package - get package info
11129: #
11130: 		    my $package=$token->[2]->{'package'};
11131: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11132: 		    if (defined($token->[2]->{'id'})) { 
11133: 			$keyroot.='_'.$token->[2]->{'id'}; 
11134: 		    }
11135: 		    if ($metaentry{':packages'}) {
11136: 			$metaentry{':packages'}.=','.$package.$keyroot;
11137: 		    } else {
11138: 			$metaentry{':packages'}=$package.$keyroot;
11139: 		    }
11140: 		    foreach my $pack_entry (keys(%packagetab)) {
11141: 			my $part=$keyroot;
11142: 			$part=~s/^\_//;
11143: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11144: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11145: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11146: 			    # ignore package.tab specified default values
11147:                             # here &package_tab_default() will fetch those
11148: 			    if ($subp eq 'default') { next; }
11149: 			    my $value=$packagetab{$pack_entry};
11150: 			    my $unikey;
11151: 			    if ($pack =~ /_0$/) {
11152: 				$unikey='parameter_0_'.$name;
11153: 				$part=0;
11154: 			    } else {
11155: 				$unikey='parameter'.$keyroot.'_'.$name;
11156: 			    }
11157: 			    if ($subp eq 'display') {
11158: 				$value.=' [Part: '.$part.']';
11159: 			    }
11160: 			    $metaentry{':'.$unikey.'.part'}=$part;
11161: 			    $metathesekeys{$unikey}=1;
11162: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11163: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11164: 			    }
11165: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11166: 				$metaentry{':'.$unikey}=
11167: 				    $metaentry{':'.$unikey.'.default'};
11168: 			    }
11169: 			}
11170: 		    }
11171: 		} else {
11172: #
11173: # This is not a package - some other kind of start tag
11174: #
11175: 		    my $entry=$token->[1];
11176: 		    my $unikey='';
11177: 
11178: 		    if ($entry eq 'import') {
11179: #
11180: # Importing a library here
11181: #
11182:                         my $location=$parser->get_text('/import');
11183:                         my $dir=$filename;
11184:                         $dir=~s|[^/]*$||;
11185:                         $location=&filelocation($dir,$location);
11186: 
11187:                         my $importid=$token->[2]->{'id'};
11188:                         my $importmode=$token->[2]->{'importmode'};
11189: #
11190: # Check metadata for imported file to
11191: # see if it contained response items
11192: #
11193:                         my $libresponseorder = &metadata($location,'responseorder');
11194:                         my $origfile;
11195:                         if ($libresponseorder ne '') {
11196:                             if ($#origfiletagids<0) {
11197:                                 undef(%importedrespids);
11198:                                 undef(%importedpartids);
11199:                             }
11200:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11201:                             if (@{$importedrespids{$importid}} > 0) {
11202:                                 $importedresponses = 1;
11203: # We need to get the original file and the imported file to get the response order correct
11204: # Load and inspect original file
11205:                                 if ($#origfiletagids<0) {
11206:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11207:                                     $origfile=&getfile($origfilelocation);
11208:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11209:                                 }
11210:                             }
11211:                         }
11212:                         if ($importmode eq 'problem') {
11213: # Import as problem/response
11214:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11215:                         } elsif ($importmode eq 'part') {
11216: # Import as part(s)
11217:                            $importedparts=1;
11218: # We need to get the original file and the imported file to get the part order correct
11219: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11220: # Load and inspect original file if we didn't do that already
11221:                            if ($#origfileimportpartids<0) {
11222:                                undef(%importedrespids);
11223:                                undef(%importedpartids);
11224:                                if ($origfile eq '') {
11225:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11226:                                    $origfile=&getfile($origfilelocation);
11227:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11228:                                }
11229:                            }
11230: 
11231: # Load and inspect imported file
11232:                            my $impfile=&getfile($location);
11233:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11234:                            if ($#impfilepartids>=0) {
11235: # This problem had parts
11236:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11237:                            } else {
11238: # Importing by turning a single problem into a problem part
11239: # It gets the import-tags ID as part-ID
11240:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11241:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11242:                            }
11243:                         } else {
11244: # Normal import
11245:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11246:                            if (defined($token->[2]->{'id'})) {
11247:                               $unikey.='_'.$token->[2]->{'id'};
11248:                            }
11249:                         }
11250: 
11251: 			if ($depthcount<20) {
11252: 			    my $metadata = 
11253: 				&metadata($uri,'keys', $location,$unikey,
11254: 					  $depthcount+1);
11255: 			    foreach my $meta (split(',',$metadata)) {
11256: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
11257: 				$metathesekeys{$meta}=1;
11258: 			    }
11259: 			
11260:                         }
11261: 		    } else {
11262: #
11263: # Not importing, some other kind of non-package, non-library start tag
11264: # 
11265:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11266:                         if (defined($token->[2]->{'id'})) {
11267:                             $unikey.='_'.$token->[2]->{'id'};
11268:                         }
11269: 			if (defined($token->[2]->{'name'})) { 
11270: 			    $unikey.='_'.$token->[2]->{'name'}; 
11271: 			}
11272: 			$metathesekeys{$unikey}=1;
11273: 			foreach my $param (@{$token->[3]}) {
11274: 			    $metaentry{':'.$unikey.'.'.$param} =
11275: 				$token->[2]->{$param};
11276: 			}
11277: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
11278: 			my $default=$metaentry{':'.$unikey.'.default'};
11279: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11280: 		 # only ws inside the tag, and not in default, so use default
11281: 		 # as value
11282: 			    $metaentry{':'.$unikey}=$default;
11283: 			} elsif ( $internaltext =~ /\S/ ) {
11284: 		  # something interesting inside the tag
11285: 			    $metaentry{':'.$unikey}=$internaltext;
11286: 			} else {
11287: 		  # no interesting values, don't set a default
11288: 			}
11289: # end of not-a-package not-a-library import
11290: 		    }
11291: # end of not-a-package start tag
11292: 		}
11293: # the next is the end of "start tag"
11294: 	    }
11295: 	}
11296: 	my ($extension) = ($uri =~ /\.(\w+)$/);
11297: 	$extension = lc($extension);
11298: 	if ($extension eq 'htm') { $extension='html'; }
11299: 
11300: 	foreach my $key (keys(%packagetab)) {
11301: 	    #no specific packages #how's our extension
11302: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
11303: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
11304: 					 \%metathesekeys);
11305: 	}
11306: 
11307: 	if (!exists($metaentry{':packages'})
11308: 	    || $packagetab{"import_defaults&extension_$extension"}) {
11309: 	    foreach my $key (keys(%packagetab)) {
11310: 		#no specific packages well let's get default then
11311: 		if ($key!~/^default&/) { next; }
11312: 		&metadata_create_package_def($uri,$key,'default',
11313: 					     \%metathesekeys);
11314: 	    }
11315: 	}
11316: # are there custom rights to evaluate
11317: 	if ($metaentry{':copyright'} eq 'custom') {
11318: 
11319:     #
11320:     # Importing a rights file here
11321:     #
11322: 	    unless ($depthcount) {
11323: 		my $location=$metaentry{':customdistributionfile'};
11324: 		my $dir=$filename;
11325: 		$dir=~s|[^/]*$||;
11326: 		$location=&filelocation($dir,$location);
11327: 		my $rights_metadata =
11328: 		    &metadata($uri,'keys',$location,'_rights',
11329: 			      $depthcount+1);
11330: 		foreach my $rights (split(',',$rights_metadata)) {
11331: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11332: 		    $metathesekeys{$rights}=1;
11333: 		}
11334: 	    }
11335: 	}
11336: 	# uniqifiy package listing
11337: 	my %seen;
11338: 	my @uniq_packages =
11339: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11340: 	$metaentry{':packages'} = join(',',@uniq_packages);
11341: 
11342:         if (($importedresponses) || ($importedparts)) {
11343:             if ($importedparts) {
11344: # We had imported parts and need to rebuild partorder
11345:                 $metaentry{':partorder'}='';
11346:                 $metathesekeys{'partorder'}=1;
11347:             }
11348:             if ($importedresponses) {
11349: # We had imported responses and need to rebuild responseorder
11350:                 $metaentry{':responseorder'}='';
11351:                 $metathesekeys{'responseorder'}=1;
11352:             }
11353:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
11354:                 my $origid = $origfiletagids[$index+1];
11355:                 if ($origfiletagids[$index] eq 'part') {
11356: # Original part, part of the problem
11357:                     if ($importedparts) {
11358:                         $metaentry{':partorder'}.=','.$origid;
11359:                     }
11360:                 } elsif ($origfiletagids[$index] eq 'import') {
11361:                     if ($importedparts) {
11362: # We have imported parts at this position
11363:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
11364:                     }
11365:                     if ($importedresponses) {
11366: # We have imported responses at this position
11367:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
11368:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
11369:                         }
11370:                     }
11371:                 } else {
11372: # Original response item, part of the problem
11373:                     if ($importedresponses) {
11374:                         $metaentry{':responseorder'}.=','.$origid;
11375:                     }
11376:                 }
11377:             }
11378:             if ($importedparts) {
11379:                 $metaentry{':partorder'}=~s/^\,//;
11380:             }
11381:             if ($importedresponses) {
11382:                 $metaentry{':responseorder'}=~s/^\,//;
11383:             }
11384:         }
11385: 
11386: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
11387: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
11388: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
11389: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
11390: # this is the end of "was not already recently cached
11391:     }
11392:     return $metaentry{':'.$what};
11393: }
11394: 
11395: sub metadata_create_package_def {
11396:     my ($uri,$key,$package,$metathesekeys)=@_;
11397:     my ($pack,$name,$subp)=split(/\&/,$key);
11398:     if ($subp eq 'default') { next; }
11399:     
11400:     if (defined($metaentry{':packages'})) {
11401: 	$metaentry{':packages'}.=','.$package;
11402:     } else {
11403: 	$metaentry{':packages'}=$package;
11404:     }
11405:     my $value=$packagetab{$key};
11406:     my $unikey;
11407:     $unikey='parameter_0_'.$name;
11408:     $metaentry{':'.$unikey.'.part'}=0;
11409:     $$metathesekeys{$unikey}=1;
11410:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11411: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
11412:     }
11413:     if (defined($metaentry{':'.$unikey.'.default'})) {
11414: 	$metaentry{':'.$unikey}=
11415: 	    $metaentry{':'.$unikey.'.default'};
11416:     }
11417: }
11418: 
11419: sub metadata_generate_part0 {
11420:     my ($metadata,$metacache,$uri) = @_;
11421:     my %allnames;
11422:     foreach my $metakey (keys(%$metadata)) {
11423: 	if ($metakey=~/^parameter\_(.*)/) {
11424: 	  my $part=$$metacache{':'.$metakey.'.part'};
11425: 	  my $name=$$metacache{':'.$metakey.'.name'};
11426: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
11427: 	    $allnames{$name}=$part;
11428: 	  }
11429: 	}
11430:     }
11431:     foreach my $name (keys(%allnames)) {
11432:       $$metadata{"parameter_0_$name"}=1;
11433:       my $key=":parameter_0_$name";
11434:       $$metacache{"$key.part"}='0';
11435:       $$metacache{"$key.name"}=$name;
11436:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
11437: 					   $allnames{$name}.'_'.$name.
11438: 					   '.type'};
11439:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
11440: 			     '.display'};
11441:       my $expr='[Part: '.$allnames{$name}.']';
11442:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
11443:       $$metacache{"$key.display"}=$olddis;
11444:     }
11445: }
11446: 
11447: # ------------------------------------------------------ Devalidate title cache
11448: 
11449: sub devalidate_title_cache {
11450:     my ($url)=@_;
11451:     if (!$env{'request.course.id'}) { return; }
11452:     my $symb=&symbread($url);
11453:     if (!$symb) { return; }
11454:     my $key=$env{'request.course.id'}."\0".$symb;
11455:     &devalidate_cache_new('title',$key);
11456: }
11457: 
11458: # ------------------------------------------------- Get the title of a course
11459: 
11460: sub current_course_title {
11461:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11462: }
11463: # ------------------------------------------------- Get the title of a resource
11464: 
11465: sub gettitle {
11466:     my $urlsymb=shift;
11467:     my $symb=&symbread($urlsymb);
11468:     if ($symb) {
11469: 	my $key=$env{'request.course.id'}."\0".$symb;
11470: 	my ($result,$cached)=&is_cached_new('title',$key);
11471: 	if (defined($cached)) { 
11472: 	    return $result;
11473: 	}
11474: 	my ($map,$resid,$url)=&decode_symb($symb);
11475: 	my $title='';
11476: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11477: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11478: 	} else {
11479: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11480: 		    &GDBM_READER(),0640)) {
11481: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
11482: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
11483: 		untie(%bighash);
11484: 	    }
11485: 	}
11486: 	$title=~s/\&colon\;/\:/gs;
11487: 	if ($title) {
11488: # Remember both $symb and $title for dynamic metadata
11489:             $accesshash{$symb.'___crstitle'}=$title;
11490:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
11491: # Cache this title and then return it
11492: 	    return &do_cache_new('title',$key,$title,600);
11493: 	}
11494: 	$urlsymb=$url;
11495:     }
11496:     my $title=&metadata($urlsymb,'title');
11497:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
11498:     return $title;
11499: }
11500: 
11501: sub get_slot {
11502:     my ($which,$cnum,$cdom)=@_;
11503:     if (!$cnum || !$cdom) {
11504: 	(undef,my $courseid)=&whichuser();
11505: 	$cdom=$env{'course.'.$courseid.'.domain'};
11506: 	$cnum=$env{'course.'.$courseid.'.num'};
11507:     }
11508:     my $key=join("\0",'slots',$cdom,$cnum,$which);
11509:     my %slotinfo;
11510:     if (exists($remembered{$key})) {
11511: 	$slotinfo{$which} = $remembered{$key};
11512:     } else {
11513: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
11514: 	&Apache::lonhomework::showhash(%slotinfo);
11515: 	my ($tmp)=keys(%slotinfo);
11516: 	if ($tmp=~/^error:/) { return (); }
11517: 	$remembered{$key} = $slotinfo{$which};
11518:     }
11519:     if (ref($slotinfo{$which}) eq 'HASH') {
11520: 	return %{$slotinfo{$which}};
11521:     }
11522:     return $slotinfo{$which};
11523: }
11524: 
11525: sub get_reservable_slots {
11526:     my ($cnum,$cdom,$uname,$udom) = @_;
11527:     my $now = time;
11528:     my $reservable_info;
11529:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11530:     if (exists($remembered{$key})) {
11531:         $reservable_info = $remembered{$key};
11532:     } else {
11533:         my %resv;
11534:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11535:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11536:         $reservable_info = \%resv;
11537:         $remembered{$key} = $reservable_info;
11538:     }
11539:     return $reservable_info;
11540: }
11541: 
11542: sub get_course_slots {
11543:     my ($cnum,$cdom) = @_;
11544:     my $hashid=$cnum.':'.$cdom;
11545:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11546:     if (defined($cached)) {
11547:         if (ref($result) eq 'HASH') {
11548:             return %{$result};
11549:         }
11550:     } else {
11551:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11552:         my ($tmp) = keys(%slots);
11553:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11554:             &do_cache_new('allslots',$hashid,\%slots,600);
11555:             return %slots;
11556:         }
11557:     }
11558:     return;
11559: }
11560: 
11561: sub devalidate_slots_cache {
11562:     my ($cnum,$cdom)=@_;
11563:     my $hashid=$cnum.':'.$cdom;
11564:     &devalidate_cache_new('allslots',$hashid);
11565: }
11566: 
11567: sub get_coursechange {
11568:     my ($cdom,$cnum) = @_;
11569:     if ($cdom eq '' || $cnum eq '') {
11570:         return unless ($env{'request.course.id'});
11571:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11572:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11573:     }
11574:     my $hashid=$cdom.'_'.$cnum;
11575:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
11576:     if ((defined($cached)) && ($change ne '')) {
11577:         return $change;
11578:     } else {
11579:         my %crshash;
11580:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11581:         if ($crshash{'internal.contentchange'} eq '') {
11582:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11583:             if ($change eq '') {
11584:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11585:                 $change = $crshash{'internal.created'};
11586:             }
11587:         } else {
11588:             $change = $crshash{'internal.contentchange'};
11589:         }
11590:         my $cachetime = 600;
11591:         &do_cache_new('crschange',$hashid,$change,$cachetime);
11592:     }
11593:     return $change;
11594: }
11595: 
11596: sub devalidate_coursechange_cache {
11597:     my ($cnum,$cdom)=@_;
11598:     my $hashid=$cnum.':'.$cdom;
11599:     &devalidate_cache_new('crschange',$hashid);
11600: }
11601: 
11602: # ------------------------------------------------- Update symbolic store links
11603: 
11604: sub symblist {
11605:     my ($mapname,%newhash)=@_;
11606:     $mapname=&deversion(&declutter($mapname));
11607:     my %hash;
11608:     if (($env{'request.course.fn'}) && (%newhash)) {
11609:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11610:                       &GDBM_WRCREAT(),0640)) {
11611: 	    foreach my $url (keys(%newhash)) {
11612: 		next if ($url eq 'last_known'
11613: 			 && $env{'form.no_update_last_known'});
11614: 		$hash{declutter($url)}=&encode_symb($mapname,
11615: 						    $newhash{$url}->[1],
11616: 						    $newhash{$url}->[0]);
11617:             }
11618:             if (untie(%hash)) {
11619: 		return 'ok';
11620:             }
11621:         }
11622:     }
11623:     return 'error';
11624: }
11625: 
11626: # --------------------------------------------------------------- Verify a symb
11627: 
11628: sub symbverify {
11629:     my ($symb,$thisurl,$encstate)=@_;
11630:     my $thisfn=$thisurl;
11631:     $thisfn=&declutter($thisfn);
11632: # direct jump to resource in page or to a sequence - will construct own symbs
11633:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11634: # check URL part
11635:     my ($map,$resid,$url)=&decode_symb($symb);
11636: 
11637:     unless ($url eq $thisfn) { return 0; }
11638: 
11639:     $symb=&symbclean($symb);
11640:     $thisurl=&deversion($thisurl);
11641:     $thisfn=&deversion($thisfn);
11642: 
11643:     my %bighash;
11644:     my $okay=0;
11645: 
11646:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11647:                             &GDBM_READER(),0640)) {
11648:         my $noclutter;
11649:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11650:             $thisurl =~ s/\?.+$//;
11651:             if ($map =~ m{^uploaded/.+\.page$}) {
11652:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11653:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
11654:                 $noclutter = 1;
11655:             }
11656:         }
11657:         my $ids;
11658:         if ($noclutter) {
11659:             $ids=$bighash{'ids_'.$thisurl};
11660:         } else {
11661:             $ids=$bighash{'ids_'.&clutter($thisurl)};
11662:         }
11663:         unless ($ids) {
11664:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
11665:             $ids=$bighash{$idkey};
11666:         }
11667:         if ($ids) {
11668: # ------------------------------------------------------------------- Has ID(s)
11669:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11670:                 $symb =~ s/\?.+$//;
11671:             }
11672: 	    foreach my $id (split(/\,/,$ids)) {
11673: 	       my ($mapid,$resid)=split(/\./,$id);
11674:                if (
11675:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
11676:    eq $symb) {
11677:                    if (ref($encstate)) {
11678:                        $$encstate = $bighash{'encrypted_'.$id};
11679:                    }
11680:                    if (($env{'request.role.adv'}) ||
11681:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11682:                        ($thisurl eq '/adm/navmaps')) {
11683:                        $okay=1;
11684:                        last;
11685:                    }
11686:                }
11687:            }
11688:         }
11689: 	untie(%bighash);
11690:     }
11691:     return $okay;
11692: }
11693: 
11694: # --------------------------------------------------------------- Clean-up symb
11695: 
11696: sub symbclean {
11697:     my $symb=shift;
11698:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11699: # remove version from map
11700:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
11701: 
11702: # remove version from URL
11703:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
11704: 
11705: # remove wrapper
11706: 
11707:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
11708:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
11709:     return $symb;
11710: }
11711: 
11712: # ---------------------------------------------- Split symb to find map and url
11713: 
11714: sub encode_symb {
11715:     my ($map,$resid,$url)=@_;
11716:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11717: }
11718: 
11719: sub decode_symb {
11720:     my $symb=shift;
11721:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11722:     my ($map,$resid,$url)=split(/___/,$symb);
11723:     return (&fixversion($map),$resid,&fixversion($url));
11724: }
11725: 
11726: sub fixversion {
11727:     my $fn=shift;
11728:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
11729:     my %bighash;
11730:     my $uri=&clutter($fn);
11731:     my $key=$env{'request.course.id'}.'_'.$uri;
11732: # is this cached?
11733:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
11734:     if (defined($cached)) { return $result; }
11735: # unfortunately not cached, or expired
11736:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11737: 	    &GDBM_READER(),0640)) {
11738:  	if ($bighash{'version_'.$uri}) {
11739:  	    my $version=$bighash{'version_'.$uri};
11740:  	    unless (($version eq 'mostrecent') || 
11741: 		    ($version==&getversion($uri))) {
11742:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
11743:  	    }
11744:  	}
11745:  	untie %bighash;
11746:     }
11747:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
11748: }
11749: 
11750: sub deversion {
11751:     my $url=shift;
11752:     $url=~s/\.\d+\.(\w+)$/\.$1/;
11753:     return $url;
11754: }
11755: 
11756: # ------------------------------------------------------ Return symb list entry
11757: 
11758: sub symbread {
11759:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
11760:     my $cache_str='request.symbread.cached.'.$thisfn;
11761:     if (defined($env{$cache_str})) {
11762:         if ($ignorecachednull) {
11763:             return $env{$cache_str} unless ($env{$cache_str} eq '');
11764:         } else {
11765:             return $env{$cache_str};
11766:         }
11767:     }
11768: # no filename provided? try from environment
11769:     unless ($thisfn) {
11770:         if ($env{'request.symb'}) {
11771:             return $env{$cache_str}=&symbclean($env{'request.symb'});
11772:         }
11773:         $thisfn=$env{'request.filename'};
11774:     }
11775:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11776: # is that filename actually a symb? Verify, clean, and return
11777:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
11778: 	if (&symbverify($thisfn,$1)) {
11779: 	    return $env{$cache_str}=&symbclean($thisfn);
11780: 	}
11781:     }
11782:     $thisfn=declutter($thisfn);
11783:     my %hash;
11784:     my %bighash;
11785:     my $syval='';
11786:     if (($env{'request.course.fn'}) && ($thisfn)) {
11787:         my $targetfn = $thisfn;
11788:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
11789:             $targetfn = 'adm/wrapper/'.$thisfn;
11790:         }
11791: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11792: 	    $targetfn=$1;
11793: 	}
11794:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11795:                       &GDBM_READER(),0640)) {
11796: 	    $syval=$hash{$targetfn};
11797:             untie(%hash);
11798:         }
11799: # ---------------------------------------------------------- There was an entry
11800:         if ($syval) {
11801: 	    #unless ($syval=~/\_\d+$/) {
11802: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
11803: 		    #&appenv({'request.ambiguous' => $thisfn});
11804: 		    #return $env{$cache_str}='';
11805: 		#}    
11806: 		#$syval.=$1;
11807: 	    #}
11808:         } else {
11809: # ------------------------------------------------------- Was not in symb table
11810:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11811:                             &GDBM_READER(),0640)) {
11812: # ---------------------------------------------- Get ID(s) for current resource
11813:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
11814:               unless ($ids) { 
11815:                  $ids=$bighash{'ids_/'.$thisfn};
11816:               }
11817:               unless ($ids) {
11818: # alias?
11819: 		  $ids=$bighash{'mapalias_'.$thisfn};
11820:               }
11821:               if ($ids) {
11822: # ------------------------------------------------------------------- Has ID(s)
11823:                  my @possibilities=split(/\,/,$ids);
11824:                  if ($#possibilities==0) {
11825: # ----------------------------------------------- There is only one possibility
11826: 		     my ($mapid,$resid)=split(/\./,$ids);
11827: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
11828: 						    $resid,$thisfn);
11829:                      if (ref($possibles) eq 'HASH') {
11830:                          $possibles->{$syval} = 1;
11831:                      }
11832:                      if ($checkforblock) {
11833:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11834:                          if (@blockers) {
11835:                              $syval = '';
11836:                              return;
11837:                          }
11838:                      }
11839:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11840: # ------------------------------------------ There is more than one possibility
11841:                      my $realpossible=0;
11842:                      foreach my $id (@possibilities) {
11843: 			 my $file=$bighash{'src_'.$id};
11844:                          my $canaccess;
11845:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11846:                              $canaccess = 1;
11847:                          } else {
11848:                              $canaccess = &allowed('bre',$file);
11849:                          }
11850:                          if ($canaccess) {
11851:          		     my ($mapid,$resid)=split(/\./,$id);
11852:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
11853:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11854:                                                              $resid,$thisfn);
11855:                                  if (ref($possibles) eq 'HASH') {
11856:                                      $possibles->{$syval} = 1;
11857:                                  }
11858:                                  if ($checkforblock) {
11859:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11860:                                      unless (@blockers > 0) {
11861:                                          $syval = $poss_syval;
11862:                                          $realpossible++;
11863:                                      }
11864:                                  } else {
11865:                                      $syval = $poss_syval;
11866:                                      $realpossible++;
11867:                                  }
11868:                              }
11869: 			 }
11870:                      }
11871: 		     if ($realpossible!=1) { $syval=''; }
11872:                  } else {
11873:                      $syval='';
11874:                  }
11875: 	      }
11876:               untie(%bighash);
11877:            }
11878:         }
11879:         if ($syval) {
11880: 	    return $env{$cache_str}=$syval;
11881:         }
11882:     }
11883:     &appenv({'request.ambiguous' => $thisfn});
11884:     return $env{$cache_str}='';
11885: }
11886: 
11887: # ---------------------------------------------------------- Return random seed
11888: 
11889: sub numval {
11890:     my $txt=shift;
11891:     $txt=~tr/A-J/0-9/;
11892:     $txt=~tr/a-j/0-9/;
11893:     $txt=~tr/K-T/0-9/;
11894:     $txt=~tr/k-t/0-9/;
11895:     $txt=~tr/U-Z/0-5/;
11896:     $txt=~tr/u-z/0-5/;
11897:     $txt=~s/\D//g;
11898:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
11899:     return int($txt);
11900: }
11901: 
11902: sub numval2 {
11903:     my $txt=shift;
11904:     $txt=~tr/A-J/0-9/;
11905:     $txt=~tr/a-j/0-9/;
11906:     $txt=~tr/K-T/0-9/;
11907:     $txt=~tr/k-t/0-9/;
11908:     $txt=~tr/U-Z/0-5/;
11909:     $txt=~tr/u-z/0-5/;
11910:     $txt=~s/\D//g;
11911:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11912:     my $total;
11913:     foreach my $val (@txts) { $total+=$val; }
11914:     if ($_64bit) { if ($total > 2**32) { return -1; } }
11915:     return int($total);
11916: }
11917: 
11918: sub numval3 {
11919:     use integer;
11920:     my $txt=shift;
11921:     $txt=~tr/A-J/0-9/;
11922:     $txt=~tr/a-j/0-9/;
11923:     $txt=~tr/K-T/0-9/;
11924:     $txt=~tr/k-t/0-9/;
11925:     $txt=~tr/U-Z/0-5/;
11926:     $txt=~tr/u-z/0-5/;
11927:     $txt=~s/\D//g;
11928:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11929:     my $total;
11930:     foreach my $val (@txts) { $total+=$val; }
11931:     if ($_64bit) { $total=(($total<<32)>>32); }
11932:     return $total;
11933: }
11934: 
11935: sub digest {
11936:     my ($data)=@_;
11937:     my $digest=&Digest::MD5::md5($data);
11938:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
11939:     my ($e,$f);
11940:     {
11941:         use integer;
11942:         $e=($a+$b);
11943:         $f=($c+$d);
11944:         if ($_64bit) {
11945:             $e=(($e<<32)>>32);
11946:             $f=(($f<<32)>>32);
11947:         }
11948:     }
11949:     if (wantarray) {
11950: 	return ($e,$f);
11951:     } else {
11952: 	my $g;
11953: 	{
11954: 	    use integer;
11955: 	    $g=($e+$f);
11956: 	    if ($_64bit) {
11957: 		$g=(($g<<32)>>32);
11958: 	    }
11959: 	}
11960: 	return $g;
11961:     }
11962: }
11963: 
11964: sub latest_rnd_algorithm_id {
11965:     return '64bit5';
11966: }
11967: 
11968: sub get_rand_alg {
11969:     my ($courseid)=@_;
11970:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11971:     if ($courseid) {
11972: 	return $env{"course.$courseid.rndseed"};
11973:     }
11974:     return &latest_rnd_algorithm_id();
11975: }
11976: 
11977: sub validCODE {
11978:     my ($CODE)=@_;
11979:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11980:     return 0;
11981: }
11982: 
11983: sub getCODE {
11984:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11985:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11986: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11987: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11988: 	return $Apache::lonhomework::history{'resource.CODE'};
11989:     }
11990:     return undef;
11991: }
11992: #
11993: #  Determines the random seed for a specific context:
11994: #
11995: # parameters:
11996: #   symb      - in course context the symb for the seed.
11997: #   course_id - The course id of the form domain_coursenum.
11998: #   domain    - Domain for the user.
11999: #   course    - Course for the user.
12000: #   cenv      - environment of the course.
12001: #
12002: # NOTE:
12003: #   All parameters are picked out of the environment if missing
12004: #   or not defined.
12005: #   If a symb cannot be determined the current time is used instead.
12006: #
12007: #  For a given well defined symb, courside, domain, username,
12008: #  and course environment, the seed is reproducible.
12009: #
12010: sub rndseed {
12011:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12012:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12013:     if (!defined($symb)) {
12014: 	unless ($symb=$wsymb) { return time; }
12015:     }
12016:     if (!defined $courseid) { 
12017: 	$courseid=$wcourseid; 
12018:     }
12019:     if (!defined $domain) { $domain=$wdomain; }
12020:     if (!defined $username) { $username=$wusername }
12021: 
12022:     my $which;
12023:     if (defined($cenv->{'rndseed'})) {
12024: 	$which = $cenv->{'rndseed'};
12025:     } else {
12026: 	$which =&get_rand_alg($courseid);
12027:     }
12028:     if (defined(&getCODE())) {
12029: 	if ($which eq '64bit5') {
12030: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12031: 	} elsif ($which eq '64bit4') {
12032: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12033: 	} else {
12034: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12035: 	}
12036:     } elsif ($which eq '64bit5') {
12037: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12038:     } elsif ($which eq '64bit4') {
12039: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12040:     } elsif ($which eq '64bit3') {
12041: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12042:     } elsif ($which eq '64bit2') {
12043: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12044:     } elsif ($which eq '64bit') {
12045: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12046:     }
12047:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12048: }
12049: 
12050: sub rndseed_32bit {
12051:     my ($symb,$courseid,$domain,$username)=@_;
12052:     {
12053: 	use integer;
12054: 	my $symbchck=unpack("%32C*",$symb) << 27;
12055: 	my $symbseed=numval($symb) << 22;
12056: 	my $namechck=unpack("%32C*",$username) << 17;
12057: 	my $nameseed=numval($username) << 12;
12058: 	my $domainseed=unpack("%32C*",$domain) << 7;
12059: 	my $courseseed=unpack("%32C*",$courseid);
12060: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12061: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12062: 	#&logthis("rndseed :$num:$symb");
12063: 	if ($_64bit) { $num=(($num<<32)>>32); }
12064: 	return $num;
12065:     }
12066: }
12067: 
12068: sub rndseed_64bit {
12069:     my ($symb,$courseid,$domain,$username)=@_;
12070:     {
12071: 	use integer;
12072: 	my $symbchck=unpack("%32S*",$symb) << 21;
12073: 	my $symbseed=numval($symb) << 10;
12074: 	my $namechck=unpack("%32S*",$username);
12075: 	
12076: 	my $nameseed=numval($username) << 21;
12077: 	my $domainseed=unpack("%32S*",$domain) << 10;
12078: 	my $courseseed=unpack("%32S*",$courseid);
12079: 	
12080: 	my $num1=$symbchck+$symbseed+$namechck;
12081: 	my $num2=$nameseed+$domainseed+$courseseed;
12082: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12083: 	#&logthis("rndseed :$num:$symb");
12084: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12085: 	return "$num1,$num2";
12086:     }
12087: }
12088: 
12089: sub rndseed_64bit2 {
12090:     my ($symb,$courseid,$domain,$username)=@_;
12091:     {
12092: 	use integer;
12093: 	# strings need to be an even # of cahracters long, it it is odd the
12094:         # last characters gets thrown away
12095: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12096: 	my $symbseed=numval($symb) << 10;
12097: 	my $namechck=unpack("%32S*",$username.' ');
12098: 	
12099: 	my $nameseed=numval($username) << 21;
12100: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12101: 	my $courseseed=unpack("%32S*",$courseid.' ');
12102: 	
12103: 	my $num1=$symbchck+$symbseed+$namechck;
12104: 	my $num2=$nameseed+$domainseed+$courseseed;
12105: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12106: 	#&logthis("rndseed :$num:$symb");
12107: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12108: 	return "$num1,$num2";
12109:     }
12110: }
12111: 
12112: sub rndseed_64bit3 {
12113:     my ($symb,$courseid,$domain,$username)=@_;
12114:     {
12115: 	use integer;
12116: 	# strings need to be an even # of cahracters long, it it is odd the
12117:         # last characters gets thrown away
12118: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12119: 	my $symbseed=numval2($symb) << 10;
12120: 	my $namechck=unpack("%32S*",$username.' ');
12121: 	
12122: 	my $nameseed=numval2($username) << 21;
12123: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12124: 	my $courseseed=unpack("%32S*",$courseid.' ');
12125: 	
12126: 	my $num1=$symbchck+$symbseed+$namechck;
12127: 	my $num2=$nameseed+$domainseed+$courseseed;
12128: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12129: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12130: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12131: 	
12132: 	return "$num1:$num2";
12133:     }
12134: }
12135: 
12136: sub rndseed_64bit4 {
12137:     my ($symb,$courseid,$domain,$username)=@_;
12138:     {
12139: 	use integer;
12140: 	# strings need to be an even # of cahracters long, it it is odd the
12141:         # last characters gets thrown away
12142: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12143: 	my $symbseed=numval3($symb) << 10;
12144: 	my $namechck=unpack("%32S*",$username.' ');
12145: 	
12146: 	my $nameseed=numval3($username) << 21;
12147: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12148: 	my $courseseed=unpack("%32S*",$courseid.' ');
12149: 	
12150: 	my $num1=$symbchck+$symbseed+$namechck;
12151: 	my $num2=$nameseed+$domainseed+$courseseed;
12152: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12153: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12154: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12155: 	
12156: 	return "$num1:$num2";
12157:     }
12158: }
12159: 
12160: sub rndseed_64bit5 {
12161:     my ($symb,$courseid,$domain,$username)=@_;
12162:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12163:     return "$num1:$num2";
12164: }
12165: 
12166: sub rndseed_CODE_64bit {
12167:     my ($symb,$courseid,$domain,$username)=@_;
12168:     {
12169: 	use integer;
12170: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12171: 	my $symbseed=numval2($symb);
12172: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12173: 	my $CODEseed=numval(&getCODE());
12174: 	my $courseseed=unpack("%32S*",$courseid.' ');
12175: 	my $num1=$symbseed+$CODEchck;
12176: 	my $num2=$CODEseed+$courseseed+$symbchck;
12177: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12178: 	#&logthis("rndseed :$num1:$num2:$symb");
12179: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12180: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12181: 	return "$num1:$num2";
12182:     }
12183: }
12184: 
12185: sub rndseed_CODE_64bit4 {
12186:     my ($symb,$courseid,$domain,$username)=@_;
12187:     {
12188: 	use integer;
12189: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12190: 	my $symbseed=numval3($symb);
12191: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12192: 	my $CODEseed=numval3(&getCODE());
12193: 	my $courseseed=unpack("%32S*",$courseid.' ');
12194: 	my $num1=$symbseed+$CODEchck;
12195: 	my $num2=$CODEseed+$courseseed+$symbchck;
12196: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12197: 	#&logthis("rndseed :$num1:$num2:$symb");
12198: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12199: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12200: 	return "$num1:$num2";
12201:     }
12202: }
12203: 
12204: sub rndseed_CODE_64bit5 {
12205:     my ($symb,$courseid,$domain,$username)=@_;
12206:     my $code = &getCODE();
12207:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
12208:     return "$num1:$num2";
12209: }
12210: 
12211: sub setup_random_from_rndseed {
12212:     my ($rndseed)=@_;
12213:     if ($rndseed =~/([,:])/) {
12214: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12215:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12216:             &Math::Random::random_set_seed_from_phrase($rndseed);
12217:         } else {
12218:             &Math::Random::random_set_seed($num1,$num2);
12219:         }
12220:     } else {
12221: 	&Math::Random::random_set_seed_from_phrase($rndseed);
12222:     }
12223: }
12224: 
12225: sub latest_receipt_algorithm_id {
12226:     return 'receipt3';
12227: }
12228: 
12229: sub recunique {
12230:     my $fucourseid=shift;
12231:     my $unique;
12232:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12233: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12234: 	$unique=$env{"course.$fucourseid.internal.encseed"};
12235:     } else {
12236: 	$unique=$perlvar{'lonReceipt'};
12237:     }
12238:     return unpack("%32C*",$unique);
12239: }
12240: 
12241: sub recprefix {
12242:     my $fucourseid=shift;
12243:     my $prefix;
12244:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12245: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12246: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
12247:     } else {
12248: 	$prefix=$perlvar{'lonHostID'};
12249:     }
12250:     return unpack("%32C*",$prefix);
12251: }
12252: 
12253: sub ireceipt {
12254:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
12255: 
12256:     my $return =&recprefix($fucourseid).'-';
12257: 
12258:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12259: 	$env{'request.state'} eq 'construct') {
12260: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12261: 	return $return;
12262:     }
12263: 
12264:     my $cuname=unpack("%32C*",$funame);
12265:     my $cudom=unpack("%32C*",$fudom);
12266:     my $cucourseid=unpack("%32C*",$fucourseid);
12267:     my $cusymb=unpack("%32C*",$fusymb);
12268:     my $cunique=&recunique($fucourseid);
12269:     my $cpart=unpack("%32S*",$part);
12270:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12271: 
12272: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
12273: 			       
12274: 	$return.= ($cunique%$cuname+
12275: 		   $cunique%$cudom+
12276: 		   $cusymb%$cuname+
12277: 		   $cusymb%$cudom+
12278: 		   $cucourseid%$cuname+
12279: 		   $cucourseid%$cudom+
12280: 		   $cpart%$cuname+
12281: 		   $cpart%$cudom);
12282:     } else {
12283: 	$return.= ($cunique%$cuname+
12284: 		   $cunique%$cudom+
12285: 		   $cusymb%$cuname+
12286: 		   $cusymb%$cudom+
12287: 		   $cucourseid%$cuname+
12288: 		   $cucourseid%$cudom);
12289:     }
12290:     return $return;
12291: }
12292: 
12293: sub receipt {
12294:     my ($part)=@_;
12295:     my ($symb,$courseid,$domain,$name) = &whichuser();
12296:     return &ireceipt($name,$domain,$courseid,$symb,$part);
12297: }
12298: 
12299: sub whichuser {
12300:     my ($passedsymb)=@_;
12301:     my ($symb,$courseid,$domain,$name,$publicuser);
12302:     if (defined($env{'form.grade_symb'})) {
12303: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12304: 	my $allowed=&allowed('vgr',$tmp_courseid);
12305: 	if (!$allowed &&
12306: 	    exists($env{'request.course.sec'}) &&
12307: 	    $env{'request.course.sec'} !~ /^\s*$/) {
12308: 	    $allowed=&allowed('vgr',$tmp_courseid.
12309: 			      '/'.$env{'request.course.sec'});
12310: 	}
12311: 	if ($allowed) {
12312: 	    ($symb)=&get_env_multiple('form.grade_symb');
12313: 	    $courseid=$tmp_courseid;
12314: 	    ($domain)=&get_env_multiple('form.grade_domain');
12315: 	    ($name)=&get_env_multiple('form.grade_username');
12316: 	    return ($symb,$courseid,$domain,$name,$publicuser);
12317: 	}
12318:     }
12319:     if (!$passedsymb) {
12320: 	$symb=&symbread();
12321:     } else {
12322: 	$symb=$passedsymb;
12323:     }
12324:     $courseid=$env{'request.course.id'};
12325:     $domain=$env{'user.domain'};
12326:     $name=$env{'user.name'};
12327:     if ($name eq 'public' && $domain eq 'public') {
12328: 	if (!defined($env{'form.username'})) {
12329: 	    $env{'form.username'}.=time.rand(10000000);
12330: 	}
12331: 	$name.=$env{'form.username'};
12332:     }
12333:     return ($symb,$courseid,$domain,$name,$publicuser);
12334: 
12335: }
12336: 
12337: # ------------------------------------------------------------ Serves up a file
12338: # returns either the contents of the file or 
12339: # -1 if the file doesn't exist
12340: #
12341: # if the target is a file that was uploaded via DOCS, 
12342: # a check will be made to see if a current copy exists on the local server,
12343: # if it does this will be served, otherwise a copy will be retrieved from
12344: # the home server for the course and stored in /home/httpd/html/userfiles on
12345: # the local server.   
12346: 
12347: sub getfile {
12348:     my ($file) = @_;
12349:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
12350:     &repcopy($file);
12351:     return &readfile($file);
12352: }
12353: 
12354: sub repcopy_userfile {
12355:     my ($file)=@_;
12356:     my $londocroot = $perlvar{'lonDocRoot'};
12357:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
12358:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
12359:     my ($cdom,$cnum,$filename) = 
12360: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
12361:     my $uri="/uploaded/$cdom/$cnum/$filename";
12362:     if (-e "$file") {
12363: # we already have a local copy, check it out
12364: 	my @fileinfo = stat($file);
12365: 	my $rtncode;
12366: 	my $info;
12367: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
12368: 	if ($lwpresp ne 'ok') {
12369: # there is no such file anymore, even though we had a local copy
12370: 	    if ($rtncode eq '404') {
12371: 		unlink($file);
12372: 	    }
12373: 	    return -1;
12374: 	}
12375: 	if ($info < $fileinfo[9]) {
12376: # nice, the file we have is up-to-date, just say okay
12377: 	    return 'ok';
12378: 	} else {
12379: # the file is outdated, get rid of it
12380: 	    unlink($file);
12381: 	}
12382:     }
12383: # one way or the other, at this point, we don't have the file
12384: # construct the correct path for the file
12385:     my @parts = ($cdom,$cnum); 
12386:     if ($filename =~ m|^(.+)/[^/]+$|) {
12387: 	push @parts, split(/\//,$1);
12388:     }
12389:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12390:     foreach my $part (@parts) {
12391: 	$path .= '/'.$part;
12392: 	if (!-e $path) {
12393: 	    mkdir($path,0770);
12394: 	}
12395:     }
12396: # now the path exists for sure
12397: # get a user agent
12398:     my $ua=new LWP::UserAgent;
12399:     my $transferfile=$file.'.in.transfer';
12400: # FIXME: this should flock
12401:     if (-e $transferfile) { return 'ok'; }
12402:     my $request;
12403:     $uri=~s/^\///;
12404:     my $homeserver = &homeserver($cnum,$cdom);
12405:     my $protocol = $protocol{$homeserver};
12406:     $protocol = 'http' if ($protocol ne 'https');
12407:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
12408:     my $response=$ua->request($request,$transferfile);
12409: # did it work?
12410:     if ($response->is_error()) {
12411: 	unlink($transferfile);
12412: 	&logthis("Userfile repcopy failed for $uri");
12413: 	return -1;
12414:     }
12415: # worked, rename the transfer file
12416:     rename($transferfile,$file);
12417:     return 'ok';
12418: }
12419: 
12420: sub tokenwrapper {
12421:     my $uri=shift;
12422:     $uri=~s|^https?\://([^/]+)||;
12423:     $uri=~s|^/||;
12424:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
12425:     my $token=$1;
12426:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
12427:     if ($udom && $uname && $file) {
12428: 	$file=~s|(\?\.*)*$||;
12429:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
12430:         my $homeserver = &homeserver($uname,$udom);
12431:         my $protocol = $protocol{$homeserver};
12432:         $protocol = 'http' if ($protocol ne 'https');
12433:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
12434:                (($uri=~/\?/)?'&':'?').'token='.$token.
12435:                                '&tokenissued='.$perlvar{'lonHostID'};
12436:     } else {
12437:         return '/adm/notfound.html';
12438:     }
12439: }
12440: 
12441: # call with reqtype HEAD: get last modification time
12442: # call with reqtype GET: get the file contents
12443: # Do not call this with reqtype GET for large files! It loads everything into memory
12444: #
12445: sub getuploaded {
12446:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12447:     $uri=~s/^\///;
12448:     my $homeserver = &homeserver($cnum,$cdom);
12449:     my $protocol = $protocol{$homeserver};
12450:     $protocol = 'http' if ($protocol ne 'https');
12451:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
12452:     my $ua=new LWP::UserAgent;
12453:     my $request=new HTTP::Request($reqtype,$uri);
12454:     my $response=$ua->request($request);
12455:     $$rtncode = $response->code;
12456:     if (! $response->is_success()) {
12457: 	return 'failed';
12458:     }      
12459:     if ($reqtype eq 'HEAD') {
12460: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
12461:     } elsif ($reqtype eq 'GET') {
12462: 	$$info = $response->content;
12463:     }
12464:     return 'ok';
12465: }
12466: 
12467: sub readfile {
12468:     my $file = shift;
12469:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
12470:     my $fh;
12471:     open($fh,"<",$file);
12472:     my $a='';
12473:     while (my $line = <$fh>) { $a .= $line; }
12474:     return $a;
12475: }
12476: 
12477: sub filelocation {
12478:     my ($dir,$file) = @_;
12479:     my $location;
12480:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
12481: 
12482:     if ($file =~ m-^/adm/-) {
12483: 	$file=~s-^/adm/wrapper/-/-;
12484: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
12485:     }
12486: 
12487:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
12488:         $location = $file;
12489:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
12490:         my ($udom,$uname,$filename)=
12491:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
12492:         my $home=&homeserver($uname,$udom);
12493:         my $is_me=0;
12494:         my @ids=&current_machine_ids();
12495:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12496:         if ($is_me) {
12497:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
12498:         } else {
12499:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12500:   	      $udom.'/'.$uname.'/'.$filename;
12501:         }
12502:     } elsif ($file =~ m-^/adm/-) {
12503: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
12504:     } else {
12505:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
12506:         $file=~s:^/(res|priv)/:/:;
12507:         my $space=$1;
12508:         if ( !( $file =~ m:^/:) ) {
12509:             $location = $dir. '/'.$file;
12510:         } else {
12511:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
12512:         }
12513:     }
12514:     $location=~s://+:/:g; # remove duplicate /
12515:     while ($location=~m{/\.\./}) {
12516: 	if ($location =~ m{/[^/]+/\.\./}) {
12517: 	    $location=~ s{/[^/]+/\.\./}{/}g;
12518: 	} else {
12519: 	    $location=~ s{/\.\./}{/}g;
12520: 	}
12521:     } #remove dir/..
12522:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12523:     return $location;
12524: }
12525: 
12526: sub hreflocation {
12527:     my ($dir,$file)=@_;
12528:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
12529: 	$file=filelocation($dir,$file);
12530:     } elsif ($file=~m-^/adm/-) {
12531: 	$file=~s-^/adm/wrapper/-/-;
12532: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
12533:     }
12534:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12535: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12536:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
12537: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12538: 	        {/uploaded/$1/$2/}x;
12539:     }
12540:     if ($file=~ m{^/userfiles/}) {
12541: 	$file =~ s{^/userfiles/}{/uploaded/};
12542:     }
12543:     return $file;
12544: }
12545: 
12546: 
12547: 
12548: 
12549: 
12550: sub current_machine_domains {
12551:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
12552: }
12553: 
12554: sub machine_domains {
12555:     my ($hostname) = @_;
12556:     my @domains;
12557:     my %hostname = &all_hostnames();
12558:     while( my($id, $name) = each(%hostname)) {
12559: #	&logthis("-$id-$name-$hostname-");
12560: 	if ($hostname eq $name) {
12561: 	    push(@domains,&host_domain($id));
12562: 	}
12563:     }
12564:     return @domains;
12565: }
12566: 
12567: sub current_machine_ids {
12568:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
12569: }
12570: 
12571: sub machine_ids {
12572:     my ($hostname) = @_;
12573:     $hostname ||= &hostname($perlvar{'lonHostID'});
12574:     my @ids;
12575:     my %name_to_host = &all_names();
12576:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12577: 	return @{ $name_to_host{$hostname} };
12578:     }
12579:     return;
12580: }
12581: 
12582: sub additional_machine_domains {
12583:     my @domains;
12584:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
12585:     while( my $line = <$fh>) {
12586:         $line =~ s/\s//g;
12587:         push(@domains,$line);
12588:     }
12589:     return @domains;
12590: }
12591: 
12592: sub default_login_domain {
12593:     my $domain = $perlvar{'lonDefDomain'};
12594:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12595:     foreach my $posdom (&current_machine_domains(),
12596:                         &additional_machine_domains()) {
12597:         if (lc($posdom) eq lc($testdomain)) {
12598:             $domain=$posdom;
12599:             last;
12600:         }
12601:     }
12602:     return $domain;
12603: }
12604: 
12605: # ------------------------------------------------------------- Declutters URLs
12606: 
12607: sub declutter {
12608:     my $thisfn=shift;
12609:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12610:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12611:         $thisfn=~s{^/home/httpd/html}{};
12612:     }
12613:     $thisfn=~s/^\///;
12614:     $thisfn=~s|^adm/wrapper/||;
12615:     $thisfn=~s|^adm/coursedocs/showdoc/||;
12616:     $thisfn=~s/^res\///;
12617:     $thisfn=~s/^priv\///;
12618:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12619:         $thisfn=~s/\?.+$//;
12620:     }
12621:     return $thisfn;
12622: }
12623: 
12624: # ------------------------------------------------------------- Clutter up URLs
12625: 
12626: sub clutter {
12627:     my $thisfn='/'.&declutter(shift);
12628:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
12629: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
12630:        $thisfn='/res'.$thisfn; 
12631:     }
12632:     if ($thisfn !~m|^/adm|) {
12633: 	if ($thisfn =~ m|^/ext/|) {
12634: 	    $thisfn='/adm/wrapper'.$thisfn;
12635: 	} else {
12636: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
12637: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
12638: 	    if ($embstyle eq 'ssi'
12639: 		|| ($embstyle eq 'hdn')
12640: 		|| ($embstyle eq 'rat')
12641: 		|| ($embstyle eq 'prv')
12642: 		|| ($embstyle eq 'ign')) {
12643: 		#do nothing with these
12644: 	    } elsif (($embstyle eq 'img') 
12645: 		|| ($embstyle eq 'emb')
12646: 		|| ($embstyle eq 'wrp')) {
12647: 		$thisfn='/adm/wrapper'.$thisfn;
12648: 	    } elsif ($embstyle eq 'unk'
12649: 		     && $thisfn!~/\.(sequence|page)$/) {
12650: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
12651: 	    } else {
12652: #		&logthis("Got a blank emb style");
12653: 	    }
12654: 	}
12655:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
12656:         $thisfn='/adm/wrapper'.$thisfn;
12657:     }
12658:     return $thisfn;
12659: }
12660: 
12661: sub clutter_with_no_wrapper {
12662:     my $uri = &clutter(shift);
12663:     if ($uri =~ m-^/adm/-) {
12664: 	$uri =~ s-^/adm/wrapper/-/-;
12665: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
12666:     }
12667:     return $uri;
12668: }
12669: 
12670: sub freeze_escape {
12671:     my ($value)=@_;
12672:     if (ref($value)) {
12673: 	$value=&nfreeze($value);
12674: 	return '__FROZEN__'.&escape($value);
12675:     }
12676:     return &escape($value);
12677: }
12678: 
12679: 
12680: sub thaw_unescape {
12681:     my ($value)=@_;
12682:     if ($value =~ /^__FROZEN__/) {
12683: 	substr($value,0,10,undef);
12684: 	$value=&unescape($value);
12685: 	return &thaw($value);
12686:     }
12687:     return &unescape($value);
12688: }
12689: 
12690: sub correct_line_ends {
12691:     my ($result)=@_;
12692:     $$result =~s/\r\n/\n/mg;
12693:     $$result =~s/\r/\n/mg;
12694: }
12695: # ================================================================ Main Program
12696: 
12697: sub goodbye {
12698:    &logthis("Starting Shut down");
12699: #not converted to using infrastruture and probably shouldn't be
12700:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
12701: #converted
12702: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
12703:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12704: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12705: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
12706: #1.1 only
12707: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12708: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12709: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12710: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12711:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
12712:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12713:    &logthis(sprintf("%-20s is %s",'hits',$hits));
12714:    &flushcourselogs();
12715:    &logthis("Shutting down");
12716: }
12717: 
12718: sub get_dns {
12719:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
12720:     if (!$ignore_cache) {
12721: 	my ($content,$cached)=
12722: 	    &Apache::lonnet::is_cached_new('dns',$url);
12723: 	if ($cached) {
12724: 	    &$func($content,$hashref);
12725: 	    return;
12726: 	}
12727:     }
12728: 
12729:     my %alldns;
12730:     open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
12731:     foreach my $dns (<$config>) {
12732: 	next if ($dns !~ /^\^(\S*)/x);
12733:         my $line = $1;
12734:         my ($host,$protocol) = split(/:/,$line);
12735:         if ($protocol ne 'https') {
12736:             $protocol = 'http';
12737:         }
12738: 	$alldns{$host} = $protocol;
12739:     }
12740:     while (%alldns) {
12741: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
12742: 	my $ua=new LWP::UserAgent;
12743:         $ua->timeout(30);
12744: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
12745: 	my $response=$ua->request($request);
12746:         delete($alldns{$dns});
12747: 	next if ($response->is_error());
12748: 	my @content = split("\n",$response->content);
12749:         unless ($nocache) {
12750: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
12751:         }
12752: 	&$func(\@content,$hashref);
12753: 	return;
12754:     }
12755:     close($config);
12756:     my $which = (split('/',$url))[3];
12757:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12758:     open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
12759:     my @content = <$config>;
12760:     &$func(\@content,$hashref);
12761:     return;
12762: }
12763: 
12764: # ------------------------------------------------------Get DNS checksums file
12765: sub parse_dns_checksums_tab {
12766:     my ($lines,$hashref) = @_;
12767:     my $lonhost = $perlvar{'lonHostID'};
12768:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
12769:     my $loncaparev = &get_server_loncaparev($machine_dom);
12770:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12771:     my $webconfdir = '/etc/httpd/conf';
12772:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12773:         $webconfdir = '/etc/apache2';
12774:     } elsif ($distro =~ /^sles(\d+)$/) {
12775:         if ($1 >= 10) {
12776:             $webconfdir = '/etc/apache2';
12777:         }
12778:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12779:         if ($1 >= 10.0) {
12780:             $webconfdir = '/etc/apache2';
12781:         }
12782:     }
12783:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12784:     my (%chksum,%revnum);
12785:     if (ref($lines) eq 'ARRAY') {
12786:         chomp(@{$lines});
12787:         my $version = shift(@{$lines});
12788:         if ($version eq $release) {
12789:             foreach my $line (@{$lines}) {
12790:                 my ($file,$version,$shasum) = split(/,/,$line);
12791:                 if ($file =~ m{^/etc/httpd/conf}) {
12792:                     if ($webconfdir eq '/etc/apache2') {
12793:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12794:                     }
12795:                 }
12796:                 $chksum{$file} = $shasum;
12797:                 $revnum{$file} = $version;
12798:             }
12799:             if (ref($hashref) eq 'HASH') {
12800:                 %{$hashref} = (
12801:                                 sums     => \%chksum,
12802:                                 versions => \%revnum,
12803:                               );
12804:             }
12805:         }
12806:     }
12807:     return;
12808: }
12809: 
12810: sub fetch_dns_checksums {
12811:     my %checksums;
12812:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
12813:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
12814:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12815:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
12816:              \%checksums);
12817:     return \%checksums;
12818: }
12819: 
12820: # ------------------------------------------------------------ Read domain file
12821: {
12822:     my $loaded;
12823:     my %domain;
12824: 
12825:     sub parse_domain_tab {
12826: 	my ($lines) = @_;
12827: 	foreach my $line (@$lines) {
12828: 	    next if ($line =~ /^(\#|\s*$ )/x);
12829: 
12830: 	    chomp($line);
12831: 	    my ($name,@elements) = split(/:/,$line,9);
12832: 	    my %this_domain;
12833: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
12834: 			       'lang_def', 'city', 'longi', 'lati',
12835: 			       'primary') {
12836: 		$this_domain{$field} = shift(@elements);
12837: 	    }
12838: 	    $domain{$name} = \%this_domain;
12839: 	}
12840:     }
12841: 
12842:     sub reset_domain_info {
12843: 	undef($loaded);
12844: 	undef(%domain);
12845:     }
12846: 
12847:     sub load_domain_tab {
12848: 	my ($ignore_cache,$nocache) = @_;
12849: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
12850: 	my $fh;
12851: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
12852: 	    my @lines = <$fh>;
12853: 	    &parse_domain_tab(\@lines);
12854: 	}
12855: 	close($fh);
12856: 	$loaded = 1;
12857:     }
12858: 
12859:     sub domain {
12860: 	&load_domain_tab() if (!$loaded);
12861: 
12862: 	my ($name,$what) = @_;
12863: 	return if ( !exists($domain{$name}) );
12864: 
12865: 	if (!$what) {
12866: 	    return $domain{$name}{'description'};
12867: 	}
12868: 	return $domain{$name}{$what};
12869:     }
12870: 
12871:     sub domain_info {
12872:         &load_domain_tab() if (!$loaded);
12873:         return %domain;
12874:     }
12875: 
12876: }
12877: 
12878: 
12879: # ------------------------------------------------------------- Read hosts file
12880: {
12881:     my %hostname;
12882:     my %hostdom;
12883:     my %libserv;
12884:     my $loaded;
12885:     my %name_to_host;
12886:     my %internetdom;
12887:     my %LC_dns_serv;
12888: 
12889:     sub parse_hosts_tab {
12890: 	my ($file) = @_;
12891: 	foreach my $configline (@$file) {
12892: 	    next if ($configline =~ /^(\#|\s*$ )/x);
12893:             chomp($configline);
12894: 	    if ($configline =~ /^\^/) {
12895:                 if ($configline =~ /^\^([\w.\-]+)/) {
12896:                     $LC_dns_serv{$1} = 1;
12897:                 }
12898:                 next;
12899:             }
12900: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
12901: 	    $name=~s/\s//g;
12902: 	    if ($id && $domain && $role && $name) {
12903:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
12904:                     my $curr = $hostname{$id};
12905:                     my $skip;
12906:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
12907:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
12908:                             $skip = 1;
12909:                         } else {
12910:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
12911:                         }
12912:                     }
12913:                     unless ($skip) {
12914:                         push(@{$name_to_host{$name}},$id);
12915:                     }
12916:                 } else {
12917:                     push(@{$name_to_host{$name}},$id);
12918:                 }
12919: 		$hostname{$id}=$name;
12920: 		$hostdom{$id}=$domain;
12921: 		if ($role eq 'library') { $libserv{$id}=$name; }
12922:                 if (defined($protocol)) {
12923:                     if ($protocol eq 'https') {
12924:                         $protocol{$id} = $protocol;
12925:                     } else {
12926:                         $protocol{$id} = 'http'; 
12927:                     }
12928:                 } else {
12929:                     $protocol{$id} = 'http';
12930:                 }
12931:                 if (defined($intdom)) {
12932:                     $internetdom{$id} = $intdom;
12933:                 }
12934: 	    }
12935: 	}
12936:     }
12937:     
12938:     sub reset_hosts_info {
12939: 	&purge_remembered();
12940: 	&reset_domain_info();
12941: 	&reset_hosts_ip_info();
12942: 	undef(%name_to_host);
12943: 	undef(%hostname);
12944: 	undef(%hostdom);
12945: 	undef(%libserv);
12946: 	undef($loaded);
12947:     }
12948: 
12949:     sub load_hosts_tab {
12950: 	my ($ignore_cache,$nocache) = @_;
12951: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
12952: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
12953: 	my @config = <$config>;
12954: 	&parse_hosts_tab(\@config);
12955: 	close($config);
12956: 	$loaded=1;
12957:     }
12958: 
12959:     sub hostname {
12960: 	&load_hosts_tab() if (!$loaded);
12961: 
12962: 	my ($lonid) = @_;
12963: 	return $hostname{$lonid};
12964:     }
12965: 
12966:     sub all_hostnames {
12967: 	&load_hosts_tab() if (!$loaded);
12968: 
12969: 	return %hostname;
12970:     }
12971: 
12972:     sub all_names {
12973:         my ($ignore_cache,$nocache) = @_;
12974: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
12975: 
12976: 	return %name_to_host;
12977:     }
12978: 
12979:     sub all_host_domain {
12980:         &load_hosts_tab() if (!$loaded);
12981:         return %hostdom;
12982:     }
12983: 
12984:     sub is_library {
12985: 	&load_hosts_tab() if (!$loaded);
12986: 
12987: 	return exists($libserv{$_[0]});
12988:     }
12989: 
12990:     sub all_library {
12991: 	&load_hosts_tab() if (!$loaded);
12992: 
12993: 	return %libserv;
12994:     }
12995: 
12996:     sub unique_library {
12997: 	#2x reverse removes all hostnames that appear more than once
12998:         my %unique = reverse &all_library();
12999:         return reverse %unique;
13000:     }
13001: 
13002:     sub get_servers {
13003: 	&load_hosts_tab() if (!$loaded);
13004: 
13005: 	my ($domain,$type) = @_;
13006: 	my %possible_hosts = ($type eq 'library') ? %libserv
13007: 	                                          : %hostname;
13008: 	my %result;
13009: 	if (ref($domain) eq 'ARRAY') {
13010: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13011: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13012: 		    $result{$host} = $hostname;
13013: 		}
13014: 	    }
13015: 	} else {
13016: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13017: 		if ($hostdom{$host} eq $domain) {
13018: 		    $result{$host} = $hostname;
13019: 		}
13020: 	    }
13021: 	}
13022: 	return %result;
13023:     }
13024: 
13025:     sub get_unique_servers {
13026:         my %unique = reverse &get_servers(@_);
13027: 	return reverse %unique;
13028:     }
13029: 
13030:     sub host_domain {
13031: 	&load_hosts_tab() if (!$loaded);
13032: 
13033: 	my ($lonid) = @_;
13034: 	return $hostdom{$lonid};
13035:     }
13036: 
13037:     sub all_domains {
13038: 	&load_hosts_tab() if (!$loaded);
13039: 
13040: 	my %seen;
13041: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13042: 	return @uniq;
13043:     }
13044: 
13045:     sub internet_dom {
13046:         &load_hosts_tab() if (!$loaded);
13047: 
13048:         my ($lonid) = @_;
13049:         return $internetdom{$lonid};
13050:     }
13051: 
13052:     sub is_LC_dns {
13053:         &load_hosts_tab() if (!$loaded);
13054: 
13055:         my ($hostname) = @_;
13056:         return exists($LC_dns_serv{$hostname});
13057:     }
13058: 
13059: }
13060: 
13061: { 
13062:     my %iphost;
13063:     my %name_to_ip;
13064:     my %lonid_to_ip;
13065: 
13066:     sub get_hosts_from_ip {
13067: 	my ($ip) = @_;
13068: 	my %iphosts = &get_iphost();
13069: 	if (ref($iphosts{$ip})) {
13070: 	    return @{$iphosts{$ip}};
13071: 	}
13072: 	return;
13073:     }
13074:     
13075:     sub reset_hosts_ip_info {
13076: 	undef(%iphost);
13077: 	undef(%name_to_ip);
13078: 	undef(%lonid_to_ip);
13079:     }
13080: 
13081:     sub get_host_ip {
13082: 	my ($lonid) = @_;
13083: 	if (exists($lonid_to_ip{$lonid})) {
13084: 	    return $lonid_to_ip{$lonid};
13085: 	}
13086: 	my $name=&hostname($lonid);
13087:    	my $ip = gethostbyname($name);
13088: 	return if (!$ip || length($ip) ne 4);
13089: 	$ip=inet_ntoa($ip);
13090: 	$name_to_ip{$name}   = $ip;
13091: 	$lonid_to_ip{$lonid} = $ip;
13092: 	return $ip;
13093:     }
13094:     
13095:     sub get_iphost {
13096: 	my ($ignore_cache,$nocache) = @_;
13097: 
13098: 	if (!$ignore_cache) {
13099: 	    if (%iphost) {
13100: 		return %iphost;
13101: 	    }
13102: 	    my ($ip_info,$cached)=
13103: 		&Apache::lonnet::is_cached_new('iphost','iphost');
13104: 	    if ($cached) {
13105: 		%iphost      = %{$ip_info->[0]};
13106: 		%name_to_ip  = %{$ip_info->[1]};
13107: 		%lonid_to_ip = %{$ip_info->[2]};
13108: 		return %iphost;
13109: 	    }
13110: 	}
13111: 
13112: 	# get yesterday's info for fallback
13113: 	my %old_name_to_ip;
13114: 	my ($ip_info,$cached)=
13115: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
13116: 	if ($cached) {
13117: 	    %old_name_to_ip = %{$ip_info->[1]};
13118: 	}
13119: 
13120: 	my %name_to_host = &all_names($ignore_cache,$nocache);
13121: 	foreach my $name (keys(%name_to_host)) {
13122: 	    my $ip;
13123: 	    if (!exists($name_to_ip{$name})) {
13124: 		$ip = gethostbyname($name);
13125: 		if (!$ip || length($ip) ne 4) {
13126: 		    if (defined($old_name_to_ip{$name})) {
13127: 			$ip = $old_name_to_ip{$name};
13128: 			&logthis("Can't find $name defaulting to old $ip");
13129: 		    } else {
13130: 			&logthis("Name $name no IP found");
13131: 			next;
13132: 		    }
13133: 		} else {
13134: 		    $ip=inet_ntoa($ip);
13135: 		}
13136: 		$name_to_ip{$name} = $ip;
13137: 	    } else {
13138: 		$ip = $name_to_ip{$name};
13139: 	    }
13140: 	    foreach my $id (@{ $name_to_host{$name} }) {
13141: 		$lonid_to_ip{$id} = $ip;
13142: 	    }
13143: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
13144: 	}
13145:         unless ($nocache) {
13146: 	    &do_cache_new('iphost','iphost',
13147: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
13148: 		          48*60*60);
13149:         }
13150: 
13151: 	return %iphost;
13152:     }
13153: 
13154:     #
13155:     #  Given a DNS returns the loncapa host name for that DNS 
13156:     # 
13157:     sub host_from_dns {
13158:         my ($dns) = @_;
13159:         my @hosts;
13160:         my $ip;
13161: 
13162:         if (exists($name_to_ip{$dns})) {
13163:             $ip = $name_to_ip{$dns};
13164:         }
13165:         if (!$ip) {
13166:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13167:             if (length($ip) == 4) { 
13168: 	        $ip   = &IO::Socket::inet_ntoa($ip);
13169:             }
13170:         }
13171:         if ($ip) {
13172: 	    @hosts = get_hosts_from_ip($ip);
13173: 	    return $hosts[0];
13174:         }
13175:         return undef;
13176:     }
13177: 
13178:     sub get_internet_names {
13179:         my ($lonid) = @_;
13180:         return if ($lonid eq '');
13181:         my ($idnref,$cached)=
13182:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
13183:         if ($cached) {
13184:             return $idnref;
13185:         }
13186:         my $ip = &get_host_ip($lonid);
13187:         my @hosts = &get_hosts_from_ip($ip);
13188:         my %iphost = &get_iphost();
13189:         my (@idns,%seen);
13190:         foreach my $id (@hosts) {
13191:             my $dom = &host_domain($id);
13192:             my $prim_id = &domain($dom,'primary');
13193:             my $prim_ip = &get_host_ip($prim_id);
13194:             next if ($seen{$prim_ip});
13195:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13196:                 foreach my $id (@{$iphost{$prim_ip}}) {
13197:                     my $intdom = &internet_dom($id);
13198:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
13199:                         push(@idns,$intdom);
13200:                     }
13201:                 }
13202:             }
13203:             $seen{$prim_ip} = 1;
13204:         }
13205:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
13206:     }
13207: 
13208: }
13209: 
13210: sub all_loncaparevs {
13211:     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);
13212: }
13213: 
13214: # ------------------------------------------------------- Read loncaparev table
13215: {
13216:     sub load_loncaparevs {
13217:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13218:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13219:                 while (my $configline=<$config>) {
13220:                     chomp($configline);
13221:                     my ($hostid,$loncaparev)=split(/:/,$configline);
13222:                     $loncaparevs{$hostid}=$loncaparev;
13223:                 }
13224:                 close($config);
13225:             }
13226:         }
13227:     }
13228: }
13229: 
13230: # ----------------------------------------------------- Read serverhostID table
13231: {
13232:     sub load_serverhomeIDs {
13233:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13234:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13235:                 while (my $configline=<$config>) {
13236:                     chomp($configline);
13237:                     my ($name,$id)=split(/:/,$configline);
13238:                     $serverhomeIDs{$name}=$id;
13239:                 }
13240:                 close($config);
13241:             }
13242:         }
13243:     }
13244: }
13245: 
13246: 
13247: BEGIN {
13248: 
13249: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13250:     unless ($readit) {
13251: {
13252:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13253:     %perlvar = (%perlvar,%{$configvars});
13254: }
13255: 
13256: 
13257: # ------------------------------------------------------ Read spare server file
13258: {
13259:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
13260: 
13261:     while (my $configline=<$config>) {
13262:        chomp($configline);
13263:        if ($configline) {
13264: 	   my ($host,$type) = split(':',$configline,2);
13265: 	   if (!defined($type) || $type eq '') { $type = 'default' };
13266: 	   push(@{ $spareid{$type} }, $host);
13267:        }
13268:     }
13269:     close($config);
13270: }
13271: # ------------------------------------------------------------ Read permissions
13272: {
13273:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
13274: 
13275:     while (my $configline=<$config>) {
13276: 	chomp($configline);
13277: 	if ($configline) {
13278: 	    my ($role,$perm)=split(/ /,$configline);
13279: 	    if ($perm ne '') { $pr{$role}=$perm; }
13280: 	}
13281:     }
13282:     close($config);
13283: }
13284: 
13285: # -------------------------------------------- Read plain texts for permissions
13286: {
13287:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
13288: 
13289:     while (my $configline=<$config>) {
13290: 	chomp($configline);
13291: 	if ($configline) {
13292: 	    my ($short,@plain)=split(/:/,$configline);
13293:             %{$prp{$short}} = ();
13294: 	    if (@plain > 0) {
13295:                 $prp{$short}{'std'} = $plain[0];
13296:                 for (my $i=1; $i<@plain; $i++) {
13297:                     $prp{$short}{'alt'.$i} = $plain[$i];  
13298:                 }
13299:             }
13300: 	}
13301:     }
13302:     close($config);
13303: }
13304: 
13305: # ---------------------------------------------------------- Read package table
13306: {
13307:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
13308: 
13309:     while (my $configline=<$config>) {
13310: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
13311: 	chomp($configline);
13312: 	my ($short,$plain)=split(/:/,$configline);
13313: 	my ($pack,$name)=split(/\&/,$short);
13314: 	if ($plain ne '') {
13315: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
13316: 	    $packagetab{$short}=$plain; 
13317: 	}
13318:     }
13319:     close($config);
13320: }
13321: 
13322: # --------------------------------------------------------- Read loncaparev table
13323: 
13324: &load_loncaparevs();
13325: 
13326: # ------------------------------------------------------- Read serverhostID table
13327: 
13328: &load_serverhomeIDs();
13329: 
13330: # ---------------------------------------------------------- Read releaseslist XML
13331: {
13332:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13333:     if (-e $file) {
13334:         my $parser = HTML::LCParser->new($file);
13335:         while (my $token = $parser->get_token()) {
13336:             if ($token->[0] eq 'S') {
13337:                 my $item = $token->[1];
13338:                 my $name = $token->[2]{'name'};
13339:                 my $value = $token->[2]{'value'};
13340:                 if ($item ne '' && $name ne '' && $value ne '') {
13341:                     my $release = $parser->get_text();
13342:                     $release =~ s/(^\s*|\s*$ )//gx;
13343:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
13344:                 }
13345:             }
13346:         }
13347:     }
13348: }
13349: 
13350: # ---------------------------------------------------------- Read managers table
13351: {
13352:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13353:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
13354:             while (my $configline=<$config>) {
13355:                 chomp($configline);
13356:                 next if ($configline =~ /^\#/);
13357:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13358:                     $managerstab{$configline} = 1;
13359:                 }
13360:             }
13361:             close($config);
13362:         }
13363:     }
13364: }
13365: 
13366: # ------------- set up temporary directory
13367: {
13368:     $tmpdir = LONCAPA::tempdir();
13369: 
13370: }
13371: 
13372: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
13373: 				'compress_threshold'=> 20_000,
13374:  			        });
13375: 
13376: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
13377: $dumpcount=0;
13378: $locknum=0;
13379: 
13380: &logtouch();
13381: &logthis('<font color="yellow">INFO: Read configuration</font>');
13382: $readit=1;
13383:     {
13384: 	use integer;
13385: 	my $test=(2**32)+1;
13386: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
13387: 	&logthis(" Detected 64bit platform ($_64bit)");
13388:     }
13389: }
13390: }
13391: 
13392: 1;
13393: __END__
13394: 
13395: =pod
13396: 
13397: =head1 NAME
13398: 
13399: Apache::lonnet - Subroutines to ask questions about things in the network.
13400: 
13401: =head1 SYNOPSIS
13402: 
13403: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
13404: 
13405:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13406: 
13407: Common parameters:
13408: 
13409: =over 4
13410: 
13411: =item *
13412: 
13413: $uname : an internal username (if $cname expecting a course Id specifically)
13414: 
13415: =item *
13416: 
13417: $udom : a domain (if $cdom expecting a course's domain specifically)
13418: 
13419: =item *
13420: 
13421: $symb : a resource instance identifier
13422: 
13423: =item *
13424: 
13425: $namespace : the name of a .db file that contains the data needed or
13426: being set.
13427: 
13428: =back
13429: 
13430: =head1 OVERVIEW
13431: 
13432: lonnet provides subroutines which interact with the
13433: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13434: about classes, users, and resources.
13435: 
13436: For many of these objects you can also use this to store data about
13437: them or modify them in various ways.
13438: 
13439: =head2 Symbs
13440: 
13441: To identify a specific instance of a resource, LON-CAPA uses symbols
13442: or "symbs"X<symb>. These identifiers are built from the URL of the
13443: map, the resource number of the resource in the map, and the URL of
13444: the resource itself. The latter is somewhat redundant, but might help
13445: if maps change.
13446: 
13447: An example is
13448: 
13449:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13450: 
13451: The respective map entry is
13452: 
13453:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
13454:   title="Problem 2">
13455:  </resource>
13456: 
13457: Symbs are used by the random number generator, as well as to store and
13458: restore data specific to a certain instance of for example a problem.
13459: 
13460: =head2 Storing And Retrieving Data
13461: 
13462: X<store()>X<cstore()>X<restore()>Three of the most important functions
13463: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13464: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13465: is is the non-critical message twin of cstore. These functions are for
13466: handlers to store a perl hash to a user's permanent data space in an
13467: easy manner, and to retrieve it again on another call. It is expected
13468: that a handler would use this once at the beginning to retrieve data,
13469: and then again once at the end to send only the new data back.
13470: 
13471: The data is stored in the user's data directory on the user's
13472: homeserver under the ID of the course.
13473: 
13474: The hash that is returned by restore will have all of the previous
13475: value for all of the elements of the hash.
13476: 
13477: Example:
13478: 
13479:  #creating a hash
13480:  my %hash;
13481:  $hash{'foo'}='bar';
13482: 
13483:  #storing it
13484:  &Apache::lonnet::cstore(\%hash);
13485: 
13486:  #changing a value
13487:  $hash{'foo'}='notbar';
13488: 
13489:  #adding a new value
13490:  $hash{'bar'}='foo';
13491:  &Apache::lonnet::cstore(\%hash);
13492: 
13493:  #retrieving the hash
13494:  my %history=&Apache::lonnet::restore();
13495: 
13496:  #print the hash
13497:  foreach my $key (sort(keys(%history))) {
13498:    print("\%history{$key} = $history{$key}");
13499:  }
13500: 
13501: Will print out:
13502: 
13503:  %history{1:foo} = bar
13504:  %history{1:keys} = foo:timestamp
13505:  %history{1:timestamp} = 990455579
13506:  %history{2:bar} = foo
13507:  %history{2:foo} = notbar
13508:  %history{2:keys} = foo:bar:timestamp
13509:  %history{2:timestamp} = 990455580
13510:  %history{bar} = foo
13511:  %history{foo} = notbar
13512:  %history{timestamp} = 990455580
13513:  %history{version} = 2
13514: 
13515: Note that the special hash entries C<keys>, C<version> and
13516: C<timestamp> were added to the hash. C<version> will be equal to the
13517: total number of versions of the data that have been stored. The
13518: C<timestamp> attribute will be the UNIX time the hash was
13519: stored. C<keys> is available in every historical section to list which
13520: keys were added or changed at a specific historical revision of a
13521: hash.
13522: 
13523: B<Warning>: do not store the hash that restore returns directly. This
13524: will cause a mess since it will restore the historical keys as if the
13525: were new keys. I.E. 1:foo will become 1:1:foo etc.
13526: 
13527: Calling convention:
13528: 
13529:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
13530:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
13531: 
13532: For more detailed information, see lonnet specific documentation.
13533: 
13534: =head1 RETURN MESSAGES
13535: 
13536: =over 4
13537: 
13538: =item * B<con_lost>: unable to contact remote host
13539: 
13540: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13541: when the connection is brought back up
13542: 
13543: =item * B<con_failed>: unable to contact remote host and unable to save message
13544: for later delivery
13545: 
13546: =item * B<error:>: an error a occurred, a description of the error follows the :
13547: 
13548: =item * B<no_such_host>: unable to fund a host associated with the user/domain
13549: that was requested
13550: 
13551: =back
13552: 
13553: =head1 PUBLIC SUBROUTINES
13554: 
13555: =head2 Session Environment Functions
13556: 
13557: =over 4
13558: 
13559: =item * 
13560: X<appenv()>
13561: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
13562: the user envirnoment file, and will be restored for each access this
13563: user makes during this session, also modifies the %env for the current
13564: process. Optional rolesarrayref - if defined contains a reference to an array
13565: of roles which are exempt from the restriction on modifying user.role entries 
13566: in the user's environment.db and in %env.    
13567: 
13568: =item *
13569: X<delenv()>
13570: B<delenv($delthis,$regexp)>: removes all items from the session
13571: environment file that begin with $delthis. If the 
13572: optional second arg - $regexp - is true, $delthis is treated as a 
13573: regular expression, otherwise \Q$delthis\E is used. 
13574: The values are also deleted from the current processes %env.
13575: 
13576: =item * get_env_multiple($name) 
13577: 
13578: gets $name from the %env hash, it seemlessly handles the cases where multiple
13579: values may be defined and end up as an array ref.
13580: 
13581: returns an array of values
13582: 
13583: =back
13584: 
13585: =head2 User Information
13586: 
13587: =over 4
13588: 
13589: =item *
13590: X<queryauthenticate()>
13591: B<queryauthenticate($uname,$udom)>: try to determine user's current 
13592: authentication scheme
13593: 
13594: =item *
13595: X<authenticate()>
13596: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
13597: authenticate user from domain's lib servers (first use the current
13598: one). C<$upass> should be the users password.
13599: $checkdefauth is optional (value is 1 if a check should be made to
13600:    authenticate user using default authentication method, and allow
13601:    account creation if username does not have account in the domain).
13602: $clientcancheckhost is optional (value is 1 if checking whether the
13603:    server can host will occur on the client side in lonauth.pm).   
13604: 
13605: =item *
13606: X<homeserver()>
13607: B<homeserver($uname,$udom)>: find the server which has
13608: the user's directory and files (there must be only one), this caches
13609: the answer, and also caches if there is a borken connection.
13610: 
13611: =item *
13612: X<idget()>
13613: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13614: (IDs are a unique resource in a domain, there must be only 1 ID per
13615: username, and only 1 username per ID in a specific domain) (returns
13616: hash: id=>name,id=>name)
13617: 
13618: =item *
13619: X<idrget()>
13620: B<idrget($udom,@unames)>: find the IDs behind a list of
13621: usernames (returns hash: name=>id,name=>id)
13622: 
13623: =item *
13624: X<idput()>
13625: B<idput($udom,%ids)>: store away a list of names and associated IDs
13626: 
13627: =item *
13628: X<rolesinit()>
13629: B<rolesinit($udom,$username)>: get user privileges.
13630: returns user role, first access and timer interval hashes
13631: 
13632: =item *
13633: X<privileged()>
13634: B<privileged($username,$domain)>: returns a true if user has a
13635: privileged and active role (i.e. su or dc), false otherwise.
13636: 
13637: =item *
13638: X<getsection()>
13639: B<getsection($udom,$uname,$cname)>: finds the section of student in the
13640: course $cname, return section name/number or '' for "not in course"
13641: and '-1' for "no section"
13642: 
13643: =item *
13644: X<userenvironment()>
13645: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
13646: passed in @what from the requested user's environment, returns a hash
13647: 
13648: =item * 
13649: X<userlog_query()>
13650: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13651: activity.log file. %filters defines filters applied when parsing the
13652: log file. These can be start or end timestamps, or the type of action
13653: - log to look for Login or Logout events, check for Checkin or
13654: Checkout, role for role selection. The response is in the form
13655: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
13656: escaped strings of the action recorded in the activity.log file.
13657: 
13658: =back
13659: 
13660: =head2 User Roles
13661: 
13662: =over 4
13663: 
13664: =item *
13665: 
13666: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
13667: returns codes for allowed actions.
13668: 
13669: The first argument is required, all others are optional.
13670: 
13671: $priv is the privilege being checked.
13672: $uri contains additional information about what is being checked for access (e.g.,
13673: URL, course ID etc.).
13674: $symb is the unique resource instance identifier in a course; if needed,
13675: but not provided, it will be retrieved via a call to &symbread().
13676: $role is the role for which a priv is being checked (only used if priv is evb).
13677: $clientip is the user's IP address (only used when checking for access to portfolio
13678: files).
13679: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13680: prevents recursive calls to &allowed.
13681: 
13682:  F: full access
13683:  U,I,K: authentication modes (cxx only)
13684:  '': forbidden
13685:  1: user needs to choose course
13686:  2: browse allowed
13687:  A: passphrase authentication needed
13688:  B: access temporarily blocked because of a blocking event in a course.
13689: 
13690: =item *
13691: 
13692: constructaccess($url,$setpriv) : check for access to construction space URL
13693: 
13694: See if the owner domain and name in the URL match those in the
13695: expected environment.  If so, return three element list
13696: ($ownername,$ownerdomain,$ownerhome).
13697: 
13698: Otherwise return the null string.
13699: 
13700: If second argument 'setpriv' is true, it assigns the privileges,
13701: and returns the same three element list, unless the owner has
13702: blocked "ad hoc" Domain Coordinator access to the Author Space,
13703: in which case the null string is returned.
13704: 
13705: =item *
13706: 
13707: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
13708: define a custom role rolename set privileges in format of lonTabs/roles.tab
13709: for system, domain, and course level. $uname and $udom are optional (current
13710: user's username and domain will be used when either of $uname or $udom are absent.
13711: 
13712: =item *
13713: 
13714: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
13715: (rolesplain.tab); plain text explanation of a user role term.
13716: $type is Course (default) or Community.
13717: If $forcedefault evaluates to true, text returned will be default 
13718: text for $type. Otherwise, if this is a course, the text returned 
13719: will be a custom name for the role (if defined in the course's 
13720: environment).  If no custom name is defined the default is returned.
13721:    
13722: =item *
13723: 
13724: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
13725: All arguments are optional. Returns a hash of a roles, either for
13726: co-author/assistant author roles for a user's Construction Space
13727: (default), or if $context is 'userroles', roles for the user himself,
13728: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13729: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13730: For each key, value is set to colon-separated start and end times for
13731: the role.  If no username and domain are specified, will default to
13732: current user/domain. Types, roles, and roledoms are references to arrays
13733: of role statuses (active, future or previous), roles 
13734: (e.g., cc,in, st etc.) and domains of the roles which can be used
13735: to restrict the list of roles reported. If no array ref is 
13736: provided for types, will default to return only active roles.
13737: 
13738: =item *
13739: 
13740: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13741: user: $uname:$udom has a role in the course: $cdom_$cnum.
13742: 
13743: Additional optional arguments are: $type (if role checking is to be restricted
13744: to certain user status types -- previous (expired roles), active (currently
13745: available roles) or future (roles available in the future), and
13746: $hideprivileged -- if true will not report course roles for users who
13747: have active Domain Coordinator role in course's domain or in additional
13748: domains (specified in 'Domains to check for privileged users' in course
13749: environment -- set via:  Course Settings -> Classlists and staff listing).
13750: 
13751: =item *
13752: 
13753: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13754: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13755: $possdomains and $possroles are optional array refs -- to domains to check and
13756: roles to check.  If $possdomains is not specified, a dump will be done of the
13757: users' roles.db to check for a dc or su role in any domain. This can be
13758: time consuming if &privileged is called repeatedly (e.g., when displaying a
13759: classlist), so in such cases, supplying a $possdomains array is preferred, as
13760: this then allows &privileged_by_domain() to be used, which caches the identity
13761: of privileged users, eliminating the need for repeated calls to &dump().
13762: 
13763: =item *
13764: 
13765: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13766: where the outer hash keys are domains specified in the $possdomains array ref,
13767: next inner hash keys are privileged roles specified in the $roles array ref,
13768: and the innermost hash contains key = value pairs for username:domain = end:start
13769: for active or future "privileged" users with that role in that domain. To avoid
13770: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13771: innerhash are cached using priv_$role and $dom as the identifiers.
13772: 
13773: =back
13774: 
13775: =head2 User Modification
13776: 
13777: =over 4
13778: 
13779: =item *
13780: 
13781: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
13782: user for the level given by URL.  Optional start and end dates (leave empty
13783: string or zero for "no date")
13784: 
13785: =item *
13786: 
13787: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13788: change a users, password, possible return values are: ok,
13789: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13790: refused
13791: 
13792: =item *
13793: 
13794: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
13795: 
13796: =item *
13797: 
13798: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13799:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
13800: 
13801: will update user information (firstname,middlename,lastname,generation,
13802: permanentemail), and if forceid is true, student/employee ID also.
13803: A user's institutional affiliation(s) can also be updated.
13804: User information fields will not be overwritten with empty entries 
13805: unless the field is included in the $candelete array reference.
13806: This array is included when a single user is modified via "Manage Users",
13807: or when Autoupdate.pl is run by cron in a domain.
13808: 
13809: =item *
13810: 
13811: modifystudent
13812: 
13813: modify a student's enrollment and identification information.
13814: The course id is resolved based on the current user's environment.  
13815: This means the invoking user must be a course coordinator or otherwise
13816: associated with a course.
13817: 
13818: This call is essentially a wrapper for lonnet::modifyuser and
13819: lonnet::modify_student_enrollment
13820: 
13821: Inputs: 
13822: 
13823: =over 4
13824: 
13825: =item B<$udom> Student's loncapa domain
13826: 
13827: =item B<$uname> Student's loncapa login name
13828: 
13829: =item B<$uid> Student/Employee ID
13830: 
13831: =item B<$umode> Student's authentication mode
13832: 
13833: =item B<$upass> Student's password
13834: 
13835: =item B<$first> Student's first name
13836: 
13837: =item B<$middle> Student's middle name
13838: 
13839: =item B<$last> Student's last name
13840: 
13841: =item B<$gene> Student's generation
13842: 
13843: =item B<$usec> Student's section in course
13844: 
13845: =item B<$end> Unix time of the roles expiration
13846: 
13847: =item B<$start> Unix time of the roles start date
13848: 
13849: =item B<$forceid> If defined, allow $uid to be changed
13850: 
13851: =item B<$desiredhome> server to use as home server for student
13852: 
13853: =item B<$email> Student's permanent e-mail address
13854: 
13855: =item B<$type> Type of enrollment (auto or manual)
13856: 
13857: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
13858: 
13859: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
13860: 
13861: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
13862: 
13863: =item B<$context> role change context (shown in User Management Logs display in a course)
13864: 
13865: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13866: 
13867: =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.
13868: 
13869: =back
13870: 
13871: =item *
13872: 
13873: modify_student_enrollment
13874: 
13875: Change a student's enrollment status in a class.  The environment variable
13876: 'role.request.course' must be defined for this function to proceed.
13877: 
13878: Inputs:
13879: 
13880: =over 4
13881: 
13882: =item $udom, student's domain
13883: 
13884: =item $uname, student's name
13885: 
13886: =item $uid, student's user id
13887: 
13888: =item $first, student's first name
13889: 
13890: =item $middle
13891: 
13892: =item $last
13893: 
13894: =item $gene
13895: 
13896: =item $usec
13897: 
13898: =item $end
13899: 
13900: =item $start
13901: 
13902: =item $type
13903: 
13904: =item $locktype
13905: 
13906: =item $cid
13907: 
13908: =item $selfenroll
13909: 
13910: =item $context
13911: 
13912: =item $credits, number of credits student will earn from this class
13913: 
13914: =item $instsec, institutional course section code for student
13915: 
13916: =back
13917: 
13918: 
13919: =item *
13920: 
13921: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13922: custom role; give a custom role to a user for the level given by URL.  Specify
13923: name and domain of role author, and role name
13924: 
13925: =item *
13926: 
13927: revokerole($udom,$uname,$url,$role) : revoke a role for url
13928: 
13929: =item *
13930: 
13931: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13932: 
13933: =back
13934: 
13935: =head2 Course Infomation
13936: 
13937: =over 4
13938: 
13939: =item *
13940: 
13941: coursedescription($courseid,$options) : returns a hash of information about the
13942: specified course id, including all environment settings for the
13943: course, the description of the course will be in the hash under the
13944: key 'description'
13945: 
13946: $options is an optional parameter that if supplied is a hash reference that controls
13947: what how this function works.  It has the following key/values:
13948: 
13949: =over 4
13950: 
13951: =item freshen_cache
13952: 
13953: If defined, and the environment cache for the course is valid, it is 
13954: returned in the returned hash.
13955: 
13956: =item one_time
13957: 
13958: If defined, the last cache time is set to _now_
13959: 
13960: =item user
13961: 
13962: If defined, the supplied username is used instead of the current user.
13963: 
13964: 
13965: =back
13966: 
13967: =item *
13968: 
13969: resdata($name,$domain,$type,@which) : request for current parameter
13970: setting for a specific $type, where $type is either 'course' or 'user',
13971: @what should be a list of parameters to ask about. This routine caches
13972: answers for 10 minutes.
13973: 
13974: =item *
13975: 
13976: get_courseresdata($courseid, $domain) : dump the entire course resource
13977: data base, returning a hash that is keyed by the resource name and has
13978: values that are the resource value.  I believe that the timestamps and
13979: versions are also returned.
13980: 
13981: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13982: supplemental content area. This routine caches the number of files for
13983: 10 minutes.
13984: 
13985: =back
13986: 
13987: =head2 Course Modification
13988: 
13989: =over 4
13990: 
13991: =item *
13992: 
13993: writecoursepref($courseid,%prefs) : write preferences (environment
13994: database) for a course
13995: 
13996: =item *
13997: 
13998: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13999: 
14000: =item *
14001: 
14002: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14003: 
14004: =item *
14005: 
14006: is_course($courseid), is_course($cdom, $cnum)
14007: 
14008: Accepts either a combined $courseid (in the form of domain_courseid) or the
14009: two component version $cdom, $cnum. It checks if the specified course exists.
14010: 
14011: Returns:
14012:     undef if the course doesn't exist, otherwise
14013:     in scalar context the combined courseid.
14014:     in list context the two components of the course identifier, domain and 
14015:     courseid.    
14016: 
14017: =back
14018: 
14019: =head2 Resource Subroutines
14020: 
14021: =over 4
14022: 
14023: =item *
14024: 
14025: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14026: 
14027: =item *
14028: 
14029: repcopy($filename) : subscribes to the requested file, and attempts to
14030: replicate from the owning library server, Might return
14031: 'unavailable', 'not_found', 'forbidden', 'ok', or
14032: 'bad_request', also attempts to grab the metadata for the
14033: resource. Expects the local filesystem pathname
14034: (/home/httpd/html/res/....)
14035: 
14036: =back
14037: 
14038: =head2 Resource Information
14039: 
14040: =over 4
14041: 
14042: =item *
14043: 
14044: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14045: and returns the value of a variety of different possible values,
14046: $varname should be a request string, and the other parameters can be
14047: used to specify who and what one is asking about. Ordinarily, $cid 
14048: does not need to be specified, as it is retrived from 
14049: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14050: within lonuserstate::loadmap() when initializing a course, before
14051: $env{'request.course.id'} has been set, so it needs to be provided
14052: in that one case.
14053: 
14054: Possible values for $varname are environment.lastname (or other item
14055: from the envirnment hash), user.name (or someother aspect about the
14056: user), resource.0.maxtries (or some other part and parameter of a
14057: resource)
14058: 
14059: =item *
14060: 
14061: directcondval($number) : get current value of a condition; reads from a state
14062: string
14063: 
14064: =item *
14065: 
14066: condval($condidx) : value of condition index based on state
14067: 
14068: =item *
14069: 
14070: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14071: resource's metadata, $what should be either a specific key, or either
14072: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14073: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14074: 
14075: this function automatically caches all requests
14076: 
14077: =item *
14078: 
14079: metadata_query($query,$custom,$customshow) : make a metadata query against the
14080: network of library servers; returns file handle of where SQL and regex results
14081: will be stored for query
14082: 
14083: =item *
14084: 
14085: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14086: return symbolic list entry (all arguments optional).
14087: 
14088: Args: filename is the filename (including path) for the file for which a symb
14089: is required; donotrecurse, if true will prevent calls to allowed() being made
14090: to check access status if more than one resource was found in the bighash
14091: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14092: a randompick); ignorecachednull, if true will prevent a symb of '' being
14093: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14094: cause possible symbs to be checked to determine if they are subject to content
14095: blocking, if so they will not be included as possible symbs; possibles is a
14096: ref to a hash, which, as a side effect, will be populated with all possible
14097: symbs (content blocking not tested).
14098: 
14099: returns the data handle
14100: 
14101: =item *
14102: 
14103: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14104: and is a possible symb for the URL in $thisfn, and if is an encrypted
14105: resource that the user accessed using /enc/ returns a 1 on success, 0
14106: on failure, user must be in a course, as it assumes the existence of
14107: the course initial hash, and uses $env('request.course.id'}.  The third
14108: arg is an optional reference to a scalar.  If this arg is passed in the
14109: call to symbverify, it will be set to 1 if the symb has been set to be 
14110: encrypted; otherwise it will be null.
14111: 
14112: =item *
14113: 
14114: symbclean($symb) : removes versions numbers from a symb, returns the
14115: cleaned symb
14116: 
14117: =item *
14118: 
14119: is_on_map($uri) : checks if the $uri is somewhere on the current
14120: course map, user must be in a course for it to work.
14121: 
14122: =item *
14123: 
14124: numval($salt) : return random seed value (addend for rndseed)
14125: 
14126: =item *
14127: 
14128: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14129: a random seed, all arguments are optional, if they aren't sent it uses the
14130: environment to derive them. Note: if symb isn't sent and it can't get one
14131: from &symbread it will use the current time as its return value
14132: 
14133: =item *
14134: 
14135: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14136: unfakeable, receipt
14137: 
14138: =item *
14139: 
14140: receipt() : API to ireceipt working off of env values; given out to users
14141: 
14142: =item *
14143: 
14144: countacc($url) : count the number of accesses to a given URL
14145: 
14146: =item *
14147: 
14148: 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
14149: 
14150: =item *
14151: 
14152: 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)
14153: 
14154: =item *
14155: 
14156: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
14157: 
14158: =item *
14159: 
14160: devalidate($symb) : devalidate temporary spreadsheet calculations,
14161: forcing spreadsheet to reevaluate the resource scores next time.
14162: 
14163: =item *
14164: 
14165: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14166: when viewing in course context.
14167: 
14168:  input: six args -- filename (decluttered), course number, course domain,
14169:                     url, symb (if registered) and group (if this is a
14170:                     group item -- e.g., bulletin board, group page etc.).
14171: 
14172:  output: array of five scalars --
14173:          $cfile -- url for file editing if editable on current server
14174:          $home -- homeserver of resource (i.e., for author if published,
14175:                                           or course if uploaded.).
14176:          $switchserver --  1 if server switch will be needed.
14177:          $forceedit -- 1 if icon/link should be to go to edit mode
14178:          $forceview -- 1 if icon/link should be to go to view mode
14179: 
14180: =item *
14181: 
14182: is_course_upload($file,$cnum,$cdom)
14183: 
14184: Used in course context to determine if current file was uploaded to
14185: the course (i.e., would be found in /userfiles/docs on the course's
14186: homeserver.
14187: 
14188:   input: 3 args -- filename (decluttered), course number and course domain.
14189:   output: boolean -- 1 if file was uploaded.
14190: 
14191: =back
14192: 
14193: =head2 Storing/Retreiving Data
14194: 
14195: =over 4
14196: 
14197: =item *
14198: 
14199: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
14200: permanently for this url; hashref needs to be given and should be a \%hashname;
14201: the remaining args aren't required and if they aren't passed or are '' they will
14202: be derived from the env (with the exception of $laststore, which is an
14203: optional arg used when a user's submission is stored in grading).
14204: $laststore is $version=$timestamp, where $version is the most recent version
14205: number retrieved for the corresponding $symb in the $namespace db file, and
14206: $timestamp is the timestamp for that transaction (UNIX time).
14207: $laststore is currently only passed when cstore() is called by
14208: structuretags::finalize_storage().
14209: 
14210: =item *
14211: 
14212: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
14213: but uses critical subroutine
14214: 
14215: =item *
14216: 
14217: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14218: all args are optional
14219: 
14220: =item *
14221: 
14222: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
14223: dumps the complete (or key matching regexp) namespace into a hash
14224: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14225: normally &store()ed into
14226: 
14227: $range should be either an integer '100' (give me the first 100
14228:                                            matching records)
14229:               or be  two integers sperated by a - with no spaces
14230:                  '30-50' (give me the 30th through the 50th matching
14231:                           records)
14232: 
14233: 
14234: =item *
14235: 
14236: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
14237: replaces a &store() version of data with a replacement set of data
14238: for a particular resource in a namespace passed in the $storehash hash 
14239: reference. If $tolog is true, the transaction is logged in the courselog
14240: with an action=PUTSTORE.
14241: 
14242: =item *
14243: 
14244: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14245: works very similar to store/cstore, but all data is stored in a
14246: temporary location and can be reset using tmpreset, $storehash should
14247: be a hash reference, returns nothing on success
14248: 
14249: =item *
14250: 
14251: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14252: similar to restore, but all data is stored in a temporary location and
14253: can be reset using tmpreset. Returns a hash of values on success,
14254: error string otherwise.
14255: 
14256: =item *
14257: 
14258: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14259: deltes all keys for $symb form the temporary storage hash.
14260: 
14261: =item *
14262: 
14263: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14264: reference filled in from namesp ($udom and $uname are optional)
14265: 
14266: =item *
14267: 
14268: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14269: namesp ($udom and $uname are optional)
14270: 
14271: =item *
14272: 
14273: dump($namespace,$udom,$uname,$regexp,$range) : 
14274: dumps the complete (or key matching regexp) namespace into a hash
14275: ($udom, $uname, $regexp, $range are optional)
14276: 
14277: $range should be either an integer '100' (give me the first 100
14278:                                            matching records)
14279:               or be  two integers sperated by a - with no spaces
14280:                  '30-50' (give me the 30th through the 50th matching
14281:                           records)
14282: =item *
14283: 
14284: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14285: $store can be a scalar, an array reference, or if the amount to be 
14286: incremented is > 1, a hash reference.
14287: 
14288: ($udom and $uname are optional)
14289: 
14290: =item *
14291: 
14292: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14293: ($udom and $uname are optional)
14294: 
14295: =item *
14296: 
14297: cput($namespace,$storehash,$udom,$uname) : critical put
14298: ($udom and $uname are optional)
14299: 
14300: =item *
14301: 
14302: newput($namespace,$storehash,$udom,$uname) :
14303: 
14304: Attempts to store the items in the $storehash, but only if they don't
14305: currently exist, if this succeeds you can be certain that you have 
14306: successfully created a new key value pair in the $namespace db.
14307: 
14308: 
14309: Args:
14310:  $namespace: name of database to store values to
14311:  $storehash: hashref to store to the db
14312:  $udom: (optional) domain of user containing the db
14313:  $uname: (optional) name of user caontaining the db
14314: 
14315: Returns:
14316:  'ok' -> succeeded in storing all keys of $storehash
14317:  'key_exists: <key>' -> failed to anything out of $storehash, as at
14318:                         least <key> already existed in the db (other
14319:                         requested keys may also already exist)
14320:  'error: <msg>' -> unable to tie the DB or other error occurred
14321:  'con_lost' -> unable to contact request server
14322:  'refused' -> action was not allowed by remote machine
14323: 
14324: 
14325: =item *
14326: 
14327: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14328: reference filled in from namesp (encrypts the return communication)
14329: ($udom and $uname are optional)
14330: 
14331: =item *
14332: 
14333: log($udom,$name,$home,$message) : write to permanent log for user; use
14334: critical subroutine
14335: 
14336: =item *
14337: 
14338: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14339: array reference filled in from namespace found in domain level on either
14340: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
14341: 
14342: =item *
14343: 
14344: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
14345: domain level either on specified domain server ($uhome) or primary domain 
14346: server ($udom and $uhome are optional)
14347: 
14348: =item * 
14349: 
14350: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14351: for: authentication, language, quotas, timezone, date locale, and portal URL in
14352: the target domain.
14353: 
14354: May also include additional key => value pairs for the following groups:
14355: 
14356: =over
14357: 
14358: =item
14359: disk quotas (MB allocated by default to portfolios and authoring spaces).
14360: 
14361: =over
14362: 
14363: =item defaultquota, authorquota
14364: 
14365: =back
14366: 
14367: =item
14368: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14369: portfolio for users).
14370: 
14371: =over
14372: 
14373: =item
14374: aboutme, blog, webdav, portfolio
14375: 
14376: =back
14377: 
14378: =item
14379: requestcourses: ability to request courses, and how requests are processed.
14380: 
14381: =over
14382: 
14383: =item
14384: official, unofficial, community, textbook
14385: 
14386: =back
14387: 
14388: =item
14389: inststatus: types of institutional affiliation, and order in which they are displayed.
14390: 
14391: =over
14392: 
14393: =item
14394: inststatustypes, inststatusorder, inststatusguest
14395: 
14396: =back
14397: 
14398: =item
14399: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14400: for course's uploaded content.
14401: 
14402: =over
14403: 
14404: =item
14405: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
14406: communityquota, textbookquota
14407: 
14408: =back
14409: 
14410: =item
14411: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14412: on your servers.
14413: 
14414: =over
14415: 
14416: =item
14417: remotesessions, hostedsessions
14418: 
14419: =back
14420: 
14421: =back
14422: 
14423: In cases where a domain coordinator has never used the "Set Domain Configuration"
14424: utility to create a configuration.db file on a domain's primary library server
14425: only the following domain defaults: auth_def, auth_arg_def, lang_def
14426: -- corresponding values are authentication type (internal, krb4, krb5,
14427: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14428: will be available. Values are retrieved from cache (if current), unless the
14429: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14430: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14431: 
14432: Typical usage:
14433: 
14434: %domdefaults = &get_domain_defaults($target_domain);
14435: 
14436: =back
14437: 
14438: =head2 Network Status Functions
14439: 
14440: =over 4
14441: 
14442: =item *
14443: 
14444: dirlist() : return directory list based on URI (first arg).
14445: 
14446: Inputs: 1 required, 5 optional.
14447: 
14448: =over
14449: 
14450: =item 
14451: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14452: 
14453: =item
14454: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
14455: 
14456: =item
14457: $username -  username of user/course to be listed. Extracted from $uri if absent. 
14458: 
14459: =item
14460: $getpropath - boolean: 1 if prepend path using &propath(). 
14461: 
14462: =item
14463: $getuserdir - boolean: 1 if prepend path for "userfiles".
14464: 
14465: =item 
14466: $alternateRoot - path to prepend in place of path from $uri.
14467: 
14468: =back
14469: 
14470: Returns: Array of up to two items.
14471: 
14472: =over
14473: 
14474: a reference to an array of files/subdirectories
14475: 
14476: =over
14477: 
14478: Each element in the array of files/subdirectories is a & separated list of
14479: item name and the result of running stat on the item.  If dirlist was requested
14480: for a file instead of a directory, the item name will be ''. For a directory 
14481: listing, if the item is a metadata file, the element will end &N&M 
14482: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14483: default copyright set (1).  
14484: 
14485: =back
14486: 
14487: a scalar containing error condition (if encountered).
14488: 
14489: =over
14490: 
14491: =item 
14492: no_host (no homeserver identified for $username:$domain).
14493: 
14494: =item 
14495: no_such_host (server contacted for listing not identified as valid host).
14496: 
14497: =item 
14498: con_lost (connection to remote server failed).
14499: 
14500: =item 
14501: refused (invalid $username:$domain received on lond side).
14502: 
14503: =item 
14504: no_such_dir (directory at specified path on lond side does not exist). 
14505: 
14506: =item 
14507: empty (directory at specified path on lond side is empty).
14508: 
14509: =over
14510: 
14511: This is currently not encountered because the &ls3, &ls2, 
14512: &ls (_handler) routines on the lond side do not filter out
14513: . and .. from a directory listing. 
14514: 
14515: =back
14516: 
14517: =back
14518: 
14519: =back
14520: 
14521: =item *
14522: 
14523: spareserver() : find server with least workload from spare.tab
14524: 
14525: 
14526: =item *
14527: 
14528: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14529: if there is no corresponding loncapa host.
14530: 
14531: =back
14532: 
14533: 
14534: =head2 Apache Request
14535: 
14536: =over 4
14537: 
14538: =item *
14539: 
14540: ssi($url,%hash) : server side include, does a complete request cycle on url to
14541: localhost, posts hash
14542: 
14543: =back
14544: 
14545: =head2 Data to String to Data
14546: 
14547: =over 4
14548: 
14549: =item *
14550: 
14551: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14552: and '&' separators, supports elements that are arrayrefs and hashrefs
14553: 
14554: =item *
14555: 
14556: hashref2str($hashref) : convert a hashref into a string complete with
14557: escaping and '=' and '&' separators, supports elements that are
14558: arrayrefs and hashrefs
14559: 
14560: =item *
14561: 
14562: arrayref2str($arrayref) : convert an arrayref into a string complete
14563: with escaping and '&' separators, supports elements that are arrayrefs
14564: and hashrefs
14565: 
14566: =item *
14567: 
14568: str2hash($string) : convert string to hash using unescaping and
14569: splitting on '=' and '&', supports elements that are arrayrefs and
14570: hashrefs
14571: 
14572: =item *
14573: 
14574: str2array($string) : convert string to hash using unescaping and
14575: splitting on '&', supports elements that are arrayrefs and hashrefs
14576: 
14577: =back
14578: 
14579: =head2 Logging Routines
14580: 
14581: 
14582: These routines allow one to make log messages in the lonnet.log and
14583: lonnet.perm logfiles.
14584: 
14585: =over 4
14586: 
14587: =item *
14588: 
14589: logtouch() : make sure the logfile, lonnet.log, exists
14590: 
14591: =item *
14592: 
14593: logthis() : append message to the normal lonnet.log file, it gets
14594: preiodically rolled over and deleted.
14595: 
14596: =item *
14597: 
14598: logperm() : append a permanent message to lonnet.perm.log, this log
14599: file never gets deleted by any automated portion of the system, only
14600: messages of critical importance should go in here.
14601: 
14602: 
14603: =back
14604: 
14605: =head2 General File Helper Routines
14606: 
14607: =over 4
14608: 
14609: =item *
14610: 
14611: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14612: (a) files in /uploaded
14613:   (i) If a local copy of the file exists - 
14614:       compares modification date of local copy with last-modified date for 
14615:       definitive version stored on home server for course. If local copy is 
14616:       stale, requests a new version from the home server and stores it. 
14617:       If the original has been removed from the home server, then local copy 
14618:       is unlinked.
14619:   (ii) If local copy does not exist -
14620:       requests the file from the home server and stores it. 
14621:   
14622:   If $caller is 'uploadrep':  
14623:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14624:     for request for files originally uploaded via DOCS. 
14625:      - returns 'ok' if fresh local copy now available, -1 otherwise.
14626:   
14627:   Otherwise:
14628:      This indicates a call from the content generation phase of the request.
14629:      -  returns the entire contents of the file or -1.
14630:      
14631: (b) files in /res
14632:    - returns the entire contents of a file or -1; 
14633:    it properly subscribes to and replicates the file if neccessary.
14634: 
14635: 
14636: =item *
14637: 
14638: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14639:                   reference
14640: 
14641: returns either a stat() list of data about the file or an empty list
14642: if the file doesn't exist or couldn't find out about it (connection
14643: problems or user unknown)
14644: 
14645: =item *
14646: 
14647: filelocation($dir,$file) : returns file system location of a file
14648: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14649: directory that relative $file lookups are to looked in ($dir of /a/dir
14650: and a file of ../bob will become /a/bob)
14651: 
14652: =item *
14653: 
14654: hreflocation($dir,$file) : returns file system location or a URL; same as
14655: filelocation except for hrefs
14656: 
14657: =item *
14658: 
14659: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14660: also removes beginning /home/httpd/html unless /priv/ follows it.
14661: 
14662: =back
14663: 
14664: =head2 Usererfile file routines (/uploaded*)
14665: 
14666: =over 4
14667: 
14668: =item *
14669: 
14670: userfileupload(): main rotine for putting a file in a user or course's
14671:                   filespace, arguments are,
14672: 
14673:  formname - required - this is the name of the element in $env where the
14674:            filename, and the contents of the file to create/modifed exist
14675:            the filename is in $env{'form.'.$formname.'.filename'} and the
14676:            contents of the file is located in $env{'form.'.$formname}
14677:  context - if coursedoc, store the file in the course of the active role
14678:              of the current user; 
14679:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14680:            if 'canceloverwrite': delete file in tmp/overwrites directory
14681:  subdir - required - subdirectory to put the file in under ../userfiles/
14682:          if undefined, it will be placed in "unknown"
14683: 
14684:  (This routine calls clean_filename() to remove any dangerous
14685:  characters from the filename, and then calls finuserfileupload() to
14686:  complete the transaction)
14687: 
14688:  returns either the url of the uploaded file (/uploaded/....) if successful
14689:  and /adm/notfound.html if unsuccessful
14690: 
14691: =item *
14692: 
14693: clean_filename(): routine for cleaing a filename up for storage in
14694:                  userfile space, argument is:
14695: 
14696:  filename - proposed filename
14697: 
14698: returns: the new clean filename
14699: 
14700: =item *
14701: 
14702: finishuserfileupload(): routine that creates and sends the file to
14703: userspace, probably shouldn't be called directly
14704: 
14705:   docuname: username or courseid of destination for the file
14706:   docudom: domain of user/course of destination for the file
14707:   formname: same as for userfileupload()
14708:   fname: filename (including subdirectories) for the file
14709:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14710:   allfiles: reference to hash used to store objects found by parser
14711:   codebase: reference to hash used for codebases of java objects found by parser
14712:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14713:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
14714:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
14715:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
14716:   context: if 'overwrite', will move the uploaded file from its temporary location to
14717:             userfiles to facilitate overwriting a previously uploaded file with same name.
14718:   mimetype: reference to scalar to accommodate mime type determined
14719:             from File::MMagic if $parser = parse.
14720: 
14721:  returns either the url of the uploaded file (/uploaded/....) if successful
14722:  and /adm/notfound.html if unsuccessful (or an error message if context 
14723:  was 'overwrite').
14724:  
14725: 
14726: =item *
14727: 
14728: renameuserfile(): renames an existing userfile to a new name
14729: 
14730:   Args:
14731:    docuname: username or courseid of destination for the file
14732:    docudom: domain of user/course of destination for the file
14733:    old: current file name (including any subdirs under userfiles)
14734:    new: desired file name (including any subdirs under userfiles)
14735: 
14736: =item *
14737: 
14738: mkdiruserfile(): creates a directory is a userfiles dir
14739: 
14740:   Args:
14741:    docuname: username or courseid of destination for the file
14742:    docudom: domain of user/course of destination for the file
14743:    dir: dir to create (including any subdirs under userfiles)
14744: 
14745: =item *
14746: 
14747: removeuserfile(): removes a file that exists in userfiles
14748: 
14749:   Args:
14750:    docuname: username or courseid of destination for the file
14751:    docudom: domain of user/course of destination for the file
14752:    fname: filname to delete (including any subdirs under userfiles)
14753: 
14754: =item *
14755: 
14756: removeuploadedurl(): convience function for removeuserfile()
14757: 
14758:   Args:
14759:    url:  a full /uploaded/... url to delete
14760: 
14761: =item * 
14762: 
14763: get_portfile_permissions():
14764:   Args:
14765:     domain: domain of user or course contain the portfolio files
14766:     user: name of user or num of course contain the portfolio files
14767:   Returns:
14768:     hashref of a dump of the proper file_permissions.db
14769:    
14770: 
14771: =item * 
14772: 
14773: get_access_controls():
14774: 
14775: Args:
14776:   current_permissions: the hash ref returned from get_portfile_permissions()
14777:   group: (optional) the group you want the files associated with
14778:   file: (optional) the file you want access info on
14779: 
14780: Returns:
14781:     a hash (keys are file names) of hashes containing
14782:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14783:         values are XML containing access control settings (see below) 
14784: 
14785: Internal notes:
14786: 
14787:  access controls are stored in file_permissions.db as key=value pairs.
14788:     key -> path to file/file_name\0uniqueID:scope_end_start
14789:         where scope -> public,guest,course,group,domains or users.
14790:               end -> UNIX time for end of access (0 -> no end date)
14791:               start -> UNIX time for start of access
14792: 
14793:     value -> XML description of access control
14794:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14795:             <start></start>
14796:             <end></end>
14797: 
14798:             <password></password>  for scope type = guest
14799: 
14800:             <domain></domain>     for scope type = course or group
14801:             <number></number>
14802:             <roles id="">
14803:              <role></role>
14804:              <access></access>
14805:              <section></section>
14806:              <group></group>
14807:             </roles>
14808: 
14809:             <dom></dom>         for scope type = domains
14810: 
14811:             <users>             for scope type = users
14812:              <user>
14813:               <uname></uname>
14814:               <udom></udom>
14815:              </user>
14816:             </users>
14817:            </scope> 
14818:               
14819:  Access data is also aggregated for each file in an additional key=value pair:
14820:  key -> path to file/file_name\0accesscontrol 
14821:  value -> reference to hash
14822:           hash contains key = value pairs
14823:           where key = uniqueID:scope_end_start
14824:                 value = UNIX time record was last updated
14825: 
14826:           Used to improve speed of look-ups of access controls for each file.  
14827:  
14828:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14829: 
14830: =item *
14831: 
14832: modify_access_controls():
14833: 
14834: Modifies access controls for a portfolio file
14835: Args
14836: 1. file name
14837: 2. reference to hash of required changes,
14838: 3. domain
14839: 4. username
14840:   where domain,username are the domain of the portfolio owner 
14841:   (either a user or a course) 
14842: 
14843: Returns:
14844: 1. result of additions or updates ('ok' or 'error', with error message). 
14845: 2. result of deletions ('ok' or 'error', with error message).
14846: 3. reference to hash of any new or updated access controls.
14847: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14848:    key = integer (inbound ID)
14849:    value = uniqueID
14850: 
14851: =item *
14852: 
14853: get_timebased_id():
14854: 
14855: Attempts to get a unique timestamp-based suffix for use with items added to a
14856: course via the Course Editor (e.g., folders, composite pages,
14857: group bulletin boards).
14858: 
14859: Args: (first three required; six others optional)
14860: 
14861: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14862:    docssequence, or name of group
14863: 
14864: 2. keyid (alphanumeric): name of temporary locking key in hash,
14865:    e.g., num, boardids
14866: 
14867: 3. namespace: name of gdbm file used to store suffixes already assigned;
14868:    file will be named nohist_namespace.db
14869: 
14870: 4. cdom: domain of course; default is current course domain from %env
14871: 
14872: 5. cnum: course number; default is current course number from %env
14873: 
14874: 6. idtype: set to concat if an additional digit is to be appended to the
14875:    unix timestamp to form the suffix, if the plain timestamp is already
14876:    in use.  Default is to not do this, but simply increment the unix
14877:    timestamp by 1 until a unique key is obtained.
14878: 
14879: 7. who: holder of locking key; defaults to user:domain for user.
14880: 
14881: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14882:    retrying); default is 3.
14883: 
14884: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14885: 
14886: Returns:
14887: 
14888: 1. suffix obtained (numeric)
14889: 
14890: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14891: 
14892: 3. error: contains (localized) error message if an error occurred.
14893: 
14894: 
14895: =back
14896: 
14897: =head2 HTTP Helper Routines
14898: 
14899: =over 4
14900: 
14901: =item *
14902: 
14903: escape() : unpack non-word characters into CGI-compatible hex codes
14904: 
14905: =item *
14906: 
14907: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14908: 
14909: =back
14910: 
14911: =head1 PRIVATE SUBROUTINES
14912: 
14913: =head2 Underlying communication routines (Shouldn't call)
14914: 
14915: =over 4
14916: 
14917: =item *
14918: 
14919: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14920: 
14921: =item *
14922: 
14923: reply() : uses subreply to send a message to remote machine, logs all failures
14924: 
14925: =item *
14926: 
14927: critical() : passes a critical message to another server; if cannot
14928: get through then place message in connection buffer directory and
14929: returns con_delayed, if incapable of saving message, returns
14930: con_failed
14931: 
14932: =item *
14933: 
14934: reconlonc() : tries to reconnect lonc client processes.
14935: 
14936: =back
14937: 
14938: =head2 Resource Access Logging
14939: 
14940: =over 4
14941: 
14942: =item *
14943: 
14944: flushcourselogs() : flush (save) buffer logs and access logs
14945: 
14946: =item *
14947: 
14948: courselog($what) : save message for course in hash
14949: 
14950: =item *
14951: 
14952: courseacclog($what) : save message for course using &courselog().  Perform
14953: special processing for specific resource types (problems, exams, quizzes, etc).
14954: 
14955: =item *
14956: 
14957: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14958: as a PerlChildExitHandler
14959: 
14960: =back
14961: 
14962: =head2 Other
14963: 
14964: =over 4
14965: 
14966: =item *
14967: 
14968: symblist($mapname,%newhash) : update symbolic storage links
14969: 
14970: =back
14971: 
14972: =cut
14973: 

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